Bolli Bolli - 7 months ago 15
Javascript Question

jquery .on(change) on specific ID

I have many different dropdowns on the same page and wan't to do an AJAX request when on of them changes.

If I do it this way, it works:

$(document).on('change', '#changeresponsibleuser', function(){
var user = $(this).val();
var partnerid = $(this).attr('name');
$.ajax({
type: "POST",
url: "resources/dialogs/editResponsibleUser.php",
data: {user: user,
partnerid: partnerid},
success: function(msg){
$('.productmessage').html(msg).hide().fadeIn(500).fadeOut(4000);

},
});
});


But this trickers on all dropdown boxes I have on the page. I wan't to do something like this:

$(document).ready(function(){
$("#changeresponsibleuser").on('change',function(){
var user = $(this).val();
var partnerid = $(this).attr('name');
$.ajax({
type: "POST",
url: "resources/dialogs/editResponsibleUser.php",
data: {user: user,
partnerid: partnerid},
success: function(msg){
$('.productmessage').html(msg).hide().fadeIn(500).fadeOut(4000);

},
});

});
});


So it ONLY listens to the dropdown with that exact ID. But it does not work, the on change event is not triggered.

How can I trigger the event only when #changeresponsibleuser changes?

The markup looks like this:

<select id="changeresponsibleuser" name="2" class="responsible2 form-control form-group">

<option name="user" value="36" selected="selected">One user</option>
<option name="user" value="41">Another user</option>
<option name="user" value="40">yet another user</option>
</select>


Thanks in advance!

Answer

$(function(){
 $("#changeresponsibleuser").on('change', function(){
   alert("Works");
 })
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="changeresponsibleuser" name="2" class="responsible2 form-control form-group">

<option name="user" value="36" selected="selected">One user</option>
<option name="user" value="41">Another user</option>
<option name="user" value="40">yet another user</option>
</select>

It works. How do you say it is not working?

But this trickers on all dropdown boxes I have on the page

No. You have to use class name instead id. It seems you are using duplicate ids. So it is triggering on all select dropdowns which has duplicate id.

$(document).on('change', '.changeresponsibleuser',function(){
   alert("Works");
 });

It will trigger on all drop down changes which has class changeresponsibleuser