In html, I have
<form id="form">
<input type="radio" name="stack" value="north" onClick="input(value)">north<br>
<input type="radio" name="stack" value="east" onClick="input(value)" >east<br>
<input type="radio" name="stack" value="west" onClick="input(value)">west<br>
<input type="radio" name="stack" value="south" onClick="input(value)">south
</form>
And the way I thought of fetching selected radio is like,
var input=function(x)
{
console.log(x);
}
I actually first coded like,
var input="north";
var dd=function(x)
{
if(input==null)
{
return direction.map(function (c) {
return data.map(function (d) {
//console.log(d[c]);
return {x: d.month, y: d[c]};
})
})
}
else{
return data.map(function (d) {
return {x: d.month , y : d[input]};
}}
}
var dataIntermediate=dd(input);
console.log(JSON.stringify(dataIntermediate));
But now I actually need to take the value of input to this function onclick and I am confused how to proceed. Please help.
change input(value) to input(this.value) and ready
var global;
var input = function(x) {
global = x;
console.log(x);
};
// Checking the global variable in realTime
setInterval(function(){
document.querySelector("#globalVariableValue").innerText = global;
},10);
<form id="form">
<input type="radio" name="stack" value="north" onClick="input(this.value)">north<br>
<input type="radio" name="stack" value="east" onClick="input(this.value)" >east<br>
<input type="radio" name="stack" value="west" onClick="input(this.value)">west<br>
<input type="radio" name="stack" value="south" onClick="input(this.value)">south
</form>
<br />
<span id="globalVariableValue"></span>
you need to start a function, after that specify an "ID" for the input and that will make the selection of vaule and running the function accurate.
for example:
function something(){
if(document.getElementById('north').checked) {
//do something
} else {
// do something else
}
the input looks like
<input type="radio" id="north" name="stack" value="north" onClick="functionName(this.value)">north<br>
First, don't use inline HTML event handling attributes (onclick, etc.) as they create "spaghetti code", create anonymous global functions that modify the this binding and don't follow the W3C DOM Event Standard
Here's all you need to get the value of a radio button and then pass that value somewhere:
var radVal = null;
// Once the DOM is ready...
window.addEventListener("DOMContentLoaded", function(){
// Get all the radiobuttons
var btns = document.querySelectorAll("[name=stack]");
// Loop through them
for(var i =0; i < btns.length; ++i){
// Set up a click event handling callback function
btns[i].addEventListener("click", function(evt){
// That grabs the value from the clicked button
radVal = evt.target.value;
// You can call another function from here, but if that other function
// needs the value, you don't need to pass it because you just set it
// into a variable (radVal) which has a higher scope than this function
foo();
// Or, you can not call another function from here and just call the
// other function when you need to, but you will need to make sure that
// this happens AFTER one of the radio buttons were clicked, otherwise
// radVal will still be null
});
}
function foo(){
// Since this function can be called at any time, we should check to make
// sure that one of the radio buttons has first been clicked.
if(radVal){
// radVal is not null, so a radio button was clicked
console.log("foo says value is: " + radVal);
} else {
// radVal is still null so no button has been clicked yet
console.log("foo says no button was clicked");
}
}
// This will show the else message because this is being called
// before the radio buttons have been clicked
foo();
});
<form id="form">
<input type="radio" name="stack" value="north">north<br>
<input type="radio" name="stack" value="east">east<br>
<input type="radio" name="stack" value="west">west<br>
<input type="radio" name="stack" value="south">south
</form>
Related
I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok
I have a form with checkboxes. The javascript function allPosPlayersCheckboxes utilizes a "Check All" Checkbox that controls the others. The other functions (getPosAllFilterOptions & getPosPlayersFilterOptions) push the "name" properties into an array. This all is triggered when anything is changed on the form.
Suppose that all checkboxes are unchecked. If the user checks the "nonP_all" checkbox, it will automatically check the other checkboxes with class="nonP". Unfortunately, when the "name" properties are pushed into the array, it will not include any with class="nonP".
I"m unsure why they are not included in the array. Are the functions (getPosAllFilterOptions & getPosPlayersFilterOptions) not waiting for allPosPlayersCheckboxes to complete? Is there a way to have the secondary checkboxes included in the arrays? Thanks for any help!
<form id="formFilter">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="nonP_all" class="Pos_all" name="nonP" checked="checked">
<label for="nonP">Position Players</label>
<input type="checkbox" id="C" class="nonP" checked="checked" name="C">
<label for="C">C</label>
<input type="checkbox" id="1B" class="nonP" checked="checked" name="1B">
<label for="1B">1B</label>
<input type="checkbox" id="2B" class="nonP" checked="checked" name="2B">
<label for="2B">2B</label>
<input type="checkbox" id="3B" class="nonP" checked="checked" name="3B">
<label for="3B">3B</label>
<input type="checkbox" id="SS" class="nonP" checked="checked" name="SS">
<label for="SS">SS</label>
<input type="checkbox" id="LF" class="nonP" checked="checked" name="LF">
<label for="LF">LF</label>
<input type="checkbox" id="CF" class="nonP" checked="checked" name="CF">
<label for="CF">CF</label>
<input type="checkbox" id="RF" class="nonP" checked="checked" name="RF">
<label for="RF">RF</label>
<input type="checkbox" id="DH" class="nonP" checked="checked" name="DH">
<label for="DH">DH</label>
</div>
function allPosPlayersCheckboxes(){
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
};
function getPosAllFilterOptions(){
var pos_all_opts = new Array();
$(".Pos_all:checked").each(function(){
pos_all_opts.push($(this).attr('name')); // places names into array
});
return pos_all_opts;
}
function getPosPlayersFilterOptions(){
var nonP_opts = new Array();
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
return nonP_opts;
}
var $formFilter = $("#formFilter");
$formFilter.change(function(){
allPosPlayersCheckboxes();
var pos_all_opts = getPosAllFilterOptions();
var nonP_opts = getPosPlayersFilterOptions();
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
The reason that you are having an issue is because the checking of the boxes event is being caught at the form change event handler, and the code that checks and unchecks all of the other boxes hasn't executed yet. As a result when you call your functions, the count for checked boxes is 0. This also happens when you uncheck one of the position checkboxes, eventually the pos_all_opts variable gets out of sync and is incorrect as well.
These click handlers don't need to be in a function. They are handlers that are hooked into the behavior of your checkboxes.
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
This is probably a little less than ideal, but it works. The code that was in the functions to build the arrays has been moved into the change handler for the form.
$("#formFilter").change(function(event){
var pos_all_opts = [];
var nonP_opts = [];
if(event.target === $("#nonP_all")[0] && event.target.checked) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else if(event.target === $("#nonP_all")[0] && !event.target.checked) {
pos_all_opts = [];
nonP_opts = [];
} else if(event.target !== $("#nonP_all")[0] && $(".nonP:checked").length === 9) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else {
pos_all_opts = [];
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
}
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
Fiddle for reference
My code so far is:
HTML
<input type="radio" name="age" value="0">1-25
<input type="radio" name="age" value="5">26-27
<input type="radio" name="age" value="7">28-29
<input type="radio" name="bmi" value="0">0-25
<input type="radio" name="bmi" value="0">26-30
<input type="radio" name="bmi" value="9">31-35
So I need to get the value of the checked radio buttons and calculate them
Javascript as the first answer that I've got
function CalculateValue(){
//call getAgeValue(), getBmiValue() here and do desired calculations here
}
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
Making use of the vanilla document.querySelector
function doCalculation(ageValue, bmiValue) {
// whatever
return ageValue + bmiValue;
}
function getRadioValue(radio_name) {
return ( // parenthesis to let us do an OR
document.querySelector('input[type="radio"][name="' + radio_name + '"]:checked')
|| // or if none is checked
{} // so we don't get an error
).value;
}
function handlerForButton(e) {
var age = +getRadioValue('age'),
bmi = +getRadioValue('bmi'),
foo = doCalculation(age, bmi);
// do whateverwith foo
console.log(foo);
}
// after elements exist
document.querySelector('input[type="button"][value="Calculate"]')
.addEventListener('click', handlerForButton);
DEMO
You may find it easier to use classes and ids to find your elements rather than seeking them out using their other attributes. This would also improve performance
This is my setup:
HTML
1. How are you?
<input class="calc" type="radio" name="1" value="2">Good
<input class="calc" type="radio" name="1" value="1">Okey
<input class="calc" type="radio" name="1" value="0">Bad
Javascript
if ( name 1 has value 2)
{ do something }
else if ( name 1 has value 1)
{ do something }
else if ( name 1 has value 0)
{ do something }
else
{ }
How do I make a if else statement out of name and value?
var names = document.getElementsByName("1");
if (names[0].checked)
{ do something }
else if (names[1].checked)
{ do something }
else if (names[2].checked)
{ do something }
else
{ }
Though it would seem simpler to just grab the checked one, and put its value in a switch() statement.
var chkd = document.querySelector(".calc:checked");
switch( chkd.value) {
case 2: // ...
break;
case 1: //
break;
default: // ...
}
However the :checked requires a modern browser, like IE9 or greater.
The general premise behind an if statement is:
if ('statement to evaluate') {
// Code to execute if above statement is true
} else if ('another statement')
// Code executes if first statement was false, but second one is true
} else {
// If both above statements are false, execute this code
}
Read more about if statments: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
More about what evaluates to true: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
Here's a complete example. The best part is - you don't need conditions at all. You can use the value itself to determine what callback to use. This method is called "property lookup".
Live demo (click).
Sample Markup:
<form id="myForm">
<h3>1. How are you?</h3>
<input name="1" type="radio" value="2">
<label>Good</label>
<input name="1" type="radio" value="1">
<label>Okay</label>
<input name="1" type="radio" value="0">
<label>Bad</label>
<button disabled>Click me.</button>
</form>
JavaScript:
var inputs = document.querySelectorAll('#myForm input');
var submit = document.querySelector('#myForm button');
for (var i=0; i<inputs.length; ++i) {
inputs[i].addEventListener('click', function() {
submit.removeAttribute('disabled');
});
}
var responses = [
function() { //this is "responses[0]
console.log('this handles value 1!');
},
function() { //this is "responses[1]
console.log('this handles value 2!');
},
function() { //this is "responses[2]
console.log('this handles value 3!');
}
];
submit.addEventListener('click', function(e) {
var checked = document.querySelector("#myForm input:checked");
var x = checked.value;
responses[x](); //call the response function for this value
e.preventDefault(); //prevent the form from submitting
});
This may seem silly and downright stupid but I can't seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following code:
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
How do I retrieve the value of gender via JavaScript?
Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).
document.querySelector('input[name="gender"]:checked').value
In pure Javascript:
var genders = document.getElementsByName("gender");
var selectedGender;
for(var i = 0; i < genders.length; i++) {
if(genders[i].checked)
selectedGender = genders[i].value;
}
update
In pure Javascript without loop, using newer (and potentially not-yet-supported) RadioNodeList :
var form_elements = document.getElementById('my_form').elements;
var selectedGender = form_elements['gender'].value;
The only catch is that RadioNodeList is only returned by the HTMLFormElement.elements or HTMLFieldSetElement.elements property, so you have to have some identifier for the form or fieldset that the radio inputs are wrapped in to grab it first.
If you are using a javascript library like jQuery, it's very easy:
alert($('input[name=gender]:checked').val());
This code will select the checked input with gender name, and gets it's value. Simple isn't it?
Live demo
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.
<form name="myForm">
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
</form>
<script>
var selected = document.forms.myForm.gender.value;
</script>
Try:
var selectedVal;
for( i = 0; i < document.form_name.gender.length; i++ )
{
if(document.form_name.gender[i].checked)
selectedVal = document.form_name.gender[i].value; //male or female
break;
}
}
Another solution for ES5+
[...document.getElementsByName("gender")].find(input => input.checked).value;
Without loop:
document.getElementsByName('gender').reduce(function(value, checkable) {
if(checkable.checked == true)
value = checkable.value;
return value;
}, '');
reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.
The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.
function myFunction() {
document.getElementById("text").value='male'
document.getElementById("myCheck_2").checked = false;
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myFunction_2() {
document.getElementById("text").value='female'
document.getElementById("myCheck").checked = false;
var checkBox = document.getElementById("myCheck_2");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
Male: <input type="checkbox" id="myCheck" onclick="myFunction()">
Female: <input type="checkbox" id="myCheck_2" onclick="myFunction_2()">
<input type="text" id="text" placeholder="Name">