Reputation: 247
how to let a select trigger a javascript method when the select is being populated and set to default value?
Thanks in advance
Upvotes: 1
Views: 228
Reputation: 1983
You can use on change event to handle it .
Javacript/Jquery
function printData() {
console.log("On change of the select box your this fuction will get call");
}
$(document).ready (function () {
$('select').change(function(){
printData();
});
})
HTML
<lable>Select option.</lable>
<select>
<option value="1">Hi</option>
<option value="2">Hello</option>
<option value="3">How are you</option>
</select>
Upvotes: 0
Reputation: 1558
This can easily been done with the change event handler.
$('select').change(function(){
if ($(this).val() == 'default') {
console.log('selected default');
} else {
$('p').text($(this).val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="default"></option>
<option value="Hello World!">Hello</option>
<option value="Foo and Bar are common used example names">Foo</option>
</select>
<p>Please pick an option.</p>
Upvotes: 1