Javascript get value by radio button name
first of all i am a beginner in javascript, a really big beginer
Can someone give me a h开发者_如何学运维int on this?
I have a form
, on the form i have a radio
button.
And i would like to that if the radio is set yes , it would show the value of it on another page.
And i would like to get the value by the input name
is it possible?
I'm not asking to write my code, but just an example for a start.
i was tried with this just for a test
<input type="hidden" name="the_name" value="yes">
if(the_name.element == 'yes') {
alert('cool');
}
the_name.value
, not the_name.element
You can use getElementsByName()
for accessing the elements value via the input name. But as a standard and since it helps load off the DOM we use getElementById()
instead of the name. Also you can start from here -> http://eloquentjavascript.net/
You can reference the form using:
document.forms[formName or formId].elements[element-name];
However, name is not necessarily unique in the document. If there is only one element with the name, then only one is returned. If more than one have the same name, then you will get a collection (a bit like an array) and you will have to iterate over them to find the one you want.
You can also use document.getElementsByName, which always returns a collection. So you can do:
var elements = document.getElementsByName('the_name');
// get the one with value 'yes'
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (elements[i].value == 'yes') {
return elements[i];
}
}
You will also need to be careful of case sensitivity, you might want to use toLowerCase() on the value first, or use a case insensitive regular expression:
e.g.
var re = /yes/i;
...
if (re.test(elements[i].value)) {
// value is Yes or YES or yeS or ...
<input type="hidden" name="the_name" id="the_name" value="yes"> <!-- id added -->
if(formName.the_name.value == 'yes')
{
alert('cool');
}
OR better (since you are not accessing the elements by global names)
var element = document.getElementById("the_name");
if(element.value === 'yes')
{
alert("yes, it is");
}
精彩评论