Loop through several check boxes and update inputs on results - javascript

I have several check boxes that I need to post the value of when a form is submitted. There is 4 at the moment and could be more so I was thinking of instead of adding individual functions is it possible to loop through them all and update respected fields in one go. I have seen a similar thing with form population with google maps but not quite the same. So I have a input like so:
function myCheck() {
var checkBox = document.getElementById("email_alerts");
if (checkBox.checked == true){
document.getElementById('form_email_alerts').value = 'YES'
} else {
document.getElementById('form_email_alerts').value = 'NO'
}
}
<ul class="confirm details">
<li class="selected">Please confirm your contact preferences</li>
<li><input type="checkbox" id="email_alerts" value="YES" onclick="myCheck()"> Receive email alerts</li>
<li><input type="checkbox" id="sms_alerts" value="NO" onclick="myCheck()"> Receive free SMS alerts</li>
<li><input type="checkbox" id="offers_alerts" value="NO" onclick="myCheck()"> Receive offers and discounts</li>
<li><input type="checkbox" id="instant_alerts" value="NO" onclick="myCheck()"> Receive Instant Notifications</li>
</ul>
<input id="form_email_alerts" type="hidden" value="">
<input id="form_sms_alerts" type="hidden" value="">
<input id="form_offers_alerts" type="hidden" value="">
<input id="form_instant_alerts" type="hidden" value="">
I could add this 4 times or more with different ID but can I just loop through so be quicker and cleaner? I have tried but cant get it to change the hidden values. Thanks

As your IDs have a good format, you can just loop all checkboxes:
document.querySelectorAll('input[type=checkbox]').forEach(e => {
e.onchange = () => document.getElementById('form_' + e.id).value = e.checked ? 'YES' : 'NO';
});
<ul class="confirm details">
<li class="selected">Please confirm your contact preferences</li>
<li><input type="checkbox" id="email_alerts" value="YES"> Receive email alerts</li>
<li><input type="checkbox" id="sms_alerts" value="NO"> Receive free SMS alerts</li>
<li><input type="checkbox" id="offers_alerts" value="NO"> Receive offers and discounts</li>
<li><input type="checkbox" id="instant_alerts" value="NO"> Receive Instant Notifications</li>
</ul>
<input id="form_email_alerts" type="text" value="NO">
<input id="form_sms_alerts" type="text" value="NO">
<input id="form_offers_alerts" type="text" value="NO">
<input id="form_instant_alerts" type="text" value="NO">

You could do that by looping on all your checkboxes and adding an event listener on each, updating the other input fields.
PS: here I removed the hidden type for you to see the value of every input.
document.querySelectorAll('ul.details li input').forEach(input => {
input.addEventListener('change', function(){
let finalInput = document.querySelector('#form_'+input.id);
if(finalInput) finalInput.value = input.checked ? 'YES' : 'NO';
});
});
<ul class="confirm details">
<li class="selected">Please confirm your contact preferences</li>
<li><input type="checkbox" id="email_alerts" value="YES"> Receive email alerts</li>
<li><input type="checkbox" id="sms_alerts" value="NO"> Receive free SMS alerts</li>
<li><input type="checkbox" id="offers_alerts" value="NO"> Receive offers and discounts</li>
<li><input type="checkbox" id="instant_alerts" value="NO"> Receive Instant Notifications</li>
</ul>
<input id="form_email_alerts" value="">
<input id="form_sms_alerts" value="">
<input id="form_offers_alerts" value="">
<input id="form_instant_alerts" value="">

Related

I need some help on validating the below code in javascript

I would like to validate the below code in js so that the user has to check one but i do not know how to. The form name is 'registration'
<li>
<input type="checkbox" name="en" value="en" />
<span>English</span>
</li>
<li>
<input type="checkbox" name="nonen" value="noen" />
<span>Non English</span>
</li>
Use an input of type radio instead.
Here is a link to the MDN documentation, basically all inputs of type radio that have the same name property are grouped together and the user can select only one of them.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
You could try this one
<input type="radio" name="raden" id="english" checked>
<label for="english">English</label>
<input type="radio" name="radnon" id="nonenglish">
<label for="nonenglish">Non-English</label>
<li><input type="checkbox" name="en" value="en" /><span>English</span></li>
<li><input type="checkbox" name="en" value="en" /><span>Non English</span></li>
In check box name must be same if all check boxes are selected. Try thid code.
<li>
<input type="radio" name="nonen" value="en" checked/>
<span>English</span>
</li>
<li>
<input type="radio" name="nonen" value="noen"/>
<span>Non English</span>
<li>
<input type="radio" name="nonen" value="en" checked/>
<span>English</span>
</li>
<li>
<input type="radio" name="nonen" value="noen"/>
<span>Non English</span>

JavaScript/HTML - Assign a value to selected radio button

The case is basically like this:
I have 2 questions (have to answer both questions):
1. Do you smoke? a. Yes b. No
2. Do you drink? a .Yes b. No
If the user choose a. in question 1, then value will be 2
If the user choose b. in question 1, then value will be 1
If the user choose a. in question 2, then value will be 2
If the user choose b. in question 2, then value will be 1
After that, I will be sum up the value for selected radio buttons of both questions and display it.
The code for the radio buttons will be:
<ul>
<li>Do you smoke cigarettes?<br>
<input type="radio" name="smoke" id="yes1" value="Y" checked="checked">
<label for="yes1">Yes</label>   
<input type="radio" name="smoke" id="no1" value="N">
<label for="no1">No</label><br>
</li>
<li>Do you drink?<br>
<input type="radio" name="drink" id="yes2" value="Y" checked="checked">
<label for="yes2">Yes</label>   
<input type="radio" name="drink" id="no2" value="N">
<label for="no2">No</label><br><br></li>
</ul>
I know that the value in the radio button can be changed but I want to assign value in the javascript function. (The value in the radio button has it's own purpose.)
That's it. Even though I googled it around but still no solution that solve my problem. Any advice or suggestion will be appreciated.
Thank you in advance.
i think this is what you want. please let me.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<body>
<ul>
<li>Do you smoke cigarettes?<br>
<input type="radio" name="smoke" id="yes1" data-vale = '2' value="Y" checked="checked">
<label for="yes1">Yes</label>   
<input type="radio" name="smoke" id="no1" data-vale = '1' value="N">
<label for="no1">No</label><br>
</li>
<li>Do you drink?<br>
<input type="radio" name="drink" id="yes2" data-vale = '2' value="Y" checked="checked">
<label for="yes2">Yes</label>   
<input type="radio" name="drink" id="no2" data-vale = '1' value="N">
<label for="no2">No</label><br><br>
</li>
</ul>
<input type="button" value="Get Value">
<script type="text/javascript">
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue = $("input[name='smoke']:checked").attr('data-vale');
var radioValue2 = $("input[name='drink']:checked").attr('data-vale');
console.log( parseInt(radioValue) +parseInt(radioValue2) )
});
});
/*
* OR if you dont want to change HTML and may be this will work for you
*
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue = $("input[name='smoke']:checked").val() == 'Y' ? 2 : 1;
var radioValue2 = $("input[name='drink']:checked").val() == 'Y' ? 2 : 1;
console.log( parseInt(radioValue) +parseInt(radioValue2) )
});
});
*/
</script>
</body>
</html>
Im not sure that i understand you right and i do not now why you want something like this. But this should work
<ul>
<li>Do you smoke cigarettes?<br>
<input type="radio" name="smoke" id="yes1" value="Y" checked="checked" onchange="yesSelected(this)">
<label for="yes1">Yes</label>   
<input type="radio" name="smoke" id="no1" value="N" onchange="noSelected(this)">
<label for="no1">No</label><br>
</li>
<li>Do you drink?<br>
<input type="radio" name="drink" id="yes2" value="Y" checked="checked" onchange="yesSelected(this)">
<label for="yes2">Yes</label>   
<input type="radio" name="drink" id="no2" value="N" onchange="noSelected(this)">
<label for="no2">No</label><br><br></li>
</ul>
<script type="text/javascript">
function yesSelected(input){
input.value = 2
console.log(input.value)
}
function noSelected(input){
input.value = 1
console.log(input.value)
}
</script>
From my understanding you could satisfy this with a script that uses event listeners, specifically the change of value in your radio buttons.
I would suggest also modeling a simple structure to capture your data. The following could be implemented. Instead of using an id for the question, associate them with an html data attribute. In this case we could specify something like data-question="1". It would also be more practical to assign the value you intend to use on the input element from the start. So instead of using value="Y" try value="2" or value="1". Now that we have our html set up we will use another structure, this time to capture the value. We declare a const question of type array that holds objects. Each object represents a question, the id property is the value we associate with the data-question attribute on our input. To find the inputs we use the document.querySelectorAll(selector) method because two radio buttons share the same attribute. After we simply attach our eventlistener with a handler function that just update our answer for that question. if you wanted to add the result you could use a forEach method on the question const and log it to the console or present it where you find appropriate. Hope this helps
`
<ul>
<li>Do you smoke cigarettes?<br>
<input type="radio" name="smoke" data-question="1" value="2" checked="checked">
<label for="yes1">Yes</label>   
<input type="radio" name="smoke" data-question="1" value="1">
<label for="no1">No</label><br>
</li>
<li>Do you drink?<br>
<input type="radio" name="drink" data-question="2" value="2" checked="checked">
<label for="yes2">Yes</label>   
<input type="radio" name="drink" data-question="2" value="1">
<label for="no2">No</label><br><br></li>
</ul>
<script>
const questions = [{id:1, answer:undefined},{id:2, answer: undefined}]
for(current of questions){
let inputs = document.querySelectorAll('[data-question="'+current.id+'"]');
for(input of inputs){
input.addEventListener('change',function(e){ current.answer = e.target.value})
}
}
</script>
`

change value in input field using radio button Jquery

I need to find a way to enable the input field with a value and change it or deactivate it with value 0
$("#tax").value(19).prop("disabled",false);
$("#tax").value(0).prop("disabled",true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>tax %</label><br>
<input type="radio" checked>Get tax
<input type="radio"> No tax
<input type="text" class="form-control" name="tax" id="tax" required="">
Update input box value on changing radio button
$('input[name=taxs]').change(function (e) {
$('#tax_value').val(e.target.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><input type="radio" name="taxs" value="10"> 10</li>
<li><input type="radio" name="taxs" value="20"> 20</li>
<li><input type="radio" name="taxs" value="30"> 30</li>
<li><input type="radio" name="taxs" value=""> No Tax</li>
</ul>
<input type="text" id="tax_value">
replace $("#tax").value(...
with $("#tax").val(...

Adding validations to see if radio button is not selected, all the questions is compulsory

I have the following code in which there are 5 questions. I want that all 5 questions should be answered, in case any questions is not filled, user gets validation.
question 1
<ul class="option">
<li> <input type="radio" name="question1" id="sd1" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question1" id="d1" value="2">Disagree</li>
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Dis<li>agree</li>
<li> <input type="radio" name="question1" id="a1" value="4">Agree</li>
<li> <input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li></ul>
<br/><br/>
question 2
<ul class="option">
<li> <input type="radio" name="question2" id="sd2" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question2" id="d2" value="2">Disagree</li>
<li> <input type="radio" name="question2" id="n2" value="3">Neither Agree Nor Disagree</li>
<li> <input type="radio" name="question2" id="a2" value="4">Agree</li?
<li> <input type="radio" name="question2" id="sa2" value="5">Strongly Agree
</li></ul>
<br/><br/>
javascript code is
// Delegate submit action
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.option').each(function () {
// Question text
var question = $(this).prev();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question.text());
question.css('color', 'red'); // Highlight unanswered question
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
I'm getting alert as a blank, only one line is written please answer following questions but no questions number inside
Just put your questions in a tag ( I have put it in span tag ) with an unique id and it should work with your code.
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.option').each(function () {
// Question text
var question = $(this).prev();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
//alert(JSON.stringify($(this).siblings()));
unanswered.push(question.text());
question.css('color', 'red'); // Highlight unanswered question
validate = false;
}
});
if (unanswered.length > 0) {
//alert(unanswered);
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
<body>
<form id='form' action='#' method='post'>
<span id='q1'>question 1</span>
<ul class="option">
<li> <input type="radio" name="question1" id="sd1" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question1" id="d1" value="2">Disagree</li>
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Dis<li>agree</li>
<li> <input type="radio" name="question1" id="a1" value="4">Agree</li>
<li> <input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li></ul>
<br/><br/>
<span id='q2'>question 2</span>
<ul class="option">
<li> <input type="radio" name="question2" id="sd2" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question2" id="d2" value="2">Disagree</li>
<li> <input type="radio" name="question2" id="n2" value="3">Neither Agree Nor Disagree</li>
<li> <input type="radio" name="question2" id="a2" value="4">Agree</li>
<li> <input type="radio" name="question2" id="sa2" value="5">Strongly Agree
</li></ul>
<input type='submit' value='submit'>
</form>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</body>

need to enable submit button

i have a small form. I want enable submit button when all the all the radio button is selected.
below is my code html
<form action="#" id="form1" method="post">
<ul>
<li>
<h3>Here’s what I want:<strong class="result1"></strong></h3>
<div>
<span><input type="radio" value="Cash Back rewards" name="want" id="01" /><label for="01">Cash Back rewards</label></span>
<span><input type="radio" value="Travel rewards" name="want" id="02" /><label for="02">Travel rewards</label></span>
<span><input type="radio" value="Gas rewards" name="want" id="03" /><label for="03">Gas rewards</label></span>
<span><input type="radio" value="Shopping rewards" name="want" id="04" /><label for="04">Shopping rewards</label></span>
</div>
</li>
<li>
<h3>Here’s my credit story: <strong class="result2"></strong></h3>
<div>
<span><input type="radio" value="I’m new to credit" name="story" id="05" /><label for="05">I’m new to credit</label></span>
<span><input type="radio" value="I pay my bills on time" name="story" id="06" /><label for="06">I pay my bills on time</label></span>
<span><input type="radio" value="I’ve had credit issues in the past" name="07" id="issues" /><label id="07">I’ve had credit issues in the past</label></span>
</div>
</li>
<li>
<h3>Here’s what I carry:</h3>
<span><input type="radio" value="I have a credit card with a good record" name="carry" id="08" /><label for="08">I have a credit card with a good record</label></span>
<span><input type="radio" value="I don’t have a credit card with a good record" name="carry" id="09" /><label for="09">I don’t have a credit card with a good record</label></span>
</li>
</ul>
<input type="submit" value="" name="" class="find" />
</form>
i am weak in javascript please advise me.
one more thing if li is not fix it will generate dynamically, so what i will have to do. basically every li is one quetion and radio button is option. so the question will be generate dynamically it can be any no. its not fix
$(':radio').on('change', function(e) {
var len = $(':radio:checked').length;
if( len === 3 ) {
$('input[type=submit].find').prop('disabled', false);
}
});
DEMO
Or again:
$('input[type=radio]').on('change', function(){
if(
$('input[name=want]').is(':checked') &&
$('input[name=story]').is(':checked') &&
$('input[name=carry]').is(':checked')
){
$('input[type=submit]').prop('disabled', false)
}
});
There 4 groups of radio buttons in your markup, you can check if the length of selcted radio buttons are equal to the length of radio groups, and if that is true, enable the submit button, try the following:
$(document).on('change', 'input[type=radio]', function(){
if ($('input[type=radio]:checked').length == 4) {
$('input[type=submit]').prop('disabled', false)
}
})
DEMO
Please note that the third element in the story group has a different name attribute.
<span><input type="radio" value="I’m new to credit" name="story" id="05" /><label for="05">I’m new to credit</label></span>
<span><input type="radio" value="I pay my bills on time" name="story" id="06" /><label for="06">I pay my bills on time</label></span>
<span><input type="radio" value="I’ve had credit issues in the past" name="07" id="issues" /><label id="07">I’ve had credit issues in the past</label></span>
--------------------------^

Categories