Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get option title="sample" using jquery

I'm trying to update a hidden field based on the a title attribute on a select option, I've tried the code bellow and can't seem to get it to work. Thanks for any help!

<form>
    <select id="selectbox">
        <option name="test" value="one" title="title" selected="selected">one</option>
        <option name="test2" value="two" title="title2">two</option>
    </select>
</form>
<input id="update" type="hidden" value="defaultold" />

<script>
    $('#update').val('default');
    $('#selectbox').change(function() {
        $('#update').val($(this).attr("title"));
    });
</script>
like image 979
tom Avatar asked May 07 '10 20:05

tom


People also ask

How do I get the text value of a selected option jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How can check select option selected or not in jQuery?

$("#mySelectBox option:selected"); to test if its a particular option myoption : if($("#mySelectBox option:selected").

How do I get the selected value of multiple dropdowns in jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.


1 Answers

Encapsulate that code within a $(document).ready(... block, and you need to use the option's title:

$(document).ready(function() {
    $('#update').val('default');   
    $('#selectbox').change(function() {
         $('#update').val($(this).find("option:selected").attr("title"));
    });
});

$(this) refers to the context of the select element, you can use find to get the descendant of interest which in this case is the selected option.

like image 152
karim79 Avatar answered Oct 02 '22 06:10

karim79