I have a select box. The selected option is sent with ajax to a server side script. This works well.
the select box
<select id="main_select">
<option selected="selected">50</option>
<option value="40">40</option>
<option value="30">30</option>
<!-- other options -->
</select>
How can I extend the .change function that the default value <option selected="selected">50</option>
is automatically send with the page load.
script:
$(document).ready(function () {
$('#main_select').change(function () {
$.ajax({
url: "itemscript.php",
type: "post",
data: {option: $(this).find("option:selected").val()},
success: function(data){
$("#details").html(data);
}
});
});
});
2
Answers
Just trigger the
change
event when the page is loaded.Also, you can use
$(this).val()
, that gets the value of the selected option.Why not extract the functionality to a seperate function? This helps to avoid hacks like triggering a
change
manually – if you had multiple listeners for such a change event, all would fire, and this might not be what you expect to happen 😉