可以将值设置为具有相同名称/键的字段吗?

时间:2013-08-14 18:18:44

标签: javascript jquery

好的,我说有一个复选框,如:

<input type="checkbox" value="1" class="discount_select" name="select[101132]">

...和3个这样的文字字段:

<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">

我正在运行一些代码,如果选中该复选框,将更新文本字段值,但是我不确定是否或如何定位正确的字段,因为它们都有不同的ID。

所以我基本上有这个代码循环选中复选框,但不知道如何更新正确的文本字段:

// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();

$('.discount_select:checked').each(function() {

  // How can I target the correct fields/ID's here?

});

2 个答案:

答案 0 :(得分:1)

尝试

// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();

$('.discount_select:checked').each(function() {
    var num = this.name.substring(7, this.name.length - 1);
    $('input[name="start[' + num + ']"]').val(start)
    $('input[name="end[' + num + ']"]').val(end)
    $('input[name="discount[' + num + ']"]').val(discount)
});

答案 1 :(得分:0)

Change the name and ids of your fields to make it simpler

<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">

<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">

Then:

    var discount = $('#apply_discount').val();
    var start = $('#apply_start_date').val();
    var end = $('#apply_end_date').val();

$('.discount_select:checked').each(function() {
    var select_id = this.attr("id");
    $('[name=start_'+select_id+']').val(start);
    $('[name=end_'+select_id+']').val(end);
    $('[name=discount_'+select_id+']').val(discount);
});