Paengski
Paengski

Reputation: 349

Change the value of array field using jQuery

<input type="text" name="fruits[]" value="Apple">
<input type="text" name="fruits[]" value="Banana">
<input type="text" name="fruits[]" value="Orange">

My question is how to change the value of "Orange" to "Grapes" using jquery? The below code is not working.

<script>
    $("input[name='fruits[2]']").val("Grapes"); 
</script>

Thanks in advance.

Upvotes: 0

Views: 118

Answers (3)

Tarun Singhal
Tarun Singhal

Reputation: 1007

Try this:

$("input[value='Orange']").val('Grapes');

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

  1. The code needs to be executed in dom ready handler
  2. your selector input[name='fruits[2]'] looks for input elements with name fruits[2] instead of with name fruits[] and is at the 3rd index

So

jQuery(function () {
    $("input[name='fruits[]']:eq(2)").val("Grapes");
})

Demo: Fiddle

Upvotes: 1

PSL
PSL

Reputation: 123739

Try using eq(index):

$(function(){ //<-- Add this in DOM ready wrapper as well
   $("input[name='fruits[]']").eq(2).val("Grapes"); 
});

Fiddle

Upvotes: 1

Related Questions