2011-06-17 28 views
0

值有一種簡單的方式在複製值到其他區域jquery的複製到其它區域

即,如果我有2或3的選擇菜單或其它形式的字段。

<select id=first> 
<option>1</option> 
<option>2</option> 
</select> 

<select id=second> 
<option>3</option> 
<option>4</option> 
</select> 

<div id=firstvalue></div> 
<div id=secondvalue></div> 

如果我想的div HTML自動顯示選擇框的值,我會做一段代碼變更或者組件上?

感謝

回答

1

如果你想的div自動顯示任何選擇框,您可以使用所選值以下的jQuery:

$('#first').change(function(){ 
/* target the first selectbox with id #first and bind a change event to it */ 

    $('#firstvalue').html($(this).val()); 
    /* set the html of the div with id #firstvalue to the selected option*/ 

}); 

/* the same for the second selectbox */ 
$('#second').change(function(){ 

    $('#secondvalue').html($(this).val()); 

}); 

我會建議雖然改變你的HTML,使被處理的selectboxes具有相同並將其目標存儲在data屬性中。像這樣:

HTML

<select class="show_val" data-target="#value_1"> 
    <option>1</option> 
    <option>2</option> 
</select> 

<div id="value_1"></div> 

jQuery的

$('.show_val').change(function(){ 

    $($(this).data('target')).html($(this).val()); 

} 

這樣,您就可以使用相同的jQuery的事件對所有selectboxes。

+1

那麼,如果你只是*寫*給他/她...... ;-) – 2011-06-17 12:18:41

+1

我想我是其中一個壞教師:(現在增加了一些解釋,所以它實際上教了一些東西 – Kokos 2011-06-17 12:19:13

1

你會通過changebind功能使用上的選擇框change事件,在事件處理程序,你會打電話的htmltext功能設置文本在相關div上,通過val(您的option元素不具有value屬性,因此val將代替他們的文本)獲取所選選項的值。在這兩種情況下,都可以通過$ (or jQuery)函數傳遞給第一個選擇框的CSS選擇器(例如,$("#first"))來查找元素。

0

你可以做這樣的事情,所以你就不必編寫代碼爲每個選擇/ DIV:

$('select').change(function() { 
    $('div[id^="' + this.id + '"]').text($(this).val()); 
}); 

JSFiddle Example

0

如果您使用綁定到視圖/頁面的JavaScript支持對象,則還可以檢出knockout.js並實施MVVM(模型 - 視圖 - 視圖 - 模型)模式。

相關問題