<input type="radio" checked="checked" value="true" name="child">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="child">
<span class="label">Hide</span>
and another radio button on the same page
<input type="radio" checked="checked" value="true" name="baby">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="baby">
<span class="label">Hide</span>
I need to know if all the radio buttons having value="false" are checked using javascript.
Note: The radio button names are different
If you use jQuery, it's very clean:
if ($("input[type='radio'][value='false']").not(':selected').length==0) {
// Do what you want
}
The jQuery expression means all the false radio buttons are selected
boudou beat me by 35 seconds...
However, besides the for you can use a foreach logic:
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
var id = button.getAttribute("id");
var type = button.getAttribute("type");
var value = button.getAttribute("value");
var checked = button.getAttribute("checked");
if (type === "radio" && value === "false" && checked === "checked") {
alert(id);
}
}
The script can be condensed, it's written like this to allow a better understanding.
See a demo here.
You can try this:
function testRadios() {
var r = document.getElementsByTagName("input");
for (var i=0; i < r.length; i++) {
if ( (r[i].type == "radio")
&& (r[i].value == "false")
&& (r[i].checked != "checked")) {
return false;
}
return true;
}
PS: Use <label> instead of <span class="label">.
Related
I have 3 checkboxes and I want them to do certain actions i.e display an alert box when they are checked and when one check box is checked, the others should be unchecked.
I've been able to get the second part to work where only one checkbox can be checked at a time but I can't seem to make the first part of displaying an alert box work.
js that ensures only one box is checked at any time:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
}
html:
<input class="qty" type="checkbox" id="pails" onchange="qtyBox(this)"/>Pails
<input class="qty" type="checkbox" id="liters" onchange="qtyBox(this)"/>Liters
<input class="qty" type="checkbox" id="gallons" onchange="qtyBox(this)"/>Gallons
Now all that's left is when Pails is checked,I want an alert box to display pails. when liters is checked, an alert box to display liters and when gallons is checked, an alert box to display gallons.
You need to get reference to the input. Just add:
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
so it become:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
}
Hope this help.
Use radio buttons with a common name (e.g. units) and a click listener to do the alert. Add a value attribute for the value, an ID seems redundant:
<input class="qty" name="units" type="radio" value="pails" onclick="alert(this.value)">Pails
<input class="qty" name="units" type="radio" value="litres" onclick="alert(this.value)">Litres
<input class="qty" name="units" type="radio" value="gallons" onclick="alert(this.value)">Gallons
Though I'd delegate the listener to an ancestor element.
You should remove the onclick from the html - and just use something like this. However, if you want to use jquery would easier, but here is vanilla javascript solution. ( in a js file or wrapped in script tags )
(function(){
var inputs = document.getElementsByClassName('qty');
for(i=0; i<inputs.length; i++){
var el = inputs[i];
el.addEventListener('click', function(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
this.checked = true
alert(this.id);
});
}
})();
how to pass checkbox values in an array to a function using onclick in JavaScript.
following is my html code. Note that I don't use form tag. only input tags are used.
<input id="a"name="a" type="checkbox" value="1" checked="checked" >A</input>
<input id="a"name="a" type="checkbox" value="2" checked="checked" >B</input>
<input id="a"name="a" type="checkbox" value="3" checked="checked" >C</input>
<button onclick="send_query(????)">CLICK</button>
following is my JavaScript function
function send_query(check) {
var str = "";
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
str = str + check[i];
}
console.log(str);
}
You can write a onclick handler for the button, which can create an array of clicked checkbox values and then call the send_query with the parameter as shown below
<button onclick="onclickhandler()">CLICK</button>
then
function onclickhandler() {
var check = $('input[name="a"]:checked').map(function () {
return this.value;
}).get();
console.log(check);
send_query(check)
}
Note: I would also recommend using jQuery to register the click handler instead of using inline onclick handler.
Note: Also ID of elements must be unique in a document... you have multiple elements with id a, I'm not seeing you using that id anywhere so you could probably remove it
With pure javascript (demo) (tested with Chrome only).
HTML :
<button onclick="send_query(document.getElementsByTagName('input'))">
Javascript :
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}
Try this
<form name="searchForm" action="">
<input type="checkbox" name="categorySelect[]" id="1"/>
<input type="checkbox" name="categorySelect[]" id="2" />
<input type="checkbox" name="categorySelect[]" id="3"/>
<input type="button" value="click" onclick="send_query();"/>
</form>
JS
function send_query() {
var check = document.getElementsByName('categorySelect[]');
var selectedRows = [];
for (var i = 0, l = check.length; i < l; i++) {
if (check[i].checked) {
selectedRows.push(check[i]);
}
}
alert(selectedRows.length);
}
I'm new to posting/stackoverflow, so please forgive me for any faux pas. I have multiple buttons and checkboxes that I need to store the values of to place into conditional statements.
The HTML code:
<h1>SECTION 1: GENDER</h1>
<p>What is your gender?</p>
<input type="button" onclick="storeGender(this.value)" value="Male"/>
<input type="button" onclick="storeGender(this.value)" value="Female"/>
<hr />
<h1>SECTION 2: AGE</h1>
<p>What is your age?</p>
<input type="button" onclick="storeAge(this.value)" value="18–22"/>
<input type="button" onclick="storeAge(this.value)" value="23–30"/>
<hr />
<h1>SECTION 3: TRAITS</h1>
<h3>Choose Two:</h3>
<form>
<input name="field" type="checkbox" value="1"/> Casual <br />
<input name="field" type="checkbox" value="10"/> Cheerful <br />
<input name="field" type="checkbox" value="100"/> Confident <br />
<input name="field" type="checkbox" value="1000"/> Tough <br />
<input type="button" id="storeTraits" value="SUBMIT" /> <br />
</form>
<hr />
<h2>Here is what I suggest</h2>
<p id="feedback">Feedback goes here.</p>
jQuery code:
// set up variables
var gender;
var age;
var string;
$(document).ready(function() {
startGame();
$("#storeTraits").click( function() {
serializeCheckbox();
}
); }
);
function startGame() {
document.getElementById("feedback").innerHTML = "Answer all the questions.";
}
function storeGender(value) {
gender = value;
}
function storeAge(value) {
age = value;
}
function serializeCheckbox() {
// clear out any previous selections
string = [ ];
var inputs = document.getElementsByTagName('input');
for( var i = 0; i < inputs.length; i++ ) {
if(inputs[i].type == "checkbox" && inputs[i].name == "field") {
if(inputs[i].checked == true) {
string.push(inputs[i].value);
}
}
}
checkFeedback();
}
//Limit number of checkbox selections
$(function(){
var max = 2;
var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
function checkFeedback() {
if(gender == "Male") {
if (age == "18–22" && string == 11){
document.getElementById("feedback").innerHTML = "test1";
} else if (age == "18–22" && string == 110){
document.getElementById("feedback").innerHTML = "test2";
} else if (age == "18–22" && string == 1100){
document.getElementById("feedback").innerHTML = "test3";
} else if (age == "18–22" && string == 101){
document.getElementById("feedback").innerHTML = "test4";
}
}
}
I found this code on JSFiddle: http://jsfiddle.net/GNDAG/ which is what I want to do for adding together my trait values. However, when I try to incorporate it my conditional statements don't work. How do I add the code from the jsfiddle example and get the conditional statements to work? Thank you!
You need an integer, not a string array. Here's the code you need:
var traits = 0;
$('input[name=field]:checked').each(function () {
traits += parseInt($(this).val(), 10);
});
This will set the "traits" variable to an integer like 1, 11, 101, or 1001.
BTW: The second parameter to parseInt() is the base.
But a few suggestions:
Don't use "string" as a variable name.
Use radio buttons for gender and age.
Put all the input elements in the form.
Have one button that submits the form.
Attach a handler to the form submit event, and do your processing in that function, but call e.preventDefault() to prevent the form from submitting to the server. Alternatively, you could have the single button not be a submit button and attach an on-click handler to it.
Here's a jsfiddle with the code above and all the suggestions implemented.
I have three radios and i want onselect of anyone to be redirected to a link. Using javascript or jquery
All <input name="EventRadio" type="radio" value="" checked="checked"/>
Events<input name="EventRadio" type="radio" value="Events" /> Classes<input name="EventRadio" type="radio" value="Classes"/><br /><br />
so since "All" is default checked, i want it to go to mysite.com/search.aspx.
now if user selects Events, I want to redirect user to mysite.com/search?type=Events
or if user selects Classes, I want to redirect the user to mysite.com/search?type=Classes
as response to the onselect of the radios. How do I achieve this?
All <input name="EventRadio" type="radio" value="" checked="checked" onclick ="goToLocation(this.value)"/>
Events <input name="EventRadio" type="radio" value="Events" onclick ="goToLocation(this.value)"/>
Classes <input name="EventRadio" type="radio" value="Classes" onclick ="goToLocation(this.value)"/><br /><br />
function goToLocation(val){
if(val == "Events")
window.location = "go to Events location";
if(val == "Classes")
window.location = "go to Classes location";
window.location = "go to default location";
}
As a demonstration:
var inputs = document.getElementsByTagName('input'),
radios = [],
output = document.getElementById('output'),
url = 'mysite.com/search?type=';
for (var i = 0, len = inputs.length; i<len; i++) {
if (inputs[i].type == 'radio'){
radios.push(inputs[i]);
}
}
for (var r=0, leng = radios.length; r<leng; r++){
radios[r].onchange = function(){
if (this.value){
/* in real life use:
document.location = url + this.value;
*/
output.innerHTML = url + this.value;
}
else {
/* in real life use:
document.location = 'mysite.com/search?type=Events';
*/
output.innerHTML = 'mysite.com/search.aspx';
}
}
}
JS Fiddle demo.
Please note that I've also changed your mark up to use <label> elements, and removed the s and <br />s.
$('input').click(function(){
var val = $(this).val();
if(val !== ''){
window.location = 'http://mysite.com/search?type=' + val;
}else{
window.location = 'http://mysite.com/search.aspx';
}
});
Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:
Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?
I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.
You can use document.getElementsByName(), passing the name of the radio group, then loop over them inspecting the checked attribute, e.g. something like:
function getCheckedValue( groupName ) {
var radios = document.getElementsByName( groupName );
for( i = 0; i < radios.length; i++ ) {
if( radios[i].checked ) {
return radios[i].value;
}
}
return null;
}
getElementsByName didn't work for me. I did this:
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
if (radios[i].type == 'radio' && radios[i].checked) {
nbchecked++;
}
}
Use document.getElementsByName() is the short answer to the question you asked.
However, it may be better to do something like this:
<form name="formFoo">
Foo: <input type="radio" name="groupFoo" value="foo" checked> <br />
Bar: <input type="radio" name="groupFoo" value="bar"> <br />
Baz: <input type="radio" name="groupFoo" value="baz"> <br />
<input type="submit" >
</form>
Then use the JavaScript:
function getRadioValue(formName, groupName) {
var radioGroup = document[formName][groupName];
for (var i=0; i<radioGroup.length; i++) {
if (radioGroup[i].checked) {
return radioGroup[i].value;
}
}
return null;
}
By doing this, you avoid having to use a function that searches the entire document. It just searches first for the form, then within that form for controls with that same name. The problem here is that if you were to have a checkbox in the middle of the form with the same name, it could be returned instead of the correct radio value. If another type of control was thrown in with the same name, then it could cause an error. Both of these circumstances should probably be considered programmer error, but it wouldn't hurt for the function to be expanded to check for them, at some potential performance loss. Just change the line:
if (radioGroup[i].checked) {
to:
if (radioGroup[i].type=='radio' && radioGroup[i].checked) {
I'll bite for the jQuery answer
var selectedValue = $("input[name='radio_name']:checked").val();
var options = document.getElementsByName('myRadioButtons');
for(i = 0; i < options.length; i++)
{
var opt = options[i];
if(opt.type=="radio")
{
if(opt.checked)
{
}
}
}
<form name="myForm" id="myForm" action="">
<input type="radio" name="radioButton" value="c1">Choice 1
<input type="radio" name="radioButton" value="c2">Choice 2
</form>
<script>
var formElements = window.document.getElementById("myForm").elements;
var formElement;
var radioArray = [];
for (var i = 0, j = 0; i < formElements.length; i++) {
formElement = formElements.item(i);
if (formElement.type === "radio" && formElement.name === "radioButton") {
radioArray[j] = formElement;
++j;
}
}
alert(radioArray[0].value);
alert(radioArray[1].value);
</script>
$("input[type='radio'][name='xxxxx']:checked").val()
To get all radio buttons directly by name:
element.querySelectorAll("input[name='nameOfTheName']")
The querySelectorAll() method can be used to get elements of a certain type by name. There are advantages to using querySelectorAll compared to getElementsByName() in certain situations. If you use getElementsByName on anything other than document, you will get an error:
element_Name_Here.getElementsByName is not a function
But querySelectorAll() can be used on sub elements of the document. This is helpful when you want to get one element out of multiple elements that all have the same structure (Rows in a list). In that case, you might not want to try to give separate ID's to every row. In that situation, the function called can be passed this, get the parentNode and from the parent, search for a specific attribute. This avoids needing to search the entire document.
html
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
<input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
script
function getOnlyThisRowsRadios(thiz) {
var i,L,parentElement,radioButtons;
parentElement = thiz.parentNode;//Get the parent of the element
radioButtons = parentElement.querySelectorAll("input[name='nameOfTheName']");
console.log('radioButtons: ' + radioButtons)
L = radioButtons.length;
console.log('L: ' + L)
for (i=0;i<L;i++) {
console.log('radBttns[i].checked: ' + radBttns[i].checked)
radBttns[i].checked = false;//Un-check all checked radios
}
This definitely works if your name attribute is taken for something else.
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
if (radios[i].type == 'radio' && radios[i].checked) {
console.log(radios[i])
}
}