开发者

JQUERY BIND to a LABEL, and pass the name & value

开发者 https://www.devze.com 2022-12-15 12:52 出处:网络
<p id=\"noteTypebox\"> <label for=\"noteType_2\" class=\"notetypelabel\" id=\"noteType_2\" >
<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(r开发者_开发问答adioClicks)
});

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

Thanks


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.


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().


Just change to:

$(".notetypelabel").click( ....
0

精彩评论

暂无评论...
验证码 换一张
取 消