verism
verism

Reputation: 1164

How to get input value attribute with jquery

I'm trying to target value of the value attribute in the input field that immediately precedes the label with a class="selected"

<div id="placeholder">
<div id="product-options" class="options">

    <input checked="checked" id="option_33295465" name="cart[add][id]" type="radio" value="33295465" class="input_hidden"/>
    <label for="option_33295465" class="selected">
        <span>option1</span>
    </label>

    <input id="option_33544344" name="cart[add][id]" type="radio" value="33544344" class="input_hidden"/>
    <label for="option_33544344">
        <span>option2</span>
    </label>

</div>
</div>

At the moment I'm just trying to log the value, but I get undefined each time.

$('body').on('click','#button1',function(e){
    e.preventDefault();
    $item = jQ('#placeholder').find('.selected').prev().attr('value');
    console.log($item); // Logs "undefined"
});

fiddle

Upvotes: 0

Views: 150

Answers (2)

hannenz
hannenz

Reputation: 513

jQuery has a seperate method for retrieving the value of any form input: val()

$item = jQ('#placeholder').find('.selected').prev().val();

should do the trick, See also here

Upvotes: 0

Turnerj
Turnerj

Reputation: 4278

What you are looking for is the .val function on the element.

The other thing is that your jQuery code to get the option/radio button value can be simplified to:

$('#product-options input:checked').val()

Upvotes: 1

Related Questions