0

The following event only fires when the first drop-down with the name merchant category is changed (different option selected). I need it to happen for any select element with this name. I thought this would be the behaviour of the selector below. What am I doing wrong ?

$('select[name=merchant-category]').change(function(){ 
    console.log('called');
});
Andy Fleming
  • 6,734
  • 5
  • 29
  • 52
madhukar93
  • 545
  • 5
  • 19

2 Answers2

0

Try this:

$(document).on('change', 'select[name="merchant-category"]',function() { 
    console.log('called');
});

By using the .on( syntax with a selector, you are able to catch dynamically created elements as well.

Regardless $('select[name="merchant-category"]') should return multiple elements, not just the first. If it isn't, double-check for typos in your code.

http://jsfiddle.net/vysft3go/

$(function() {
    
    $(document).on('change', 'select[name="merchant-category"]', function() {
    
        var notification = $('<p>').text($(this).attr('id') + ' changed!');
        
        $('#updates').append(notification);
        
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<form>
    
    <select name="merchant-category" id="select1">
        <option>1</option>
        <option>2</option>
    </select>
    
    <select name="merchant-category" id="select2">
        <option>1</option>
        <option>2</option>
    </select>

    
</form>

<div id="updates"></div>
Andy Fleming
  • 6,734
  • 5
  • 29
  • 52
  • will try and let you know – madhukar93 Mar 04 '15 at 04:24
  • thanks, that worked, can you tell me why (I was adding the other select elements dynamically) ? I was using the previous piece of code inside $(document).ready().. So, was it not binding the event listener to the dom element ? Will it have worked had I put it outside $(document).ready() ? – madhukar93 Mar 04 '15 at 04:29
  • `$(document).ready(...` just runs code when the DOM is ready. However, if you add a new element after the page has already loaded, your selector won't catch that new incoming element. When you use the approach I explained you are saying "listen to the `document` for any element that matches `select[name="merchant-category"]`" even if it is added later on. – Andy Fleming Mar 04 '15 at 05:12
-2

Use each() for selecting multiple elements in jQuery.

Attempt1:

$.each('select[name=merchant-category]').change(function(){ 
        console.log('called');
    });

Attempt2:

$('select[name=merchant-category]').each(change(function(){ 
        console.log('called');
    });
Ataboy Josef
  • 1,855
  • 2
  • 18
  • 27
  • This won't do anything different, jQuery already uses `each` internally to add the event handler to the collection. If OP code doesn't work, this won't either – charlietfl Mar 04 '15 at 04:14