Reputation: 93
I want to trigger on change event when the page load I tried to do $("#formtype").change();
but it doesn't work
<div class="form-group">
<select name="form" id="formtype" class="form-control">
<option value="A">Form A</option>
<option value="B">Form b</option>
</select>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$('#formtype').on('change', function () {
// alert( this.value ); // or $(this).val()
if(this.value == "A") {
$('#form1').show();
$('#form2').hide();
} else {
$('#form1').hide();
$('#form2').show();
}
});
</script>
Upvotes: 1
Views: 13308
Reputation: 908
try to execute this code inside the document ready event's function:
$("#formtype").trigger('change');
Upvotes: 2
Reputation: 207501
You can do it directly in the binding of the events
$('#formtype').on('change', function () { }).trigger("change");
or
$('#formtype').on('change', function () { }).change();
Upvotes: 0
Reputation: 2815
Why not put it the code you want to run in a function, then call that function? Something like this will work:
$('#formtype').on('change', function() {
doStuff();
});
function doStuff() {
if($('#formtype').val() == "A") {
$('#form1').show();
$('#form2').hide();
} else {
$('#form1').hide();
$('#form2').show();
}
}
$(document).ready(function() {
doStuff();
})
See it working here: https://jsfiddle.net/5jLx6q8b/
Upvotes: 2
Reputation: 218798
Don't try to trick the DOM into thinking that an event has occurred. If you want to execute code when the page loads, just execute it. Something like this:
// define the function
var toggleElements = function () {
if($('#formtype').val() == "A") {
$('#form1').show();
$('#form2').hide();
} else {
$('#form1').hide();
$('#form2').show();
}
};
// set the handler
$('#formtype').on('change', toggleElements);
// execute the function when the page loads
$(document).ready(toggleElements);
Upvotes: 5