1

I have an array of drop-downs in a page, one for each row in a list of records. I need to update a DIV's content in the row of the drop-down that triggers each change event.

Something like this:

<div class="price"></div>

<select id="plan[]" name="plan[]" class="sel">
  <option value="0" selected="selected">None</option>
  <option value="1">One</option>
  <option value="2">Two</option>
</select>   


$(function() {
    $('#plan').change(function(){
        $(this).prevAll('.price:first').html('foo bar');
    });
});

The change event never fires, what am I missing? Here's a fiddle to test

2
  • I'm assuming you've set name="plan[]" because it will eventually be submitted to a PHP script and needs to be an array. You don't have to set id="plan[]" as PHP will not use it. Just set id="plan" and your jQuery will work fine. Commented Jan 16, 2013 at 15:48
  • Yes, I need to submit it to a PHP script. So I can leave id="plan" and name="plan[]"? Didn't know that to be honest... Thanks Commented Jan 16, 2013 at 15:51

3 Answers 3

3

Try using startswith wild card with id selector.

Live Demo

$(function() {
    $('[id^=plan]').change(function(){
        $('.price:first').html('foo bar');
    });
});

If you have single item and do not need wild card you can do it with id selector like this.

Live Demo

$(function () {
  $('[id="plan[]"]').change(function () {
    $(this).prev('.price').html('foo bar');
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

the id of your element is plan[] and not plan so the event callback is registered to no object.

Comments

0

The id isn't plan it's plan[]. $("#plan[]") should work as the selector, but it also seems like a mistake to me. You probably want to change it to something else. It also implies that there are multiple plan[] id elements on the page, which is invalid.

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.