单击 javascript jquery 单选按钮

我有2个单选按钮和 jquery 运行。

<input type="radio" name="lom" value="1" checked> first
<input type="radio" name="lom" value="2"> second

现在,通过一个按钮,我可以设置 onClick 来运行一个函数。当我点击其中一个单选按钮时,如何让它运行一个函数?

323733 次浏览

You can use .change for what you want

$("input[@name='lom']").change(function(){
// Do something interesting here
});

as of jQuery 1.3

you no longer need the '@'. Correct way to select is:

$("input[name='lom']")

this should be good

$(document).ready(function() {
$('input:radio').change(function() {
alert('ole');
});
});

If you have your radios in a container with id = radioButtonContainerId you can still use onClick and then check which one is selected and accordingly run some functions:

$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});

it is always good to restrict the DOM search. so better to use a parent also, so that the entire DOM won't be traversed.

IT IS VERY FAST

<div id="radioBtnDiv">
<input name="myButton" type="radio" class="radioClass" value="manual" checked="checked"/>
<input name="myButton" type="radio" class="radioClass" value="auto" checked="checked"/>
</div>






$("input[name='myButton']",$('#radioBtnDiv')).change(
function(e)
{
// your stuffs go here
});

There are several ways to do this. Having a container around the radio buttons is highly recommended regardless, but you can also put a class directly on the buttons. With this HTML:

<ul id="shapeList" class="radioList">
<li><label>Shape:</label></li>
<li><input id="shapeList_0" class="shapeButton" type="radio" value="Circular" name="shapeList" /><label for="shapeList_0">Circular</label></li>
<li><input id="shapeList_1" class="shapeButton" type="radio" value="Rectangular" name="shapeList" /><label for="shapeList_1">Rectangular</label></li>
</ul>

you can select by class:

$(".shapeButton").click(SetShape);

or select by container ID:

$("#shapeList").click(SetShape);

In either case, the event will trigger on clicking either the radio button or the label for it, though oddly in the latter case (Selecting by "#shapeList"), clicking on the label will trigger the click function twice for some reason, at least in FireFox; selecting by class won't do that.

SetShape is a function, and looks like this:

function SetShape() {
var Shape = $('.shapeButton:checked').val();
//dostuff
}

This way, you can have labels on your buttons, and can have multiple radio button lists on the same page that do different things. You can even have each individual button in the same list do different things by setting up different behavior in SetShape() based on the button's value.

<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>


$("input[name='radio']:checked").val()