shakked
shakked

Reputation: 811

How do you use jQuery to get the value of an input of a select form?

I set up this example code to try and track the problem in my bigger website, but I don't understand why the value keeps coming back as undefined.

<script>
    function echo(){
        value = $('input[name=select_form]').val();
        $(document).ready(function(){
                $('#test_div').append("<p>" + value + "</p>"); 
            })          
        }
</script>

</head>

<table>
    <tr>
        <td>select an option</td>
        <td><select name = "select_form">
                <option value="Alpha">Alpha</option>
                <option value="Beta">Beta</option>
             </select>
        </td>
    </tr>
</table>

<input type='button' value='echo' name='submitbtn' onclick='echo()' />

<div id = "test_div"> </div>

Upvotes: 0

Views: 52

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Your selector is wrong, you are targeting a select element, not an input element

value = $('select[name=select_form]').val();

Demo: Fiddle

Note: also there is no need for dom ready handler - if you want to use it then use a proper jQuery event handler inside a dom ready handler

<input type='button' value='echo' name='submitbtn' />

then

jQuery(function () {
    $('input[name="submitbtn"]').click(function () {
        var value = $('select[name=select_form]').val();
        $('#test_div').append("<p>" + value + "</p>");
    })
})

Demo: Fiddle

Upvotes: 4

Rocky Pulley
Rocky Pulley

Reputation: 23301

I think $('select[name=select_form] option:selected').text() will work.

Upvotes: 0

Related Questions