I have the following script at the end of my page:
<script type="text/javascript">
jQuery.noConflict();
jQuery(function() {
jQuery('#optElem').change(function(){
jQuery.post('http://example.com', { 'id1': 1, id2 : jQuery(this).val() },
function(data){
jQuery('#abc').html(data.payload);
jQuery('#abc').effect("highlight", {}, 3000);
}, "json");
});
});
</script>
I have an option select field with id ‘optElem’. The code above is supposed to be triggered on the change event, and also I want to pass the value of the selected option to the callback handler.
The change event is correctly being triggered and captured by jQuery, however, I am getting an empty value for id2 (this is supposed to be the value of the selected item).
I am using JQuery(this).val() – but that is suprisingly, returning a blank value – anyone knows why?
The option select field in the HTML looks likes this:
<div>
<div>
<span id="yearElem">Year: </span><span id="optElem">
<select>
<option value="2010">2010</option>
<option value="2009">2009</option>
</select>
</span>
</div>
</div>
It’s because
optElemis a<span>, not a<select>. You are attaching the change event to the span, and as a result,thisrefers to the span when you are inside the function attached to change.Since
thisis the span, it doesn’t have a value associated with it.Your best bet is to give the
<select>an id, and attach the change function to it instead. It makes a lot more sense to have the change event be associated with theselectrather than aspan.