How to check if radiobutton is selected (javascript, html) - javascript

I am trying to check if a radio button is selected or not. If the "morn_before" radiobutton is selected, the data will be stored as "2", but if the "morn_after" radiobutton is selected instead, the data will be stored as "1".
Currently my code show below is not working. For example when i select the "morn_before" radiobutton, it doesnt print "morn_before checked true" in the console, despite me putting console.log("morn_before checked true") in that if statement.
HTML:
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="morn_before">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="morn_after">
<label for="morn_after">After Food</label><br><br>
</div>
Javascript:
function check() {
let user=firebase.
auth().currentUser;
let uid;
if(user!=null){
uid=user.uid;
}
var firebaseRef = firebase.database().ref();
if(document.getElementById("morn_before").checked){
console.log("morn_before checked true");
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("2");
}
else if(document.getElementById("morn_after").checked){
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("1");
}
}
check();

You don't need any JavaScript for this. You can have a completely different display than the stored value.
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="2">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="1">
<label for="morn_after">After Food</label><br><br>
</div>
Should produce the same result. The only improvement would be to set one of these to default true, in case the user chose neither. But that'd be up to you.
ADDITIONAL INFO: You are not supposed to read a radio button group that way.
You should go over some basics of HTML INPUT tag such as
https://www.geeksforgeeks.org/how-to-get-value-of-selected-radio-button-using-javascript/

Related

Checkbox Functionality with Two Series of Checkboxes

I'm currently developing a form that has two containers with checkboxes. There first is the master and then there's the secondary which corresponds to the master.
The first container's checkboxes contain a data attribute value such as: "One", "Two", "Three", etc.
Upon clicking one of the master checkboxes (the onCheck function) it checks all the input data attribute values that have an input of "checked", and then proceeds to check every checkbox in the secondary container (which has an array of information in its data attribute) and if there's a match between any of the information, they get checked.
What I'm trying to figure out is the uncheck functionality (the offCheck function). When the user unchecks a master checkbox, it should look through each master input checkbox and if there's one that's checked and it corresponds to the data information in one of the secondary checkboxes, it shouldn't be unchecked. If there's no corresponding information, it gets unchecked.
Please let me know if you need clarification as this can be a bit confusing.
HTML:
<div class="master">
<input type="checkbox"
data-information="One"
/> Primary Checkbox One
<input type="checkbox"
data-information="Two"
/> Primary Checkbox Two
<input type="checkbox"
data-information="Three"
/> Primary Checkbox Three
</div>
<div class="secondary">
<input type="checkbox"
data-information='["One", "Seven", "Ten"]'
/> Secondary Checkbox One
<input type="checkbox"
data-information='["Two", "Three", "Ten"]'
/> Secondary Checkbox One
</div>
jQuery / JavaScript:
function onCheck(){
// Gather all information from checkboxes that are checked
var informationOne = [];
$(".master input:checkbox").each(function(){
if($(this).is(":checked")){
informationOne.push($(this).data("information"));
}
});
$('.secondary input:checkbox').each(function(){
var informationTwo = [];
informationTwo = $(this).data("information");
for(var i=0; i<informationTwo.length; i++){
if($.inArray(informationTwo[i], informationOne) != -1){
$(this).prop("checked", true);
}
}
});
}
function offCheck(){
}
$(".master input:checkbox").change("checked", function(){
if($(this).is(":checked")){
onCheck();
} else {
offCheck();
}
});
Welcome to StackOverflow, Nate!
I took a slightly different approach. Instead of asking, "what changed, and how does it affect the checkboxes?" this code says "something changed, set all the checkboxes according to the current state."
function setCheckboxes(){
[...document.querySelectorAll('.secondary input[type=checkbox]')].forEach((i) => {
i.checked = shouldBeChecked(i);
});
}
function shouldBeChecked(el) {
const matchingNumbers = JSON.parse(el.dataset.information);
return [...document.querySelectorAll('.master input[type=checkbox]:checked')].some((i) =>
matchingNumbers.includes($(i).data('information'))
);
}
$(".master input:checkbox").change("checked", function(){
setCheckboxes();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="master">
<input type="checkbox"
data-information="One"
/> Primary Checkbox One
<input type="checkbox"
data-information="Two"
/> Primary Checkbox Two
<input type="checkbox"
data-information="Three"
/> Primary Checkbox Three
</div>
<div class="secondary">
<input type="checkbox"
data-information='["One", "Seven", "Ten"]'
/> Secondary Checkbox One
<input type="checkbox"
data-information='["Two", "Three", "Ten"]'
/> Secondary Checkbox One
</div>

Requiring radio button selection in Javascript

I'm a total beginner to JS, trying to create a radio button with two options (left/right), in which one of the two options needs to be selected for the program to continue, or else it will display an error screen.
I've got code that will either prevent the participant from continuing no matter what they press (i.e. the error pops up regardless), or code that will allow the participant to continue no matter what (i.e. the program continues even if they don't select one of the options.) I feel like this could be something with my logical operators, but I'm really not sure. I've tried using a manual XOR and that doesn't seem to be the problem.
I'm using adapted code, so please let me know if there's anything else I can/should include!
<div class="radio"><label><input id="option1" name="option1" type="radio" value="Right" />Right</label></div>
<div class="radio"><label><input id="option1" name="option1" type="radio" value = "Left" />Left</label></div>
Code that causes the error no matter what:
<input onclick="function filledOut(id) { return (document.getElementById(id).value == 'Left')} if(filledOut('option1') ) { next(); }else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
Code that causes the program to continue:
<input onclick="function filledOut(id) { return ((document.getElementById(id).value == 'Left')|| (document.getElementById(id).value == 'Right'))} if(filledOut('option1') ) { next(); } else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
<form name="formName">
<input type="radio" name="option1" id="option1" value="Right"/>Right
<input type="radio" name="option2" id="option2" value="Left"/>Left
</form>
<input onclick="checkResponse()" type="button" value="Continue" />
checkResponse function will check if any options are selcted when user clicks on the continue button.
<script type="text/javascript">
function checkResponse(){
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
}
function isChecked(id){
return document.getElementById(id).checked; //returns true if any options are selected
}
</script>
You need to change the ID's to something different. In the case of radio buttons, the "name" is the radio button group. You don't need the ID's unless you are going individually look at each item, and if you give them ID's, they need to be distinct from every other ID, as well as the "name" attributes.
https://www.w3schools.com/tags/att_input_type_radio.asp
<input id="optionRight" name="groupName" type="radio" value="Right" />
<input id="optionLeft" name="groupName" type="radio" value="Left" />
Also, you can make one of the radio buttons as selected by default.
How to select a radio button by default?
<input id="option1" name="groupName" type="radio" value="Right" checked="checked" />
What I've understood is that you need to show an error if nothing is checked and continue if one of them is checked.
To do that, you will need to check if either of them is checked not checking it's value & give each radio button a unique id.
You can do something similar to this
function isChecked(id){//Instead of filledOut
return document.getElementById(id).checked;
//.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
Another function to get the value if you need it:
function getCheckedBtnValue(){
if(isChecked('option1')) return document.getElementById('option1').value
if(isChecked('option2')) return document.getElementById('option2').value
return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
next();
}else{
alert("Your error message");
}
Also, try not to write JavaScript inside of HTML elements it can be hard to read often.
Keep JavaScripting.

Selected value of Radio Button doesn't change

In the view, I have these two radio buttons:
#Html.RadioButtonFor(c => c.CampaignType, "Exclusive")<label>Exclusive</label>
#Html.RadioButtonFor(c => c.CampaignType, "Shared")<label>Shared</label>
The value for Model.CampaignType is set in the controller before the page loads. All of this works fine. If Exclusive is what's saved in the DB, then we get this rendered in the HTML:
<input checked="checked" id="CampaignType" name="CampaignType" type="radio" value="Exclusive"><label>Exclusive</label>
<input id="CampaignType" name="CampaignType" type="radio" value="Shared"><label>Shared</label>
So far, all's well.
But, inside an onclick() event for a button, if I do this:
var values =
{
"CampaignType": $('#CampaignType').val()
}
alert(values.CampaignType);
The alert always comes up as `Exclusive', even if I have changed the selection to 'Shared'.
What do I need to do so that values.CampaignType reflects the what is selected on the page, and not what was set when the page was loaded?
So you can do start with these:
Remove the invalid ids - multiple ids are invalid in CSS. For getting the value of the checked radio button you can use:
$('input[name=CampaignType]:checked').val()
or
$('input[type=radio]:checked').val()
For the label to work you have to link it with the corresponding radio button using the for attribute.
See demo below:
function submit() {
var values = {
"CampaignType": $('input[name=CampaignType]:checked').val()
}
console.log(values.CampaignType);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input checked="checked" id="CampaignType1" name="CampaignType" type="radio" value="Exclusive">
<label for="CampaignType1">Exclusive</label>
<input id="CampaignType2" name="CampaignType" type="radio" value="Shared">
<label for="CampaignType2">Shared</label>
<br/>
<button onclick="submit()">click here</button>
All the best!

How to identify whether or not a radio has been checked programmatically?

I have a form page in which the user can enter an ID, and the corresponding profile data is pulled from mysql and displayed in the form so that the user may edit it.
One element is a group of radios, so you may select a year level (ie "1", "2", "3", etc).
When a user provides an ID, an AJAX call is made to pre-populate the form with data, including selecting the appropriate radio.
problem:
The user must select a year level to submit the form. I check this with a verifyForm() method:
function verifyForm() {
if( !document.addStudentForm.elements["yearLevel"].checked ) {
alert( "You must select a year level before submitting." );
return false;
}
};
I expect this to check yearLevel and, if an option isn't selected, alert/return false.
However, when the yearLevel radio is pre-selected by the AJAX data, this is still behaving as if the user did not select a radio.
The radio is populated by js via the following code:
document.getElementById( "yearLevel_<?=$student['student']->get('yearLevel')?>" ).checked = true;
edit: Here is the relevant HTML.
<form name="addStudentForm" action="validation/updateStudentValidate.php" method="POST" onSubmit="return verifyForm()">
<input type="radio" value="1" name="yearLevel" disabled id="yearLevel_1" /> 1
<input type="radio" value="2" name="yearLevel" disabled id="yearLevel_2" /> 2
<input type="radio" value="3" name="yearLevel" disabled id="yearLevel_3" /> 3
<input type="radio" value="4" name="yearLevel" disabled id="yearLevel_4" /> 4
<input type="radio" value="5" name="yearLevel" disabled id="yearLevel_5" /> 5
<input type="radio" value="6" name="yearLevel" disabled id="yearLevel_6" /> 6
</form>
Question:
How can I have my javascript properly identify whether or not the radio has been checked, regardless of if it was selected by hand or programmatically?
Taken from this StackOverflow post and adapted for this example and for speed, you can have this in your AJAX success return:
var radios = document.getElementsByName('yearLevel'),
i = radios.length,
isChecked = false;
while(i--){
if (radios[i].checked) {
isChecked = true;
break;
}
}
Then when the function is called:
function verifyForm(){
if(!isChecked){
alert( "You must select a year level before submitting." );
return false;
}
};
This is assuming that you don't have any other items with the name yearLevel in your HTML.
This will actually return the value, I guess I'm unsure if you are wanting to see a specific item checked, or just that they have been checked at all. This function will do both.

If radio button checked add new form element using dom?

How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?
//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">
//Add new form elements
<span id="datesettings"></span>
Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.
Check out this page:
It explains the process so you understand why you're doing it a certain way, AND it gives good example code.
http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3
You would write a function to do the check, like this:
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.appendChild(...);
}
else if(o2.checked) {
eSettings.appendChild(...);
}
}
But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.
<form id="TestForm">
<!-- //Radio buttons -->
<input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
<input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
<!-- //Add new form elements -->
<span id="datesettings"></span>
</form>

Categories

Resources