JavaScript/HTML - Assign a value to selected radio button - javascript

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>
`

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>

Loop through several check boxes and update inputs on results

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="">

html input type radio checked doesn't work with ng-model

I want my radio-input in the html preselected. It works fine when i just write:
<input type="radio" name="trackingOption" id="trackingOption" value="1"> Yes
<input type="radio" name="trackingOption" id="trackingOption" value="0" checked=""> No
But as soon as I add my ng-model for interact with my javaScript, the checked Option is gone
<input type="radio" name="trackingOption" ng-model="tracking" id="trackingOption" value="0" checked=""> No
Anyone know why "checked" doesn't work anymore with ng-model?!
you assign the value=0 that's why checked gone,so dont assign like that
The solution is to insert a ng-init expression which says which ng-model has the ng-value
<div ng-init="tracking=0">
<input type="radio" name="trackingOption" ng-model="tracking" ng-value="1" id="trackingOption" value="1"> Yes
<input type="radio" name="trackingOption" ng-model="tracking" ng-value="0" id="trackingOption" value="0" checked=""> No
</div>
You should be able to interact with your model:
<input type="radio" name="trackingOption" ng-model="tracking" id="trackingOption" value="0"> No
<input type="radio" name="trackingOption" ng-model="tracking" id="trackingOption2" value="1"> Yes
The value is: {{tracking}}
See that the value of tracking gets updated each time you click on the other input.
Then you need this part in your directive:
scope.$watch('tracking', (newValue, oldValue) => { //doyourstuffhere } )
Is this what you want?

Radio button malfunctioning when used inside label tag

i am working on html and CSS. i have to add 5 radio buttons to my page and i have added within <label> tag. but when i look for the page. it shows all the radio buttons selected and also i am unable to unselect it. the thing is i need only one radio button selected at a time. here is my code.
<label class="radio"><input type="radio"> Pepse</label>
<label class="radio"><input type="radio"> Coke</label>
<label class="radio"><input type="radio">Mirinda</label>
<label class="radio"><input type="radio">Maaza </label>
radio buttons require a common name. If you don't give them a name attribute, each radio button essentially becomes a one-way checkbox. You can select them, but you can't UNselect them.
<input type="radio" name="foo" value="1" />
<input type="radio" name="foo" value="2" />
<input type="radio" value="3" />
In this case, the two foo radio buttons will be linked internally because they are both named the same, but the one with value 3 will be completely independent and act as your are.
Add a group name.
jsFiddle
<label class="radio"><input name="drinks" type="radio">Pepse</label>
<label class="radio"><input name="drinks" type="radio">Coke</label>
<label class="radio"><input name="drinks" type="radio">Mirinda</label>
<label class="radio"><input name="drinks" type="radio">Maaza </label>
<label class="radio"><input name="drinks" type="radio">Milk Frothers</label>
1.agroup of radios need a name so that the browser know which one is selected
2.if u want to put the label outside of the input u can use the for attribute
to tell the browser that this label is for that radio with the same id
<label for="a">a</label>
<input type="radio" name="aname" id="a" value="a"><br>
<label for="b">b</label>
<input type="radio" name="aname" id="b" value="b"><br>
<label for="c">c</label>
<input type="radio" name="aname" id="c" value="c"><br>
<label for="d">d</label>
<input type="radio" name="aname" id="d" value="d"><br>
but i also prefer radios inside labels so
<label><input type="radio" name="aname" value="a">a</label><br>
<label><input type="radio" name="aname" value="b">b</label><br>
<label><input type="radio" name="aname" value="c">c</label><br>
<label><input type="radio" name="aname" value="d">d</label><br>
<label><input type="radio" name="aname" value="e">e</label><br>
3.in a common way they also need a value, except ur using js
<label><input type="radio" name="aname">a</label><br>
<script>
document.write(document.getElementsByTagName('label')[0].childNodes[1].nodeValue)
</script>
writes a after <br>

Disable radio button according to selected choice

I want to disable some radio button in a html form according to selected choices, if he select the first choice in the first radio button group the 2 choices in the second radio button group will be enabled, if not they will be disabled, here's my code:
<script language="javascript">
function RadioMeuble() {
if (document.f.radio1[0].checked) {
alert("Vous avez choisi la proposition " + document.f.radio1[0].value);
document.f.radio2[0].disabled = false;
document.f.radio2[1].disabled = false;
} else {
document.f.radio2[0].disabled = true;
document.f.radio2[1].disabled = true;
}
}
}
</script>
<input type="radio" name="radio1" value="L" id="radio1" onBlur="RadioMeuble()">á louer</label>
<br>
<label>
<input type="radio" name="radio1" value="V" id="radio1">á vendre</label>
</p>
<p>Superficie
<label for="textfield"></label>
<input type="text" name="superficie" id="Superficie">en Km ²</p>
<p>Prix
<label for="textfield2"></label>
<input type="text" name="prix" id="Prix">en DT</p>
<p>Meublé
<input type="radio" name="radio2" id="radio2" value="oui" disabled>Oui
<input type="radio" name="radio2" id="radio2" value="non" disabled>
<label for="radio2"></label>
<label for="radio"></label>Non</p>
It doesn't work. What's wrong with it?
There's a "}" too much in your code (last one).
Don't use the onblur EventHandler. You should use onchange or onclick instead.
<input type="radio" name="radio1" value="L" id="radio1" onchange="RadioMeuble()">
or
<input type="radio" name="radio1" value="L" id="radio1" onclick="RadioMeuble()">
HTH,
--hennson
Well, first of all, you have an extra "}" Second, you probably want the click event instead of the blur event. And you want it on both radio buttons. Next what is document.f? That's not a variable. Next, even if it were, I'm not aware of a browser that lets you use form elements like you are trying to. E.g., document.f.radio2[0].disabled. Also, your radio button should have unique ID names.
See: http://jsfiddle.net/vzYT3/1/ for something more sensible.
You could improve your coding a little, check this example:
<input type="radio" id="r1-1" name="r1" value="1">
<label for="r1-1">Option 1</label>
<input type="radio" id="r1-2" name="r1" value="2">
<label for="r1-2">Option 2</label>
<hr />
<input type="radio" id="r2-1" name="r2" value="a">
<label for="r2-1">Option A</label>
<input type="radio" id="r2-2" name="r2" value="b">
<label for="r2-2">Option B</label>
and
function byId(id) {
return document.getElementById(id);
}
window.onload = function() {
byId('r1-1').onchange = byId('r1-2').onchange = function() {
byId('r2-1').disabled = byId('r2-2').disabled = byId('r1-1').checked;
}
}
Running example at: http://jsfiddle.net/5Mp9m/
It wouldn't be a bad idea to use a javascript library like Jquery.

Categories