I have HTML like this:
<input type="radio" name="v" value="1"> 1<br>
<input type="radio" name="v" value="2"> 2<br>
<input type="radio" name="v" value="3" checked> 3<br>
I want to know how to monitor all of those radio buttons. I could have many more than 3.
One thing I considered is to have an onclick
function for al开发者_JAVA技巧l of them. Is that the right way, or is there a neater way to register a common javascript function when the radio button set has changed?
In addition to Markandey's comment: if you are using jquery, you can use attribute selectors instead of classnames without too much hassle so that you have minimal code.
$("input[name=v]").click(mycallback);
In the mycallback function, 'this' will refer to the element that was clicked.
e.g.
mycallback = function(){
alert($(this).val());
};
Putting an onclick attribute on each element creates a maintenance headache. It also prevents you from treating HTML and JavaScript as separate layers - a data layer and a behaviour layer - in the same way that CSS is your presentation layer.
Listening for events is a more mature way of developing JavaScript. Initially it takes a bit of getting used to (as it is no longer obvious from the element alone that some functionality will get triggered when you click on it) but you soon find your way around that by organising and commenting your code better.
Edited because I saw I hadn't turned the 'this' into a jquery object, and when you are in the callback 'this' is the native DOM object so .val() wouldn't work.
<input class="someclass" type="radio" name="v" value="1"> 1<br>
<input class="someclass" type="radio" name="v" value="2"> 2<br>
<input class="someclass" type="radio" name="v" value="3" checked> 3<br>
function yourcallback()
{
}
$('.someclass").click(yourcallabck);
This the way you can do using jquery
You can add an event listener to the parent of these elements. Events bubble up the DOM tree so you only need to attach one handler.
See an example here: http://jsfiddle.net/cLzBV/3/
How do I register a javascript event handler to an element that hasn't been added to the page yet... This is a similar post with good solution how to have an 'onclick' function for all of them.
And next code I see useful for you:
document.onclick = myRadioButtonOnClickHandler;
function myRadioButtonOnClickHandler(e) {
var realTarget = e ? e.target : window.event.srcElement;
if (realTarget.nodeName.toLowerCase() === 'input' && realTarget.type === 'radio' ) {
doSomething();
}
}
Hope it helpful.
You can use Jquery add class to every radio such as "RadioClass" add jquery file to your page and use the code below...
$(document).ready(function() {
$('.RadioClass').click(function () {
alert($(this).val());
});
});
精彩评论