Reputation: 67
I am new in jquery. I want to make single Onchange for multiple dropdowns. I've tried with for loop but didn't work. I've been searching but didn't find the solution. How to make this code look simple? Thanks for your help
$(document).on('change', '#medicine1', function(){
var medicine=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('example/product')?>",
dataType : "JSON",
data : {medicine: medicine},
cache:false,
success: function(data){
$.each(data,function(medicine, stock, unit){
$('#stock1').val(data.stock);
$('#unit1').val(data.unit);
});
}
});
return false;
});
$(document).on('change', '#medicine2', function(){
var medicine=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('example/product')?>",
dataType : "JSON",
data : {medicine: medicine},
cache:false,
success: function(data){
$.each(data,function(medicine, stock, unit){
$('#stock2').val(data.stock);
$('#unit2').val(data.unit);
});
}
});
return false;
});
Upvotes: 1
Views: 1778
Reputation: 337656
The technique you're looking for is called Don't Repeat Yourself, or DRY. To achieve this you can use common classes on the elements which you assign a single event handler to. Then you can use the this
keyword within the event handler to reference the single element which raised the event.
The only logical difference I can see is the id
attributes of the elements which you affect in the callback of the AJAX request.
In this case it would be preferable to use DOM traversal to find the related elements. That is methods such as closest()
, find()
, siblings()
etc. If, for whatever reason, that's not possible, then you can use data
attributes on the select
to target them. As you haven't provided the HTML to see how to traverse the DOM here's an example of the latter:
<select class="medicine" data-stock="#stock1" data-unit="#unit1">
<option>Foo</option>
<option>Bar</option>
</select>
<select class="medicine" data-stock="#stock2" data-unit="#unit2">
<option>Fizz</option>
<option>Buzz</option>
</select>
$(document).on('change', '.medicine', function() {
var $select = $(this);
var medicine = $select.val();
$.ajax({
type: "POST",
url: "<?php echo base_url('example/product')?>",
dataType: "JSON",
data: { medicine: medicine },
cache: false,
success: function(data) {
$.each(data, function(medicine, stock, unit) {
$($select.data('stock')).val(data.stock);
$($select.data('unit')).val(data.unit);
});
}
});
});
It's also worth noting that repeatedly setting the val()
of a single element in a loop is a little odd. It will only ever show the value of the last item in the iteration.
Upvotes: 1