I have a function to detect the value and do some stuff (not important for the question). I am unable to get the value when the page is ready, but when selecting a value, it can find the value. How can I pass this
to the function?
<select id="select">
<option value="choise1">choise1</option>
<option value="choise2">choise2</option>
<option value="choise3" selected="selected">choise3</option>
<option value="choise4">choise4</option>
</select>
function check_select() {
alert( "!" + $( this ).val() + "!" );
}
$('#select').on( 'change', check_select );
// Why is value not set?
$('#select').ready( check_select );
Example: http://jsfiddle.net/7en4op4j/
select
elements do not raise a ready
event. To do what you require you would need to just call the check_select()
function in the document.ready
handler itself. You would also need to change the scope of this
within the function due to the logic in the function. To do that you can use $.proxy()
:
$(function() {
$('#select').on('change', check_select); // on change
$.proxy(check_select, $('#select'))(); // on load
});
Your fiddle is set to onDomReady
, if you change this to No wrap, in head
then you can take advantage of jQuery's handling of dom ready.
Thereafter, what you want to do is call your method with the context of this
set to the select element in question:
check_select.call($('#select')[0])
Updated fiddle: http://jsfiddle.net/7en4op4j/2/
Modified your code a bit. Used $(document).ready()
instead:
http://jsfiddle.net/7en4op4j/5/
function check_select(obj) {
alert( "!" + $( obj ).val() + "!" );
}
$('#select').on( 'change', function(){
check_select($(this));
} );
// Why is value not set?
$(document).ready( function(){
check_select($("#select"))
});
On load of the function your trying to read the value with 'this' which is the object of the document. instead of using 'this' select id.
Fiddle : http://jsfiddle.net/7en4op4j/1/
function check_select() {
alert( "!" + $( '#select' ).val() + "!" );
}
there is not ready event for dom elements, at least i have never used it in that way. You can use $(document).on('ready',callback)
to execute somethin(code) when the all the DOM is ready. That is why it does not work correct.
instead of this just use $(document).on('ready',function)
, and keep the check_select function for the change event.
function check_select() {
alert( "!" + $( this ).val() + "!" );
}
$('#select').on( 'change', check_select );
$(document).on('ready',function(){
alert($('select').val());
})
live jsfiddle : http://jsfiddle.net/tornado1979/7en4op4j/7/
hope helps,good luck
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.