1

I have two dropdown lists containing customers info. Using PHP for loop, I have allowed to enter 5 customers details at a time.

for($i=1; $i<6; $i++)
{
   echo "<tr><td><select id=\"customer_" . $i . "_class\"></select></td>";
   echo "<td><select id=\"customer_" . $i . "_age\"></select></td></tr>";
}

Now I want to execute a jQuery function in such a way that if, for example, customer_2_class changes, it executes some function to its corresponding customer_2_age.

$("#customer_?_clas").change(function()
{
   //some function to execute on corresponding customer_?_age
});
0

3 Answers 3

3

Add class to your <select> and move the id to another attribute, like data:

echo "<tr>";
echo "<td><select class=\"customer_class\" data-id=\"$i\"></select></td>";
echo "<td><select class=\"customer_age\" data-id=\"$i\"></select></td>";
echo "</tr>";

And in your javascript:

$('.customer_class').change(function() {
  var id = $(this).attr('data-id');
  // process customer_class with this id
});
Sign up to request clarification or add additional context in comments.

4 Comments

In addition to the data-id attribute, adding the id attribute wouldn't hurt here since the id selector is much faster than the regular attribute selector.
I like the use of the class attributes (the only reason I didn't suggest it in my answer is that you already had), but I'd probably do it without the data-id attribute, instead finding the matching age select with something like $(this).closest('tr').find('.customer_age').
Thanks guys, Now you have the data-id in var id. How do I execute a function for customer_class with that specific data-id? Sorry for this newbie question..
@AsadoQureshi You should create a new question with more HTML/JS code and explain what you want to achieve.
0

You could use the attribute ends-with selector:

$('select[id$="_class"]').change(function() {

It might be worth browsing through the full list of jQuery selectors.

Comments

0
$('select').
   filter(function() { 
       return /^customer_[0-9]_class$/.test(this.id); // filter on select 
                                                      // based on id format
   }) 
   . change(function() {                              // binding change 
                                                      // to filtered select
       var num = this.id.match(/\d/)[0];              // get numerical value 
                                                      // of select box on change

       $('#customer_' + num + '_age')                 // point to target select 
            .css('background', '#f00');               // do something
   });

Working sample

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.