Michael Sickler
Michael Sickler

Reputation: 65

Similar selects, how to know which one is changed?

I have a page where rows can be added which include drop downs (select) fields. each one of those fields is dynamically created with an id of "drop1, drop2, drop3" etc.

I'm wanting to achieve pulling some data from mysql with ajax, problem i'm having is knowing which drop down has changed to pull the data.

ive used this to know how many select fields there are currently, but don't know how to decide which one has changed. any help is appreciated.

var myCount = $("select[id^=drop]").length;

here is the row that gets added.

var n=($('.detail tr').length-0)+1;  

var tr = '<tr>'+  
'<td>'+n+'</td>'+
'<td><select id="drop'+n+'" name="prodService[]"></select></td>'+
'<td id="desc'+n+'"></td>'+ 
'<td><a href="#" class="remove">Delete</a></td>'+ 
'</tr>'; 

Upvotes: 0

Views: 50

Answers (1)

Amir Fawzy
Amir Fawzy

Reputation: 468

The whole idea around the select input it's like any input accepts all events. Any input takes click, change, input...etc let's say we have 3 select dropdown.

How to detect if any of them has changed and get the new value

$('.select-list').on('change', function(evt) {
    console.log($(this).val());   // get the select value - new value if changed
    console.log($(this).attr('id'));   // just for implementation purposes and debugging   
});

Going further you can implement something like: When the user selects an item from a dropdown, send a request to a server to get some data. You can do that with the value="" attribute, put keyword/key-trigger (just to differentiate between them) to send different request depending on what item has been selected.

$('.select-list').on('change', function(evt) {
		console.log($(this).val());   // get the select value - new value if changed
		console.log($(this).attr('id'));   // just for implementation purposes and debugging   
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select-list" name="items" id="itemsList1">
    	<option value="1">item1</option>
    	<option value="2">item2</option>
    	<option value="3">item3</option>
    	<option value="4">item4</option>
    </select>
    
    <select class="select-list" name="items" id="itemsList2">
    	<option value="1">item1</option>
    	<option value="2">item2</option>
    	<option value="3">item3</option>
    	<option value="4">item4</option>
    </select>
    
    <select class="select-list" name="items" id="itemsList3">
    	<option value="1">item1</option>
    	<option value="2">item2</option>
    	<option value="3">item3</option>
    	<option value="4">item4</option>
    </select>

Upvotes: 2

Related Questions