0

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

5
  • 3
    Where's the element with id placeholder ? Commented May 4, 2013 at 14:46
  • Works fine here...jsfiddle.net/HybkH/4 Commented May 4, 2013 at 14:47
  • Apologies - question edited to accurately reflect actual DOM tree. Commented May 4, 2013 at 14:49
  • 2
    @verism Urm.. your code already works - jsfiddle.net/HybkH/3 Commented May 4, 2013 at 14:50
  • @Zenith - you're right, but somehow it wasn't functioning in my problem code. For some reason .val() did the trick. Commented May 4, 2013 at 15:11

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

or just #product-options :checked. Only input elements can be :checked after all ;)
That's good to know, but I'm not looking for the checked value in this particular instance.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.