html5 validation on checkboxes - javascript

HTML5 form validation will not cover the situation where, starting from a group of checkboxes, at least one of them is checked. If a checkbox has the required attribute it must be checked, this is what I can get at most.
So I built a workaround that works fine (code in the snippet). The issue is that this works for one group of checkboxes. But I want my code to be valid even if I add more chackboxes groups. I need a suggestion on how to make it valid for multiple groups.
Any idea?
function bindItemsInput() {
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
}
bindItemsInput() // call in window onload
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
A second snippet with the relevant HTML (not working, goal of the question is to fix this). It will have now the same ID for the radio button: that is invalid and is the reason of the question:
function bindItemsInput() {
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
}
bindItemsInput() // call in window onload
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="products[]" value="option1"/>
<input type="checkbox" name="products[]" value="option2"/>
<input type="checkbox" name="products[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
The form will be valid if at least on products[] checkbox and one option[] checkbox is checked. So I need the javascript to run indipendently for option[] and for products[]. If I have selected one item in groups[] but none in products[] then only products will be surrounded by the box and marked for completition

So this what I imagine you are looking for:
const myForm = document.forms['my-form']
myForm.addEventListener('change', bindItemsInput) // global change event listener
function bindItemsInput(e) //
{
if (!e.target.matches('div.checkboxs-wrapper input[type=checkbox]')) return
// to reject unconcerned checkbox
let groupDiv = e.target.closest('div.checkboxs-wrapper')
, radioGroup = groupDiv.querySelector('input[type=radio]')
, checkGroup = groupDiv.querySelectorAll('input[type=checkbox]')
;
radioGroup.checked = [...checkGroup].reduce((flag,chkBx)=>flag || chkBx.checked, false)
}
// ------ verification part-------------------
myForm.onsubmit=e=> // to verify
{
e.preventDefault() // disable submit for testing
console.clear()
// chexboxes checked values:
let options = [...myForm['option[]'] ].reduce((r,s)=>{ if (s.checked) r.push(s.value);return r},[])
, products = [...myForm['product[]'] ].reduce((r,s)=>{ if (s.checked) r.push(s.value);return r},[])
console.log('options = ', JSON.stringify( options ))
console.log('products = ', JSON.stringify( products ))
myForm.reset() // clear anything for new testing
console.log(' form reseted')
}
<form name="my-form">
<div class="checkboxs-wrapper">
<input type="radio" name="rGroup_1" required >
<input type="checkbox" name="option[]" value="option1">
<input type="checkbox" name="option[]" value="option2">
<input type="checkbox" name="option[]" value="option3">
</div>
<div class="checkboxs-wrapper">
<input type="radio" name="rGroup_2" required>
<input type="checkbox" name="product[]" value="product1">
<input type="checkbox" name="product[]" value="product2">
<input type="checkbox" name="product[]" value="product3">
</div>
<button type="submit">submit</button>
</form>

if i understant. so you have to give another id and another name of course, try this:
function bindItemsInput() {
var inputs = $("input[type=checkbox]");
var radios = $("input[type=radio]");
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radios.each( function(){
$(this).checked = $(this).siblings($("input[type=checkbox]:checked")).length > 0;
});
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
}

Using jQuery this can be done with a lot less code.
$(document).ready(function() {
var checkCheckboxesInSameGroup = function() {
var inputs = $(this).children("input[name='option[]']");
var radio = $(this).children("input[name^='radio-for-group']")[0];
radio.checked = inputs.is(":checked");
};
$(".checkboxs-wrapper").on('change', checkCheckboxesInSameGroup);
});
.checkboxs-wrapper {
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="checkboxs-wrapper">
<input type="radio" name="radio-for-group1" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<div class="checkboxs-wrapper">
<input type="radio" name="radio-for-group2" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
</form>

Related

How does one calculate an output-value which needs to be updated from various form-control elements by control-specific calculation-rules?

I need some help as I'm fairly new to JavaScript.
I wish to create a function that calculates a membership fee
I tried making a function in JavaScript that checks whether only one option has been selected, but I have no idea how to make it so that I can calculate the fee if a user is eligible for more than one or all discounts. There is no current JS for the age condition yet (between 60 and 80) as I am unsure how to do it.
function feeCalc() {
var ans = document.getElementById("answer");
if (document.getElementById('medicalCond-yes').checked) {
ans.value = calculate('medicalCond-yes');
}
if (document.getElementById('empstatus-yes').checked) {
ans.value = calculate('empstatus-yes');
}
if (document.getElementById('empstatus-no').checked) {
ans.value = calculate('empstatus-no');
}
if (document.getElementById('medicalCond-no').checked) {
ans.value = calculate('medicalCond-no');
}
}
function calculate(action) {
var standardRate = 10;
var ageRate = 0.1;
var medicalRate = 0.4;
var unemployedRate = 0.3;
var result;
switch (action) {
case 'medicalcond-yes':
discount = (standardRate * studentRate);
result = standardRate - discount;
break;
case 'empstatus-yes':
discount = (standardRate * unemployedRate);
result = standardRate - discount;
break;
case 'empstatus-no':
result = standardRate;
break;
case 'medicalcond-no':
result = standardRate;
break;
}
return result;
}
<div class="form">
<label>
Age
</label>
<input type="range" value="50" min="1" max="100" class="slider" id="age"/>
</div>
<div class="form">
<label>
Do you have any long-term medical conditions
that can affect daily life
</label>
<br/>
<input type="radio" name="status" value="yes" id="medicalCond-yes"/>Yes
<input type="radio" name="status" value="no" id="medicalCond-no"/>No
</div>
<div class="form">
<label>
Are you currently employed?
</label>
<br/>
<input type="radio" name="empstatus" value="yes" id="empstatus-yes"/>Yes
<input type="radio" name="empstatus" value="no" id="empstatus-no"/>No
</div>
<div class="form">
<label>
Membership Fee
</label>
<br/>
Total Fee:
<input type="text" id="answer" readonly/>
<input type="button" value="Calculate" onclick="feeCalc()"/>
</div>
Even though for the OP's problem it looks like over-engineering, the OP's provided code is nevertheless small enough in order to demonstrate the advantages of (more) generic approaches which are ...
Being forced to work with a clean HTML markup/structure as DOM and/or data base.
Decoupling (validation) code from very (business) case specific data like ... not depending ​anymore ...
on very specific DOM-element queries,
on "baked in" data for e.g. validation and edge case handling.
On long term base easier to maintain (in terms of changed business data) and to adapt to e.g. new discount options.
Especially the JavaScript code which implements a generic approach/behavior of cause is larger from the beginning than its very explicitly written competitor. But the former does not tend to grow or does not even need to get touched for new discount options or changed discount values. This part gets covered by cleaner more generic (hence reusable) substructures of the also generic calculator superstructure.
In addition such a generic component based approach automatically enables the usage of more than just one component at/within one and the same document.
function parseJson(str) {
let result;
try {
result = JSON.parse(str);
} catch (exc) {
result = null;
}
return result;
}
function getDevaluationFactorFromRange(formControl, range) {
let factor = 0;
range = parseJson(range);
if (range !== null) {
const controlValue = parseFloat(formControl.value);
Object
.entries(range)
.some(([devaluationKey, { min, max }]) => {
let isStopIteration = false;
if (
(controlValue >= parseFloat(min)) &&
(controlValue <= parseFloat(max))
) {
factor = parseFloat(devaluationKey);
isStopIteration = true;
}
return isStopIteration
});
}
return Number.isFinite(factor) ? factor : 0;
}
function getDevaluationFactor(formControl) {
const { dataset } = formControl;
let rawRange = dataset.devaluationRange ?? null;
let rawFactor = dataset.devaluationFactor ?? null;
let factor = (rawRange !== null)
? getDevaluationFactorFromRange(formControl, rawRange)
: 0;
factor = (
(factor === 0) && (rawFactor !== null) && parseFloat(rawFactor)
) || factor;
factor = Number.isFinite(factor) ? factor : 0;
if (factor !== 0) {
const { type } = formControl;
if ((type === 'radio') || (type === 'checkbox')) {
factor = formControl.checked ? factor : 0;
}
}
return factor;
}
function computeCurrentFee(rootNode, elmFee, baseFee) {
return Array
// array from `HTMLFormControlsCollection`
.from(rootNode.elements)
// calculate currrent fee from each form element's data
.reduce((currentFee, formControl) => {
return currentFee - (baseFee * getDevaluationFactor(formControl));
}, baseFee);
}
function updateCurrentValueAtBoundFeeContext(/*evt*/) {
const { rootNode, elmFee, baseFee } = this;
elmFee.value = computeCurrentFee(rootNode, elmFee, baseFee);
}
function displayCurrentValueAtBoundAgeContext(/*evt*/) {
const { elmRange, elmOutput } = this;
elmOutput.value = elmRange.value;
}
function initializeCurrentAgeDisplay(rootNode) {
const ageNode = rootNode.querySelector('[data-age-range]');
if (ageNode) {
const elmRange = ageNode.querySelector('input[type="range"]');
const elmOutput = ageNode.querySelector('output');
if (elmRange && elmOutput) {
const target = { elmRange, elmOutput };
const boundContextHandler =
displayCurrentValueAtBoundAgeContext.bind(target);
elmRange.addEventListener('input', boundContextHandler);
rootNode.addEventListener('reset', () =>
// decouple custom dom refresh from the system's one.
setTimeout(boundContextHandler, 0)
);
// display initial age value.
// // displayCurrentValueAtBoundAgeContext.call(target);
boundContextHandler();
}
}
}
function initializeMembershipFeeCalculator(rootNode) {
const DEFAULT_BASE_FEE = 10;
initializeCurrentAgeDisplay(rootNode);
const elmFeeValue = rootNode.querySelector('[data-fee-value]');
if (elmFeeValue) {
const baseFee = parseFloat(rootNode.dataset.baseFee);
const target = {
rootNode,
elmFee: elmFeeValue,
baseFee: Number.isFinite(baseFee) ? baseFee : DEFAULT_BASE_FEE,
};
const boundContextHandler =
updateCurrentValueAtBoundFeeContext.bind(target);
rootNode.addEventListener('input', boundContextHandler);
rootNode.addEventListener('reset', () =>
// decouple custom dom refresh from the system's one.
setTimeout(boundContextHandler, 0)
);
// compute initial fee value.
// // updateCurrentValueAtBoundFeeContext.call(target);
boundContextHandler();
rootNode.addEventListener('submit', evt => {
evt.preventDefault();
return false;
});
}
}
function main() {
document
.querySelectorAll('form[data-membership-fee-calculator]')
.forEach(initializeMembershipFeeCalculator);
}
main();
body, form {
margin: 0;
padding: 0;
}
form {
float: left;
width: 50%;
margin-top: -2px;
}
fieldset {
position: relative;
margin: 0 0 2px 0;
padding: 0 10px 2px 10px;
}
fieldset p {
margin: 1px 0 2px 0;
}
fieldset output {
color: #333;
font-weight: bolder;
}
label {
display: inline-block;
}
input[type="range"] {
width: 70%;
}
[data-age-range] output {
display: inline-block;
overflow: hidden;
max-width: 25%;
max-height: 1.2em;
position: relative;
top: 1px;
}
[type="reset"] {
position: absolute;
right: 4px;
top: -4px;
}
<form data-membership-fee-calculator data-base-fee="10">
<fieldset data-age-range>
<legend>
Age
</legend>
<input
type="range"
name="age" id="age"
value="50" min="1" max="100"
data-devaluation-range='{"0.1":{"min":60,"max":80}}'
/>
<output for="age">### not yet computed ###</output>
</fieldset>
<fieldset>
<p>
Do you have any long-term medical conditions
that can affect daily life?
</p>
<label>
<input
type="radio"
name="status"
value="yes"
data-devaluation-factor="0.4"
/>
<span class="label-copy">
Yes
</span>
</label>
<label>
<input type="radio" name="status" value="no" />
<span class="label-copy">
No
</span>
</label>
</fieldset>
<fieldset>
<p>
Are you currently employed?
</p>
<label>
<input
type="radio"
name="empstatus"
value="yes"
data-devaluation-factor="0.3"
/>
<span class="label-copy">
Yes
</span>
</label>
<label>
<input type="radio" name="empstatus" value="no" />
<span class="label-copy">
No
</span>
</label>
</fieldset>
<fieldset>
<legend>
Membership Fee
</legend>
<label>
<span class="label-copy">
Total Fee:
</span>
<output data-fee-value>### not yet computed ###</output>
</label>
<button type="reset">Restore base fee</button>
</fieldset>
</form>
<form data-membership-fee-calculator data-base-fee="20">
<fieldset data-age-range>
<legend>
Age
</legend>
<input
type="range"
name="age" id="age"
value="21" min="1" max="100"
data-devaluation-range=
'{"0.05":{"min":60,"max":69},"0.1":{"min":70,"max":79},"0.2":{"min":80,"max":120}}'
/>
<output for="age">### not yet computed ###</output>
</fieldset>
<fieldset>
<p>
Do you have any long-term medical conditions
that can affect daily life?
</p>
<label>
<input
type="radio"
name="status"
value="yes"
data-devaluation-factor="0.3"
/>
<span class="label-copy">
Yes
</span>
</label>
<label>
<input type="radio" name="status" value="no" />
<span class="label-copy">
No
</span>
</label>
</fieldset>
<fieldset>
<p>
Are you currently employed?
</p>
<label>
<input
type="radio"
name="empstatus"
value="yes"
data-devaluation-factor="0.3"
/>
<span class="label-copy">
Yes
</span>
</label>
<label>
<input type="radio" name="empstatus" value="no" />
<span class="label-copy">
No
</span>
</label>
</fieldset>
<fieldset>
<legend>
Membership Fee
</legend>
<label>
<span class="label-copy">
Total Fee:
</span>
<output data-fee-value>### not yet computed ###</output>
</label>
<button type="reset">Restore base fee</button>
</fieldset>
</form>
Instead of switch-case routing into a single branch, you probably want to check through all cases in one go.
function feeCalc() {
var ans = document.getElementById("answer");
ans.value = calculateRate();
}
function calculateRate() {
let discount = 0;
const age = Number(document.getElementById('age').value);
if (age >= 60 && age <= 80) {
discount += 0.1;
}
if (document.getElementById('medicalCond-yes').checked) {
discount += 0.4;
}
if (document.getElementById('empstatus-no').checked) {
discount += 0.3;
}
return 1 - discount;
}
<div class="form">
<label>
Age
</label>
<input type="range" value="50" min="1" max="100" class="slider" id="age"/>
</div>
<div class="form">
<label>
Do you have any long-term medical conditions
that can affect daily life
</label>
<br/>
<input type="radio" name="status" value="yes" id="medicalCond-yes"/>Yes
<input type="radio" name="status" value="no" id="medicalCond-no"/>No
</div>
<div class="form">
<label>
Are you currently employed?
</label>
<br/>
<input type="radio" name="empstatus" value="yes" id="empstatus-yes"/>Yes
<input type="radio" name="empstatus" value="no" id="empstatus-no"/>No
</div>
<div class="form">
<label>
Membership Fee
</label>
<br/>
Total Fee:
<input type="text" id="answer" readonly/>
<input type="button" value="Calculate" onclick="feeCalc()"/>
</div>

Checkbox checked input required , if checkbox is unchecked input not required

This is my html
<input type="checkbox" name="checked" id="check" onclick="unlocking()">
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display:none;">
<input type="text" name="Name" value="Name" id="inside" required>
<input type="text" name="email" value="email" id="inside" required>
<input type="text" name="Adress" value="Adress" id="inside" required>
</fieldset>
And this is my js with the function to hide and show the fieldset.
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
if(checkBox.checked) {
form.style.display="block";
}else {
form.style.display="none";
}
}
If the fieldset is show i want the input to be required and if not just to skip it.
You could loop through each child and set its required attribute to either true or false depending on if the checkbox is checked or not, like so:
for (child of form.children) {
child.required = true;
}
Please check the snippet below:
function unlocking() {
var checkBox = document.getElementById("check");
var form = document.getElementById("unlock");
if (checkBox.checked) {
form.style.display = "block";
for (child of form.children) {
child.required = true;
console.log(child);
}
} else {
form.style.display = "none";
for (child of form.children) {
child.required = false;
console.log(child);
}
}
}
<input type="checkbox" name="checked" id="check" onclick="unlocking()" />
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display: none;">
<input type="text" name="Name" value="Name" id="inside" />
<input type="text" name="email" value="email" id="inside" />
<input type="text" name="Adress" value="Adress" id="inside" />
</fieldset>
//element.setAttribute("required", ""); turns required on
//element.removeAttribute("required"); turns required off
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
var inputs = document.querySelectorAll('input[type=text]')
if(checkBox.checked) {
form.style.display="block";
for(var i = 0; i < inputs.length; i++)
inputs[i].setAttribute("required", "");
}else {
form.style.display="none";
for(var i = 0; i < inputs.length; i++)
inputs[i].removeAttribute("required");
}
}

How to .focus() a .srcElement / childNode in Javascript

I am attempting to .focus() a text box when a user clicks on a larger div. The input is a child of the div and I can locate the element, however Javascript throws an error upon attempting the .focus() function.
I have already tried to directly .focus() the childNodes as shown but I cannot 1) focus the node and 2) locate the input tag in the list.
function clickables() {
let clickables = document.getElementsByClassName("clickables")
for (var i = 0; i < clickables.length; i++) {
clickables[i].addEventListener("click", function(e) {
const target = e.srcElement.childNodes;
target.focus(input); // .getElementsByTagNames isn't working
});
}
}
clickables();
The expected results is that upon clicking the larger div it will focus the input inside of it, the actual result is java script tossing an error.
First you should be using inputs.length and not clickables.length.
Second you need to pick which child to .focus().
function clickables() {
let inputs = document.getElementsByClassName("clickables");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function(e) {
const target = e.srcElement.firstElementChild;
target.focus();
});
}
}
clickables();
.clickables {
background-color: #999;
padding: 10px;
}
<div class="clickables">
<input type="text" value="first">
<input type="text" value="second">
<input type="text" value="third">
</div>
In this example I am picking the first element to focus on.
UPDATE
As stated you need to know which child you want to call .focus() on.
Let's say that you use the attribute autofocus on the child you want to receive focus then you can do this:
function clickables() {
let inputs = document.getElementsByClassName("clickables");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function(e) {
let target = e.srcElement.querySelector('[autofocus]');
if (!target) {
target = e.srcElement.firstElementChild;
}
target.focus();
});
}
}
clickables();
.clickables {
background-color: #999;
padding: 10px;
}
<div class="clickables">
<input type="text" value="first">
<input type="text" value="second" autofocus>
<input type="text" value="third">
</div>
<hr>
<div class="clickables">
<input type="text" value="first">
<input type="text" value="second">
<input type="text" value="third" autofocus>
</div>
<hr>
<div class="clickables">
<input type="text" value="first">
<input type="text" value="second">
<input type="text" value="third">
</div>
Since #sean indicated, correctly, that the above example is a miss use of autofocus you should probably use a different attribute or here is an alternate way to accomplish the same thing:
function clickables() {
let inputs = document.getElementsByClassName("clickables");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function(e) {
let index = Number(e.srcElement.getAttribute('focus')||'1')-1;
console.log(index)
let target = e.srcElement.children[index];
target.focus();
});
}
}
clickables();
.clickables {
background-color: #999;
padding: 10px;
}
<div class="clickables" focus="2">
<input type="text" value="first">
<input type="text" value="second">
<input type="text" value="third">
</div>
<hr>
<div class="clickables" focus="3">
<input type="text" value="first">
<input type="text" value="second">
<input type="text" value="third">
</div>
<hr>
<div class="clickables">
<input type="text" value="first">
<input type="text" value="second">
<input type="text" value="third">
</div>
I think the attribute is the best solution since you can guarantee setting .focus on the correct/expected element.
You could try something like
function clickables() {
let inputs = document.getElementsByClassName("clickables")
for (var i = 0; i < clickables.length; i++) {
clickables[i].addEventListener("click", function(e) {
const childElements = e.srcElement.children;
for (var j = 0; j < childElements.length; j++) {
childElements[j].focus();
}
});
}
}
clickables();

Get Radio Button Value into another function in javascript

Here is my radio buttons' code:
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>
and I want to get value of button in following script audio src, so by clicking on radio button I can switch between media folder:
function PlayVerse(surat,n) {
var aud=document.getElementById("myaudio");
aud.src= "http://data.quranacademy.com/AUDIOS/Media-/01_"
+TxtFormat(surat,"000")
+"_"
+TxtFormat(n,"000")
+".mp3";
}
var x = document.getElementsByTagName("IMG");
var i;
for (i = 0; i < x.length; i++) {
x[i].style = 'display: inline-block; '
+'border: 1px solid #ddd; '
+'border-radius: 4px; padding: 5px;';
}
Try something like this with plain javascript
function PlayVerse(){
var radio = document.getElementsByName('sp');
var check;
for (var i = 0, length = radio.length; i < length; i++)
{
if (radio[i].checked)
{
console.log(radio[i].value);
check = radio[i].value;
break;
}
}
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
if you want to do something by clicking on radio button it can help you
window.onload=function(){
(function (){
var radios = document.getElementsByName('sp');
radios.forEach(function(radio){
radio.onclick = function(){
alert(this.value);
//do something
}
})
})();
}
Red color
Yelow color
<p id="demo"></p>
<script>
function myFunction() {
//var x = document.getElementById("myRadioRed").value;
//document.getElementById("demo").innerHTML = x;
var radios = document.getElementsByName('colors');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
document.getElementById("demo").innerHTML = radios[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
}
</script>
<input type="radio" name="colors" value="red" id="myRadioRed" onchange="myFunction()" checked="checked" />Red color
<input type="radio" name="colors" value="yellow" id="myRadioYellow" onchange="myFunction()" />Yelow color
<p id="demo"></p>
function PlayVerse() {
var selected_radio_button_value = getRadioButtonValue("sp");
alert(selected_radio_button_value);
}
function getRadioButtonValue(elementName) {
var array1 = document.getElementsByName(elementName), rValue = null;
array1.forEach(function(element) {
if( element.checked ) {
rValue = element.value;
return true;
}
});
return rValue;
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
here you can get value of radio button using javascript i have created an function which will give you value of selected radio button you can store that value in variable and access it anywhere you want you can do it in both way
Here is how you can get value of radio button which one is checked. Get all NodeList by getElementsByName and iterate over each one and check if it is checked.
function getVal(elementName) {
var radios = document.getElementsByName(elementName), rValue = null;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
rValue = radios[i].value;
break;
}
}
console.log(rValue);
}
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>

get radio value with javascript

hello everyone I can't get the radio input value here is my code :
the alert isn't running
I want to do a real time calculation that shows the total to pay and I couldn't handle the radio values I appreciate your help thanks :D
function transfer()
{
var vip=document.getElementByName('mercedes');
for (var i = 0, length = vip.length; i < length; i++)
{
if (vip[i].checked)
{
alert(vip[i].value);
break;
}
}
}
<div class="form-group">
<label for="f1-about-yourself">Mercedes VIP transfer*:</label> <br>
<input type="radio" name="mercedes" id="yes" value="yes"
onclick="transfer()">
<label for="yes">Yes:</label>
<input type="radio" name="mercedes" id="no" value="no" checked="" onclick="transfer()">
<label for="no">No:</label>
</div>
function transfer()
{
var vip=document.getElementsByName('mercedes');
for (var i = 0, length = vip.length; i < length; i++)
{
if (vip[i].checked)
{
alert(vip[i].value);
break;
}
}
}
<div class="form-group">
<label for="f1-about-yourself">Mercedes VIP transfer*:</label> <br>
<input type="radio" name="mercedes" id="yes" value="yes"
onclick="transfer()">
<label for="yes">Yes:</label>
<input type="radio" name="mercedes" id="no" value="no" onclick="transfer()">
<label for="no">No:</label>
</div>
In addition to the already given answer that did fix the OP's problem the OP might think about separation of markup and code, thus not using inline code within html element markup.
Making use of the html form element that then hosts specific form controls like input, button etc. is highly advised too. Making
use of the "DOM Level 0" form collection also is not outdated. Event delegation as provided with the next example for instance helps if there will be other controls added to a form dynamically - one does not need to take care about registering event handlers to each newly appended form control. And last, registering to 'change' events will capture every change to the radio collection ...
function isMercedesTransferType(elmNode) {
return ((elmNode.type === 'radio') && (elmNode.name === 'mercedes'));
}
function handleVipTransferChange(evt) {
var elmNode = evt.target;
if (isMercedesTransferType(elmNode) && elmNode.checked) {
console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
}
}
function initializeVipTransfer() {
document.forms['mercedes-vip-transfer'].addEventListener('change', handleVipTransferChange, false);
}
initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" name="mercedes-vip-transfer">
<legend>Mercedes VIP transfer*:</legend>
<label>
<input type="radio" name="mercedes" value="yes">
<span>Yes</span>
</label>
<label>
<input type="radio" name="mercedes" value="no">
<span>No</span>
</label>
</form>
Another way of dealing with initializing the required form controls directly will be demonstrated hereby ...
function isMercedesTransferType(elmNode) {
return ((elmNode.type === 'radio') && (elmNode.name === 'mercedes'));
}
function handleVipTransferChange(evt) {
var elmNode = evt.target;
if (elmNode.checked) {
console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
}
}
function initializeVipTransfer() {
var list = document.forms['mercedes-vip-transfer'].elements['mercedes'];
Array.from(list).filter(isMercedesTransferType).forEach(function (elmNode) {
elmNode.addEventListener('change', handleVipTransferChange, false);
});
}
initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" name="mercedes-vip-transfer">
<legend>Mercedes VIP transfer*:</legend>
<label>
<input type="radio" name="mercedes" value="yes">
<span>Yes</span>
</label>
<label>
<input type="radio" name="mercedes" value="no">
<span>No</span>
</label>
</form>
... and just in order to round it up, if there is an "up to date" DOM, one might consider making use of modern DOM queries via querySelector and/or querySelectorAll ...
function handleVipTransferChange(evt) {
var elmNode = evt.target;
if (elmNode.checked) {
console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
}
}
function initializeVipTransfer() {
var list = document.querySelectorAll('#mercedes-vip-transfer [type="radio"][name="mercedes"]');
Array.from(list).forEach(function (elmNode) {
elmNode.addEventListener('change', handleVipTransferChange, false);
});
}
initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" id="mercedes-vip-transfer">
<legend>Mercedes VIP transfer*:</legend>
<label>
<input type="radio" name="mercedes" value="yes">
<span>Yes</span>
</label>
<label>
<input type="radio" name="mercedes" value="no">
<span>No</span>
</label>
</form>

Categories