0

I have generated multiple text boxes using PHP with name="student[<?php echo $StudentID ; ?>]".

Now on a button click i want to change the value of all these text boxes using jquery.

How do i do this ? Please help.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
sqlchild
  • 8,754
  • 28
  • 105
  • 167

3 Answers3

1

You can use the Attribute Starts With selector, to look for student[ at the beginning of the name attribute:

$('input[name^="student["]').val('the new value');

It's probably unnecessary to include the [ at the end, and name^="student" will be sufficient, assuming you don't have other inputs with names like student_name or the like.

// If no conflicting named inputs, use
$('input[name^="student"]').val('the new value');
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • You probably better add `'` around your selectors – ZenMaster Nov 04 '11 at 18:28
  • @Michael : but sir, if i have some other elements also starting with name 'student...' , then what would i do? shall i have to use a foreach loop to loop all the Student IDs and then do this :------------: $('input[name="student[]").val('new value'); – sqlchild Nov 04 '11 at 18:52
  • 1
    @sqlchild Then my first example should work, using the partial selector `student[` – Michael Berkowski Nov 04 '11 at 19:03
1

HTML

<input type="text" name="student[]"></input>
<input type="text" name="student[]"></input>
<input type="text" name="student[]"></input>

<button id="button">Change</button>

JavaScript

$('#button').click(function() {
    $('input[name^="student"]').val('some value ');
});

JSFiddle

ZenMaster
  • 12,363
  • 5
  • 36
  • 59
1

You can also simply add a class that is unique to all of those text boxes (i.e. changableTextBox) and then select it with that and change them all at once. It's also helpful for the future if you need to adjust some styling on all of them at once. Just declare that class in CSS and you're styling.

<input type="text" class="changeableStudentTextBox" id="student[11]" />
<input type="text" class="changeableStudentTextBox" id="student[23]" />
<input type="text" class="changeableStudentTextBox" id="student[45]" />
<input type="text" class="changeableStudentTextBox" id="student[66]" />

<script type="text/javascript">
     $('#button').click( function() { $('.changeableStudentTextBox').val('hi!'); });
</script>
tigertrussell
  • 521
  • 2
  • 13