views:

37

answers:

2

I'm trying to select dynamic ids when a user types something into the input fields. My app spits out the input fields in the following format:

<input id="student_1_first_name" />
<input id="student_1_last_name" />

<input id="student_2_first_name" />
<input id="student_2_last_name" />

<input id="student_3_first_name" />
<input id="student_3_last_name" />

etc.

For example, I tried doing this to select the end of the id string:

<script type="text/javascript">
  $(document).ready(
  function (){
    $("input[id$=_first_name]").bind("keyup", run_some_function_here);
    run_some_function_here();
    $("input[id$=_last_name]").bind("keyup", run_some_function_here);
    run_some_function_here();
  }
);
</script>

When I do that, Jquery can't seem to select the input ids, so the functions don't run. Do you have any ideas on how I can select the ids correctly?

+2  A: 

$("input[id$=_first_name]") looks like it should work.

Does this give them red borders?

$("input[id$=_first_name]").css({ border: '2px solid red' });

If it does, then the function is probably not being called properly. Are you using anonymous functions or passing a reference to an existing function?

Update

Does this work as intended?

$("input[id$=_first_name]")
    .bind("keyup", function() {   run_some_function_here();   });
alex
Thanks for the very quick response Alex. I'm passing a reference to an existing function. Your code does give them red borders, so I think it's an error with how I'm passing it to the function. I'll continue working at it now that I know where to look. Thank you!
sjsc
Thank you Alex! It looks like it's working now. Thank you so much :)
sjsc
+3  A: 

assign class to each input e.g <input id="student_1_first_name" class="input-class" />

then try this

$(function() {
   $('input.input-class').each(function() {
       var id = $(this).attr('id');
   });
});
Puaka
Thanks Puaka. Great suggestion. I'll try that too. Thank you so much.
sjsc