Is it possible to trigger a change event on a select field when the selectedIndex or val is set with jQuery?
I've tried it and it doesn't seem to work. I'm attempting to replace a select field with one of my own design. The issue is if i attached a change event to a select field, when the index is changed it needs to fire that event.
Is there a way to do this?
var a = $("a");
$("a").on("click", function() {
$("#selectList")[0].selectedIndex = a.index($(this));
//now fire event
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Trigger 1</a>
<a href="#">Trigger 2</a>
<a href="#">Trigger 3</a>
<select id="selectList">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
EDIT: @xSaint32 answered this, by using jQuery's trigger method.
@xSaint32 answered this, by using jQuery's trigger method.
var a = $("a"),
select = $("#selectList");
$("a").on("click", function() {
select[0].selectedIndex = a.index($(this));
select.trigger( "change" );
return false;
});
select.on("change", function() {
alert("My index changed");
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Trigger 1</a>
<a href="#">Trigger 2</a>
<a href="#">Trigger 3</a>
<select id="selectList">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>