I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.
Related
I have some radio buttons on a page, and I need to just identify which one was checked in my JS, based on ID. I'm not sure why this isn't working. Each time, I get the "nothing checked" message in my console. Thanks!
HTML:
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
JS:
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
}else if(document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
}else if (document.getElementById('aud3').checked){
var aud = document.getElementById('file3');
}
else console.log('nothing checked');
See below. I've added a button to your code that you can click after you have some checked.
Initially, when the page loads, there is nothing clicked. Your JS is ran as soon as the page is built there which is why you were seeing the nothing clicked.
document.getElementById('check-radios').onclick = function() {
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
console.log('aud1 checked');
}
else if (document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
console.log('aud2 checked');
}
else if (document.getElementById('aud3').checked) {
var aud = document.getElementById('file3');
console.log('aud3 checked');
}
else console.log('nothing checked');
}
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
<button id="check-radios">Check for clicked</button>
do you explicitly need this code? why not use a single class, and have the filename/desc as a custom attribute like so:
<input type="radio" name="animals" class="order" data-animal="elephant" />elephant
<input type="radio" name="animals" class="order" data-animal="zebra" />zebra
<input type="radio" name="animals" class="order" data-animal="lion" />lion
<script>
$(".order").click(function () {
var choice = this.getAttribute("data-animal");
alert(choice);
/* console.log(choice); */
})
</script>
That way you dont have to manually keep adding more code, u can just add the html at the top using the same class and a different attribute value... much easier to maintain -
Also since you had an elseif i added a name to group them as individual radios as I presume you intended?
<input type="radio" name="animals" class="order" checked data-animal="zebra">zebra
bear in mind there is no closing tag for input tags - just /> at the end instead of >
I want to hide a div (AppliedCourse), when radi button value is Agent. I wrote below code but it is not working.
Any idea?
$('#HearAboutUs').click(function() {
$("#AppliedCourse").toggle($('input[name=HearAboutUs]:checked').val()='Agent');
});
<tr><td class="text"><input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other</td></tr>
Either your HTML is incomplete or your first selector is wrong. It is possible that your click handler is not being called because you have no element with id 'HeadAboutUs'. You might want to listen to clicks on the inputs themselves in that case.
Also, your logic is not quite right. Toggle hides the element if the parameter is false, so you want to negate it using !=. Try:
$('input[name=HearAboutUs]').click(function() {
var inputValue = $('input[name=HearAboutUs]:checked').val()
$("#AppliedCourse").toggle( inputValue!='Agent');
});
I have made a JSFiddle with a working solution: http://jsfiddle.net/c045fn2m/2/
Your code is looking for an element with id HearAboutUs, but you don't have this on your page.
You do have a bunch of inputs with name="HearAboutUs". If you look for those, you'll be able to execute your code.
$("input[name='HearAboutUs']").click(function() {
var clicked = $(this).val(); //save value of the input that was clicked on
if(clicked == 'Agent'){ //check if that val is "Agent"
$('#AppliedCourse').hide();
}else{
$('#AppliedCourse').show();
}
});
JS Fiddle Demo
Another option as suggested by #Regent is to replace the if/else statement with $('#AppliedCourse').toggle(clicked !== 'Agent');. This works too.
Here is the Fiddle: http://jsfiddle.net/L9bfddos/
<tr>
<td class="text">
<input type="radio" name="HearAboutUs" value="Press">Press & Print media
<input type="radio" name="HearAboutUs" value="Internet">Internet
<input type="radio" name="HearAboutUs" value="Agent">Agent
<input type="radio" name="HearAboutUs" value="Friend">Friend
<input type="radio" name="HearAboutUs" value="Other" checked="checked">Other
</td>
Test
$("input[name='HearAboutUs']").click(function() {
var value = $('input[name=HearAboutUs]:checked').val();
if(value === 'Agent'){
$('#AppliedCourse').hide();
}
else{
$('#AppliedCourse').show();
}
});
I am using this javascript code. and on button click I want that atleast one checkbox selection is required. do anyone have idea what I am doing wrong. I don't want to use jquery.
function check()
{
var flag = false;
for(var i=1;i<=4;i++)
{
var checkb = document.getElementById("check"+i);
if(checkb.checked)
{
flag = true;
break;
}
}
if(!flag)
alert("What is your interest \n(select at least one option)");
return flag;
}
</script>
Button Click Code is
<input type="submit" name="submit" value="Submit" onclick="return check();">
The code works fine. Do hou have id="check1" set on your checkbox tags?
Yes, your code works fine as noted by the comments above. However, you could do your check for...checks a little more cleanly - you're expecting "check0" - "check4" for the IDs. You could just grab them all and not worry about a set limit (odds are your code isn't working because at least one of the IDs you're using doesn't exist).
<input type="checkbox" id="check0" />
<input type="checkbox" id="check1" />
<input type="checkbox" id="check2" />
<input type="checkbox" id="check3" />
<hr/>
<input type="button" onclick="checkIt();" value="Check the Checks">
And some JS:
checkIt = function()
{
var checks = document.getElementsByTagName('input');
var hasCheck = false;
for(i in checks)
{
// Could also check for a classname here to narrow
// your result set.
if(checks[i].type == 'checkbox')
hasCheck |= checks[i].checked;
}
if(!hasCheck)
alert('You should check one!');
return hasCheck;
}
I know nothing of JavaScript.
I had to add a group of two radio buttons to an HTML form with values "yes" and "no".
Now I need to make them "required"
There are several other required fields in the form and this piece of JavaScript:
<SCRIPT LANGUAGE="JavaScript">
<!--
reqd_fields = new Array();
reqd_fields[0] = "name";
reqd_fields[1] = "title";
reqd_fields[2] = "company";
reqd_fields[3] = "address";
reqd_fields[4] = "city";
reqd_fields[5] = "state";
reqd_fields[6] = "zip";
reqd_fields[7] = "phone";
reqd_fields[8] = "email";
reqd_fields[9] = "employee";
function validate(form_obj) {
if (test_required && !test_required(form_obj)) {
return false;
}
It was done by someone else, not me.
What I did is just added my field to this array, like this:
reqd_fields[10] = "acknowledge";
However it doesn't seem to be working.
Please guide me as I am totally ignorant when it comes to JavaScript.
Why don't you just make one selected by default then one will always be selected.
A link to your page or a sample of your HTML would make this easier, but I'm going to hazard a guess and say that the values in the array match the "name" attribute of your radio button elements.
If this the case, "acknowledge" should be the name of both radio buttons, and to make things easier, one should have the attribute "checked" set to "true" so there is a default, so you'll get a value either way.
So, something like this:
<input type="radio" name="acknowledge" value="yes" /> Yes <br/>
<input type="radio" name="acknowledge" value="no" checked="true" /> No <br/>
I know question is ancient but this is a simple solution that works.
<script type="text/javascript">
function checkForm(formname)
{
if(formname.radiobuttonname.value == '') {
alert("Error: Please select a radio button!");
return false;
}
document.getElementById('submit').value='Please wait..';void(0);
return true;
}
</script>
<form name="formname" onsubmit="return checkForm(this)"
<input type="radio" value="radio1" name="radiobuttonname" style="display:inline;"> Radio 1<br>
<input type="radio" value="radio2" name="radiobuttonname" style="display:inline;"> Radio 2<br>
<input type="submit" value="Submit">
</form>
Without seeing your HTML and more context of your validate function it's unclear exactly what you're looking for, but here's an example of how to require a selected value from a radio group:
<form name="form1">
<input type="radio" name="foo"> Foo1<br/>
<input type="radio" name="foo"> Foo2<br/>
</form>
<script type="text/javascript">
var oneFooIsSelected = function() {
var radios = document.form1.foo, i;
for (i=0; i<radios.length; i++) {
if (radios[i].checked) {
return true;
}
return false;
};
</script>
Here is a working example on jsFiddle.
I always recommend using jQuery validate seems better to me than trying to re-invent the wheel
How can we access the value of a radio button using the DOM?
For eg. we have the radio button as :
<input name="sex" type="radio" value="male">
<input name="sex" type="radio" value="female">
They are inside a form with name form1. When I try
document.getElementByName("sex").value
it returns 'male' always irrespective of the checked value.
Just to "generify" Canavar's very helpful function:
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
... which would now be referenced thusly:
getRadioValue('sex');
Strange that something like this isn't already a part of prototype.js.
Surprised no-one has suggested actually using the Selector API:
document.querySelector('input[name=sex]:checked').value
Browser support is good
If you need the selected one, most frameworks support functionality like this:
//jQuery
$("input[name='sex']:checked").val()
You can get your selected radio's value by this method :
<script>
function getRadioValue()
{
for (var i = 0; i < document.getElementsByName('sex').length; i++)
{
if (document.getElementsByName('sex')[i].checked)
{
return document.getElementsByName('sex')[i].value;
}
}
}
</script>
There are a couple of ways.
1. Put an id on each input
<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">
Then you can use document.getElementById("sex_male")
2. Use something like PrototypeJS (jQuery works too)
Then you can do something like this:
//This loops over all input elements that have a name of "sex"
$$('input[name="sex"]').each( function(elem) {
//Do something
});
Or even this to get at just the "male" radio button:
$$('input[name="sex"][value="male"]').each(function(elem) {
//Do something
});
An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:
for (var i = 0; i < document.form1.sex.length; i++) {
if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
if(list[i].type=='radio' && list[i].checked){
alert(list[i].value);
break;
}
}
If you use document.form1.sex, you are returned an array.
document.form1.sex[0] = first radio button
document.form1.sex[1] = second radio button
To check which is checked you need to loop:
whoChecked(document.form1.sex)
function whoChecked(fieldName) {
for(var x=0;x<fieldName.length;x++) {
if(fieldName[x].checked) {
return fieldname[x].value
}
}
document.getElementByName("sex").value
You mean getElementsByName('sex')[0].value? (There's no getElementByName.)
That will of course always pick the first input element with that name — the one whose value is indeed male. You then check to see if it's selected by using the ‘.checked’ property.
For this simple case you can get away with:
var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';
For the general case you have to loop over each radio input to see which is checked. It would probably be better to get the form object first (putting an id on the form and using document.getElementById is generally better than using the ‘name’-based document.forms collection), and then access form.elements.sex to get the list, in case there are any other elements on the page that have name="sex" attributes (potentially other things than form fields).
function getEleByName(){
if(true==document.getElementsByName('gender')[0].checked){
alert('selected gender is: male');
}
else{
alert('selected gender is: female');
}
}
Loops can achieve the task, as others have shown but it could be simpler than using a loop, which will help performance if desired. Also, it can be portable/modular so it can be used for different radio groups.
Simple Example
function getValue(x) {
alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
A more complex example:
function getValue(x){
alert(x.value);
}
<fieldset>
<legend>Sex</legend>
<label>Male:
<input name="sex" type="radio" value="male" onChange="getValue(this)"/>
</label>
<label>Female:
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
</label>
</fieldset>
<fieldset>
<legend>Age Group</legend>
<label>0-13:
<input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
</label>
<label>13-18:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>18-30:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>30+:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
</fieldset>
document.all.sex[0].checked
document.all.set[1].checked