Reputation: 379
I can not figure out how to get the value of a radio button.
I've tried everything except the right way. Here is an example here
OK, the first switch may not be the right way to use the switch stateemnt, although I like doing it this way since it is easy to read and add new options.
Alert statements display true or false. So then I tried an if statement. This did not work. Ok, maybe I must type out everything. Nope, this did not work either. Maybe it needs a numeral? Nope. String? Nope.
So I tried another switch. Nope again.
Can someone give me the proper way to do this please?
function commitData()
{
switch (true) {
case document.getElementsByName('StatusOnHeader')[0]:
alert('Edit');
break;
case document.getElementsByName('StatusOnHeader')[1]:
alert('Add');
break;
default:
alert('XXX');
break;
}
if (document.getElementsByName('StatusOnHeader')[0]) {
alert("TRUE");
} else {
alert("FALSE");
}
if (document.getElementsByName('StatusOnHeader')[0] == true) {
alert("TRUE");
} else {
alert("FALSE");
}
if (document.getElementsByName('StatusOnHeader')[0] == 1) {
alert("TRUE");
} else {
alert("FALSE");
}
if (document.getElementsByName('StatusOnHeader')[0] == '1') {
alert("TRUE");
} else {
alert("FALSE");
}
switch (document.getElementsByName('StatusOnHeader')[0]) {
case true:
alert('Edit');
break;
case false:
alert('Add');
break;
default:
alert('XXX');
break;
}
}
Upvotes: 0
Views: 83
Reputation: 386519
switch (true) {...}
true is not a variable; insert here a variable
case variable: ...
variable is unusual; mostly constants are used here
document.formName.inputRadio[0..n].checked
returns false or true
getElementsByID()
is unknown. the id is unique and so the method is getElementById()
and now the answer:
<form action="" name="chooseAFormName">
<input type="radio" name="StatusOnHeader" value="Edit">Edit existing
<input type="radio" name="StatusOnHeader" value="Add" checked="checked">Add new
<input type="submit" name="send_button" value="Save" onclick='commitData()'>
</form>
script part:
function commitData() {
if (document.chooseAFormName.StatusOnHeader[0].checked) {
alert('first radio checked!');
// insert here valuable stuff
}
if (document.chooseAFormName.StatusOnHeader[1].checked) {
alert('second radio checked!');
// insert here valuable stuff as well
}
}
Upvotes: 0
Reputation: 14361
Boolean Result (true / false)
var checkedOrNot = document.getElementsByName('StatusOnHeader')[0].checked;
String Result ('Checked', 'Not checked')
var result = (document.getElementsByName('StatusOnHeader')[0].checked)?'Checked':'Not Checked';
Upvotes: 0
Reputation: 803
if(document.getElementsByName('StatusOnHeader')[0].checked)
Upvotes: 2