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
});
Related
I have an input[type="radio"], with no checked option by default, and i need to return false if none of these options are checked.
I'm exploring javascript only, so a jquery, angular or any other will be useles (at this moment).
I'm able to iterate over a radioObj and select its value, but i can't return false if no option is checked (actually, i can't return true)
not exactly what i have, but...
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
and in JS i have...
var rdObj = document.getElementByName("radioGrp");
var selectedValue;
for (var i = 0, length = rdObj.length; i < length; i++){
if(!rdObj[i].checked){
alert("Select one option");
return false;
}else{
//do something with value of radio checked value
}
}
This code always gives me the alert("Select one option"), no matter if i select one option or not.
Need for validation.
Any hel will be very appreciated
You probably want to wait for an event before you do any sort of value checking, otherwise your script will only run once, and at this point in time, nothing would have ever had the chance be checked.
You can attach a change event listener to each of your radios...
var myRadios = document.querySelectorAll('[name=radioGrp]');
var selectedValue;
myRadios.forEach(radio => {
radio.addEventListener('change', changeHandler);
})
function changeHandler(evt) {
// do some check in here
console.log(evt.target.value)
}
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
...or you can attach a submit event handler to your form and do some checking of your data then.
const myForm = document.querySelector('form');
myForm.addEventListener('submit', submitHandler);
function submitHandler(evt) {
evt.preventDefault();
const data = new FormData(evt.target);
const optionVal = data.get('radioGrp');
// do some check in here
if (!optionVal) {
console.log(`Please select a value`)
} else {
console.log(`Thanks for selecting ${optionVal}`)
}
}
<form>
<input type="radio" id="rd1" name="radioGrp" value='opt1'>opt1
<br>
<input type="radio" id="rd2" name="radioGrp" value='opt2'>opt2
<input type="submit">
</form>
You can try this:
function validateForm() {
var radios = document.getElementsByName("radioGrp");
var formValid = false;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
formValid = true;
break;
}
}
if (!formValid) {
alert("Select one option");
}
return formValid;
}
<form name="form1" action="#" onsubmit="return validateForm();" method="post">
<input type="radio" id="rd1" name="radioGrp">opt1
<br>
<input type="radio" id="rd2" name="radioGrp">opt2
<br>
<input type="submit" value="Submit">
</form>
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
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>
In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>
Basically I have a script the function "hola ()" that should return the value of 1 if the radio button value is 1. But for some reason when I try to get the return value in another function i never get it.
The form works perfectly.. the only issue is that it doesnt return the value
Can anyone tell me what i did wrong?? thanks
$(document).ready(function(){
function hola() {
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
return 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
})
}
$("#iForm").submit( function(event){
event.preventDefault();
var user = $("input[name=username]").val();
var password = $("input[name=password]").val();
var dbName = $("input[name=dbName]").val();
var server = $("input[name=server]").val();
$.get("1.php",
{username: user, password: password, dbName: dbName, server: server },
function(data){
if (data == "The table PAGE exists" || data == "The table SUBJECTS exists" || data == "The table USERS exists" ) {
// CALLING THE hola () function and expecting a return
var opt = hola();
$("p").html(data + opt);
}
}
)
})
})
HTML
<!-- Yes or No form -->
<form name="yN" style= "display: none; margin-left: auto; margin-right: auto; width: 6em">
<input type="radio" name="yN" value="1">yes</input>
<input type="radio" name="yN" value="0">no</input>
<button id=1 >click me!</button>
</form>
<!-- Login Form -->
<form id="iForm" style= "display: show">
<label id="username" >Username</label>
<input id="username" name="username"/>
<label id="password">Password</label>
<input id="password" name="password" />
<label id="server" >Server</label>
<input id="server" name="server"/>
<label id="dbName" >dbName</label>
<input id="dbName" name="dbName"/>
<input type="submit" value="submit" />
</form>
<p> </p>
Event handlers cannot return values because they're called asynchronously*.
Your existing hola() function will return immediately and the return statements in the click handlers are only called much later, i.e. when the button is clicked.
My approach would be this, using jQuery deferred objects (jQuery 1.6+):
function hola() {
var def = $.Deferred();
// show the popup confirm form
...
$('input[type=radio]').click(function() {
// determine return value
...
// send it back to anything waiting for it
def.resolve(retval);
});
// return a _promise_ to send back a value some time later
return def.promise();
}
$.get("1.php", { ... }).done(function(data) {
if (...) {
hola().done(function(opt)) { // will be called when the promise is resolved
$("p").html(data + opt);
});
}
});
If you prefer, instead of returning the opt value you could use def.reject() to indicate "non-acceptance" and then use a .fail handler to register a handler to be called for that condition.
You return 1 only in the click function of the radiobutton.
If you want to have a function "hola" that returns 1 if the radiobutton is checked, you simply need something like this:
function hola() {
return $("input:radio[name='yN']:checked").val();
}
hola does not even have a return statement. That's the reason for its not returning anything (more precisely: returning undefined always).
A JavaScript function that does not contain a return statement at all or whose all return statements are within nested functions will never return anything but undefined.
Your are tring to return the value from withing the click callback function. Move the return outside that:
function hola() {
var result;
$("form[name=yN]").show("slow");
$('input[type=radio]').click( function (){
var opt = $(this).attr("value");
if (opt == "1") {
this.checked = false;
$("form[name=yN]").hide("slow");
result = 1;
}
if (opt == 0) {
$("p").html ("ok");
this.checked = false;
}
});
return result;
}