Helpful Information
 
 
Category: JavaScript programming
problem with checking submit info.

Hello, I've got this problem where I need to check if one of the radio buttons is checked (true). I have set up a test script and when I do not click on the tested button and then click on the submit the test says that it is true (checked). so here's my code. let me know if you see something wrong...

i have for the form
<form name="frmSearch" method="GET" action="/cgi/search.pl" onSubmit="checkSearch();">

then ill just write here two radio buttons they can only pick one.

<input type="radio" name="destination" checked>blah blah
<input type="radio" name="destination">blah blah

now the javascript

<script language="JavaScript">
function checkSearch()
{
if (document.frmSearch.destination[1].checked == 'true')
{
document.write("true");
return false
}
else
{
document.write("false");
return false //so it won't process.. just for testing
}
}
</script>

i have 14 radio buttons and i need to check if one specific radio button is checked. If so i need to run another type of verification on a textbox.

thanks :thumbsup:
hogtied

counting starts at 0, not 1.


if (document.frmSearch.destination[0].checked == 'true')

If you just want to see if a particular button is checked you can use:

if (document.frmSearch.destination[1].checked)

by thge same token, if want to see if a particular button is not checked you can use:

if (!document.frmSearch.destination[1].checked)

It looks to me like you just need to take off the single quotes around 'true' and make it true. (Or do it like John Krutsch did, since his returns a boolean value as is):

if(document.frmSearch.destination[0].checked)

is the same as

if(document.frmSearch.destination[0].checked==true)

and if you want to see if it ISN'T checked you'd use:

if(!document.frmSearch.destination[0].checked){
// do something
}

:)


This doesn't necessarily apply to your question, but to make for interesting reading, if you wanted to check to make sure at least ONE radio button was checked you could also loop through them, like:



var dest = document.frmSearch.destination;
var isChecked = "no";
for(i=0;i<dest.length;i++){
if(dest[i].checked==true){
isChecked = "yes";
}
}
alert(isChecked);


There are more elegant ways to do this but that one is pretty easy to understand! Basically you just loop through the length of the radiobutton name and see if any of them are checked. If so, you set isChecked to "yes".

:)

thanks guys ill sure try those responses.. Joh6nn I know it starts at 0 i wanted to test if the 2nd radio button was clicked.. but thanks for the info..... I ll get back to you a let you know if it worked...

Thanks,
Hogtied.,,

Thanks guys! JohnKrutsch and whammy both ways worked so i guess its just a matter of preference..

Thanks,,,,,

hogtied :thumbsup:










privacy (GDPR)