views:

224

answers:

3
<p id="noteTypebox">
<label for="noteType_2" class="notetypelabel" id="noteType_2" >
<input type="radio" name="noteTypeID" value="2" class="notetype">IDI</input>
</label>
</p>

Given the code above, I would like JQUERY code that Binds to the LABEL, since the INPUT box is hidden (I don't want the radio buttons on the apge).

When a user clicks on a label, it should trigger the JQUERY function and provide the value of the INPUT associated with the label. For example, if a user clicked on label for="noteType_1", it would be able to alert noteType_1 & 1

Here is my current code, I could use your help! thanks

$( document ).ready( function() { 
    $('#noteTypebox:label').click(radioClicks)
});

function radioClicks() {
    alert(input name + input value);
    return false;
};

Thanks

A: 

Just change to:

$(".notetypelabel").click( ....
menkes
AnApprentice
+1  A: 

I would do something like this:

$(document).ready(function() { 
    $('#noteTypebox label').click(radioClicks);
});

function radioClicks() {
    var input = $(this).children("input");
    alert(input.attr("name") + " " + input.val());
    return false;
};

This however relies that you always structure your HTML the same.

A far more robust way would be to do the following:

function radioClicks() {
    var label = $(this);
    var input = $("input#" + label.attr("for"));
    alert(input.attr("name") + " " + input.val());
    return false;
};

in this case the label can be anywhere in relation to the input and it will still work.

UPDATE: Have updated second code snippet to only get the radio button that is checked.

A response to the comment:

The code above looks for an input with the same id as the for attribute of the label. Seeing as you changed the id of the input, this breaks the code and makes the second example not so adequate. The first example however should work fine for you as long as the input remains a child of the label. Also, I need to mention that the for attribute on your label has become redundant with your changes since all its saying now is that the label applies to itself.

Darko Z
Both of his inputs have the same `name`.
SLaks
Thanks, have updated the code.
Darko Z
Ran into an issue and needed to change the HTML to:<label for="noteType_2" class="notetypelabel" id="noteType_2"> <input type="radio" name="noteTypeID" value="2" class="notetype">IDI</input></label>This ended up breaking the JS. By updating the 3rd line to: var input = $("label#" + label.attr("for"));I received the NAME but am no longer getting the INPUT's value, can you help me update the JS to return the VALUE, likely, replacing "input.val()"Thanks!
AnApprentice
Have updated my answer
Darko Z
+1  A: 

You need to find the input element associated with the label, like this:

var input = $('#' + $(this).attr('for'));

You can then get the name by writing input.attr('name') and the value by writing input.val().

SLaks