0

フォーム要素を動的に追加するフォームがあります。追加する要素は、テキストフィールドとラジオボタンです。ここで、選択したラジオボタンの値を、ユーザーが隣接する入力ボックスに入力したテキストにします。これが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を共有しました。問題は、入力テキストからラジオボタンの値に渡される値を取得できないことです。

4

1 に答える 1

1

問題は、ラジオボタンがページに存在する前に、ラジオボタンを選択し、イベントハンドラーをアタッチしていることです。

on将来追加されるラジオボタンのイベントを委任するために使用することをお勧めします。

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

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

更新された例:http: //jsfiddle.net/Pyj7K/2/

于 2013-03-25T14:14:04.393 に答える