2013-03-25 20 views
0

我有一個表單,可以動態添加表單元素。我添加的元素是一個文本字段和一個單選按鈕。現在,我希望所選單選按鈕的值是用戶在相鄰輸入框中鍵入的文本。這裏是JS:將單選按鈕的值設置爲jquery中最接近輸入文本的文本

var $node = ""; 
var varCount=0; 

$('body').on('click', '.removeVar', function(){   
    $(this).parent().remove(); 
    varCount--; 
}); 
$('#addfld').on('click', function(){ 
    varCount++; 
    $node = '<label for="losfldlbl[]">Field Name '+varCount+': </label>' + 
      '<input type="text" name="losfldlbl[]" id="losfldlbl[]" title="Custom field name cannot be blank" required=true placeholder="Field name'+varCount+'"/>'+ 
      'Is this the value field? &nbsp;<input type="radio" name="losvaluefld[]" id="losvaluefld[]" value=false />&nbsp;&nbsp;'+ 
      '<span class="removeVar label label-important"><a id="removeFld" href="#" title="Click here to remove this field"><i class="icon-minus icon-white"></i></a></span>'; 

    $(this).parent().before($node); 
}); 
$('input:radio').click(function() { 
    $(this).attr('value', $(this).prev().attr("value")); 
    alert($(this).val()); 
}); 

,這裏是我的HTML:

<form id='myForm'> 
click on the yellow button custom fields &nbsp;&nbsp;&nbsp;<span class='label label-warning'><a id='addfld' href='#' title='Click here to add a new field'><i class='icon-plus icon-white'></i></a></span>&nbsp;  
</form> 

我共享了JsFiddle here。問題是我無法將從輸入文本傳遞的值傳遞給單選按鈕的值。

+0

你爲什麼不能等到用戶完成添加元素然後抓住一切,然後呢? – jmm 2013-03-25 22:12:45

回答

1

問題在於,您選擇單選按鈕並在頁面上存在單選按鈕之前附加事件處理程序。

我推薦使用on委派爲將來添加單選按鈕事件:

$(document.body).on('click', 'input:radio', function() { 
    $(this).attr('value', $(this).prev().attr("value")); 

    alert($(this).val()); 
}); 

更新例如:http://jsfiddle.net/Pyj7K/2/

+0

感謝您的回答,如果用戶在打字之前決定點擊單選按鈕,我們仍然可以將文本傳遞給單選按鈕的值 – indago 2013-03-25 14:20:27

+0

在這種情況下,它是空字符串(''''),除非我誤解了 – 2013-03-25 14:22:33

+0

你誤解了,我們可以在輸入字段上添加一個處理程序嗎?這樣當用戶在輸入文字之前點擊收音機時,我們可以避免使用空字符串? – indago 2013-03-25 14:27:45

相關問題