Brett
Brett

Reputation: 20049

Setting values to fields with the same name/key possible?

Ok, say I have a checkbox such as this:

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

...and 3 text fields like this:

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

I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.

So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:

// 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?

});

Upvotes: 0

Views: 70

Answers (2)

Farhan
Farhan

Reputation: 752

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);
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

// 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)
});

Upvotes: 1

Related Questions