Pergunta

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>
Foi útil?

Solução

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.

Outras dicas

Accessing the text of selected option using jquery:

var title = $( "#myselectId option:selected" ).text();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top