views:

1073

answers:

4

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>
A: 

The val() only works on HTML input elements (input, select, textarea, button). You need to move the id="optElem" to the <select> element and it will work.

BalusC
A: 

Try to change row 4 to this:

jQuery('#optElem select').change(function(){

This will make you work on the select element inside the #optElement.

(also see the answer by BalusC, you need to work on a select element, not a span)

Emil Vikström
+2  A: 

It's because optElem is a <span>, not a <select>. You are attaching the change event to the span, and as a result, this refers to the span when you are inside the function attached to change.

Since this is 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 the select rather than a span.

zombat
(*Blushing*) - I can't believe I missed that. Thanks
Stick it to THE MAN
A: 

Yes! you need to focus on the "Select" element
by doing this!

jQuery('#optElem select:first-child').change(function(){  
            // your codes here
});
joberror