通过jquery将单选按钮的值设置为距离最近的输入文本的文本

Set the value of a radio button to be the text from the closest input text via jquery

本文关键字:文本 距离 输入 最近 jquery 单选按钮 通过 设置      更新时间:2023-09-26

我有一个动态添加表单元素的表单。我要添加的元素是一个文本字段和一个单选按钮。现在,我希望所选单选按钮的值是用户在相邻输入框中键入的文本。这是JS:

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。问题是我无法获得从输入文本传递到单选按钮值的值。

问题是,在页面上存在单选按钮之前,您选择了单选按钮并附加了事件处理程序。

我建议使用on来为将来添加的单选按钮委派事件:

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

更新的例子: http://jsfiddle.net/Pyj7K/2/