HTML input checkbox always returns false - javascript

I know this has been already asked. I checked all the previous question about this topic but I can't find a solution.
This is the problem: I have two input, one is a checkbox and the other one is a radio with three possible choices. Inside a function I have to see firstly if the first checkbox is checked, if yes I will check some other things with an if else statement, otherwise the function will proceed. The radio input will appear later inside the same function. This one will check which of the three choices had been checked previously and will set a variable equal to the value of the checked one. To see if the checkbox is checked I use jQuery with .is(':checked'), but it every returns false, even if I checked them. Any idea?
Sorry if I haven't properly used Stack Overflow, but this is my first question.
This is the HTML, the input is #geoloc_waypoint_active and the radio is #locomotion_radio
<div id="create_route_modal_content" class="modal-body">
<div id="geo_switch">
<div id="geoSwitchDiv">
<label for="geoloc_waypoint_active">
Usa la tua posizione
</label>
<label class="switch">
<input id="geoloc_waypoint_active" class="form-check form-check-inline" type="checkbox">
<span class="slider round"></span>
</label>
</div>
<br>
<div id="locomotion_radio">
<label><input class="locomInput" type="radio" name="locomotion" value="walking" checked><img class='locomotionImg' src='immagini/walking.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="cycling"><img class='locomotionImg' src='immagini/cycling.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="driving"><img class='locomotionImg' src='immagini/driving.png'></label>
</div>
DrawOnMap() {
let formattedCoord = "";
let geoposition = $('#geoloc_waypoint_active').is(':checked');
console.log(geoposition)
if (geoposition) {
var geoL = $('#geo_Locator .mapboxgl-ctrl .mapboxgl-ctrl-icon');
if (!map.getLayer('points') && geoL.attr('aria-pressed') === 'false') {
alert("L'utente non ha una posizione attualmente attiva.");
return;
} else {
this.waypoints.unshift(window.userPosition);
}
}
if (this.waypoints.length < 2) {
alert("Devi inserire almeno due punti di interesse.");
return;
}
this.waypoints.forEach((waypoint, index, source) => {
formattedCoord += waypoint[0] + "," + waypoint[1];
if (index < source.length - 1) {
formattedCoord += ";";
}
});
let locomotion = $('input[name=locomotion]:checked').val();
let geoposition = $('#geoloc_waypoint_active').is(':checked'); is always false and so It never enter the if
Same thing with let locomotion = $('input[name=locomotion]:checked').val(); It can't find the checked one and set locomotion

have you tried this $("#geoloc_waypoint_active")[0].checked it will give you control right value.
$(document).ready(function(){
console.log($("#geoloc_waypoint_active")[0].checked)
$('#check').on('click',function(){
console.log($("#geoloc_waypoint_active")[0].checked)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value='checkVakue' type='button' id='check'/>
<div id="create_route_modal_content" class="modal-body">
<div id="geo_switch">
<div id="geoSwitchDiv">
<label for="geoloc_waypoint_active">
Usa la tua posizione
</label>
<label class="switch">
<input id="geoloc_waypoint_active" class="form-check form-check-inline" type="checkbox">
<span class="slider round"></span>
</label>
</div>
<br>
<div id="locomotion_radio">
<label><input class="locomInput" type="radio" name="locomotion" value="walking" checked><img class='locomotionImg' src='immagini/walking.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="cycling"><img class='locomotionImg' src='immagini/cycling.png'></label>
<label><input class="locomInput" type="radio" name="locomotion" value="driving"><img class='locomotionImg' src='immagini/driving.png'></label>
</div>

Related

How to get the checked radio button in JS?

I have seen that this works for most of users, but for some reason it doesn't for me. I use Google Chrome.
radioBut = document.querySelector(".rad-design")
getColor = function(){
for (i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i)
}
}
Html
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
</div>
</form>
The selector should be document.querySelectorAll to get inputs as array and you should target to .rad-input class which is the input and not .rad-design which is the label. Also you should use checked for the inputs to make the input checked, its not check. Also you cannot set checked to two inputs with same name. If thats done only the last input with that name will be checked.
Working Fiddle
const radioBut = document.querySelectorAll(".rad-input")
getColor = function () {
for (i = 0; i < radioBut.length; i++) {
if (radioBut[i].checked) {
console.log(radioBut[i])
}
}
}
<form id="rad">
<div class="radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" checked name="colList">
<div class="rad-design">One</div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design">Two</div>
</label>
</div>
<button type="button" onclick="getColor()">getColor</button>
</form>
document.querySelector returns just one element not an array/list, so in the for loop at i<radioBut.length radioBut.length is undefined, you need to use document.querySelectorAll() instead.
Also I noticed you have selected the div and not the input and you have a couple of syntax errors.
Maybe this can help you:
const radioBut = document.querySelectorAll(".rad-input")
const getColor = function(){
for (let i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i].value)
}
}
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>
Another options is to use the form element functionality
const form = document.getElementById('rad');
const getColor = function(){
return form.colList.value;
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>

Change src related to "Radio Button Checks"

In my project I want change src part (ar-button's src) related to my radio buttons check.
For ex: When you check "Option 1" I want to change src part on ar-button. Than when you check Option3x(with checked option1 and option1x) I want to change src again.
I mean for all 64 combination of checks I want to change src.
Any help or suggestion would be great!
Thanks..
<label>
<input type="radio" id="diffuse" name="kumas" value="textues/kumas/2/pgwfpjp_2K_Albedo.jpg"checked>
Option1
</label>
<label>
<input type="radio"id="adiffuse" name="kumas" value="textues/kumas/1/oi2veqp_2K_Albedo.jpg">
Option 2
</label>
<label>
<input type="radio" id="bdiffuse"name="kumas" value="textues/kumas/3/sjfvce3c_2K_Albedo.jpg">
Option 3
</label>
<label>
<input type="radio" id="cdiffuse"name="kumas" value="textues/kumas/4/sjfvcjzc_2K_Albedo.jpg">
Option 4
</label>
<br><br>
<label>
<input type="radio" id="diffuse1" name="kol" value="textues\kol\1\teqbcizc_2K_Albedo.jpg" checked>
Option 1x
</label>
<label>
<input type="radio" id="adiffuse1" name="kol" value="textues\kol\2\tfjbderc_2K_Albedo.jpg">
Option 2x
</label>
<label>
<input type="radio" id="bdiffuse1"name="kol" value="textues\kol\3\tcnodi3c_2K_Albedo.jpg">
Option 3x
</label>
<label>
<input type="radio" id="cdiffuse1"name="kol" value="textues\kol\4\tcicdebc_2K_Albedo.jpg">
Option 4x
</label>
</div>
</div>
</div>
<br><br>
<label>
<input type="radio" id="diffuse2" name="dugme" value="textues\metal\1\scksebop_2K_Albedo.jpg" checked>
Option 1z
</label>
<label>
<input type="radio" id="adiffuse2" name="dugme" value="textues\metal\2\se4objgc_2K_Albedo.jpg">
Option 2z
</label>
<label>
<input type="radio" id="bdiffuse2"name="dugme" value="textues\metal\3\se4pcbbc_2K_Albedo.jpg">
Option 3z
</label>
<label>
<input type="radio" id="cdiffuse2"name="dugme" value="textues\metal\4\shkxcgfc_2K_Albedo.jpg">
Option 4z
</label>
<br><br>
<ar-button
id="change" src="https://basebros.com/models/ar_base_tekli_koltuk_3d.glb"
id="change2 ios-src="https://basebros.com/models/ar_base_tekli_koltuk_3d.usdz"
title="3D-AR by BASE">
<img class="arbuttonicon" src="Assets/evindebutton.png" width="170px" alt="AR-icon">
</ar-button>
Try using this code:
const kumas = document.getElementsByName("kumas");
const kol = document.getElementsByName("kol");
const dugme = document.getElementsByName("dugme");
const arButton = document.querySelector("ar-button");
let sources = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]; /* Fill this with the sources. The first element is if the first option for kumas is selected, the second is for if the second option is selected, etc. The elements inside those elements are for each of the different options for kol, and the elements inside those elements are for each of the different options for dugme. */
function foo() {
let kumasSelected;
let kolSelected;
let dugmeSelected;
for(let i of kumas) {
if(i.checked) {
kumasSelected = kumas.indexOf(i);
}
}
for(let i of kol) {
if(i.checked) {
kolSelected = kol.indexOf(i);
}
}
for(let i of dugme) {
if(i.checked) {
dugmeSelected = dugme.indexOf(i);
}
}
arButton.src = sources[kumasSelected][kolSelected][dugmeSelected];
}
Run the function each time you want to update the source.
<label>
<input type="radio" id="diffuse" name="kumas" value="textues/kumas/2/pgwfpjp_2K_Albedo.jpg"checked>
Option1
</label>
<label>
<input type="radio"id="adiffuse" name="kumas" value="textues/kumas/1/oi2veqp_2K_Albedo.jpg">
Option 2
</label>
<label>
<input type="radio" id="bdiffuse"name="kumas" value="textues/kumas/3/sjfvce3c_2K_Albedo.jpg">
Option 3
</label>
<label>
<input type="radio" id="cdiffuse"name="kumas" value="textues/kumas/4/sjfvcjzc_2K_Albedo.jpg">
Option 4
</label>
<br><br>
<label>
<input type="radio" id="diffuse1" name="kol" value="textues\kol\1\teqbcizc_2K_Albedo.jpg" checked>
Option 1x
</label>
<label>
<input type="radio" id="adiffuse1" name="kol" value="textues\kol\2\tfjbderc_2K_Albedo.jpg">
Option 2x
</label>
<label>
<input type="radio" id="bdiffuse1"name="kol" value="textues\kol\3\tcnodi3c_2K_Albedo.jpg">
Option 3x
</label>
<label>
<input type="radio" id="cdiffuse1"name="kol" value="textues\kol\4\tcicdebc_2K_Albedo.jpg">
Option 4x
</label>
</div>
</div>
</div>
<br><br>
<label>
<input type="radio" id="diffuse2" name="dugme" value="textues\metal\1\scksebop_2K_Albedo.jpg" checked>
Option 1z
</label>
<label>
<input type="radio" id="adiffuse2" name="dugme" value="textues\metal\2\se4objgc_2K_Albedo.jpg">
Option 2z
</label>
<label>
<input type="radio" id="bdiffuse2"name="dugme" value="textues\metal\3\se4pcbbc_2K_Albedo.jpg">
Option 3z
</label>
<label>
<input type="radio" id="cdiffuse2"name="dugme" value="textues\metal\4\shkxcgfc_2K_Albedo.jpg">
Option 4z
</label>
<br><br>
<ar-button
src="https://basebros.com/models/ar_base_tekli_koltuk_3d.glb"
title="3D-AR by BASE">
<img class="arbuttonicon" src="Assets/evindebutton.png" width="170px" alt="AR-icon">
</ar-button>
<script>
const kumas = document.getElementsByName("kumas");
const kol = document.getElementsByName("kol");
const dugme = document.getElementsByName("dugme");
const arButton = document.querySelector("ar-button");
let sources = [[["https://basebros.com/models/ar_base_ayakkabi.glb"],["https://basebros.com/models/ar_base_camasir_makinesi_3d.glb"],["https://basebros.com/models/ar_base_kahve_makinesi_3d.glb"],["https://basebros.com/models/ar_base_nintendo.glb"]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]; /* Fill this with the sources. The first element is if the first option for kumas is selected, the second is for if the second option is selected, etc. The elements inside those elements are for each of the different options for kol, and the elements inside those elements are for each of the different options for dugme. */
function foo() {
let kumasSelected;
let kolSelected;
let dugmeSelected;
for(let i of kumas) {
if(i.checked) {
kumasSelected = kumas.indexOf(i);
}
}
for(let i of kol) {
if(i.checked) {
kolSelected = kol.indexOf(i);
}
}
for(let i of dugme) {
if(i.checked) {
dugmeSelected = dugme.indexOf(i);
}
}
arButton.src = sources[kumasSelected][kolSelected][dugmeSelected];
}
</script>

Creating a textarea when user clicks button

I was wondering what the best way to approach this next feature is.
Right now, when user selects "no" an alert appears. However, I would like for a text area box to appear, instead. Any help or leads on how to tackle this? My first thought is that my if statement will have to change, correct? Any leads are appreciated. I provided a snippet for you to view of what I have so far.
let button = document.querySelector("input.button");
button.addEventListener("click", question1);
function question1() {
var selection = document.querySelector("input[name='groupOfDefaultRadios']:checked");
if (selection.value == 'yes') {
alert("Thank you for your kindness");
} else {
alert("We are sorry! Please write to us telling us what was wrong");
}
}
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<input class="button" type="button" name="groupOfDefaultRadios" value="Submit">
</form>
</div>
Here are a few ways you can give a user something to enter text into and then handle it as you see fit.
The first way is to insert a textarea element and add a callback so that when the user selects OK, you can do what you want with the text.
The second way is to use prompt as called called out in other comments
function okButtonCallback(evt) {
const textArea = document.getElementById('textarea1');
alert(`Text Area Text: ${textArea.value}`);
}
const btnTextArea = document.getElementById('textarea');
const btnPrompt = document.getElementById('prompt');
// Use a Text Area to get text and
// add a callback to handle the text
// when the user selects ok
btnTextArea.addEventListener('click', e => {
const container = document.getElementById('myContainer');
const textArea = document.createElement('textarea');
textArea.id = 'textarea1';
const okButton = document.createElement('button');
okButton.innerText = 'OK';
okButton.onclick = okButtonCallback;
container.appendChild(textArea);
container.appendChild(okButton);
});
// Use a prompt to get the text
btnPrompt.addEventListener('click', e => {
const enteredText = prompt('Some sort of message');
alert(`Prompt Text: ${enteredText}`);
});
<button id="textarea">Show Text Area</button>
<button id="prompt">Show Prompt</button>
<div id="myContainer"></div>
The built in alert function cannot be used to get user input.
You can add a hidden div which replaces the alert and where you can also add HTML elements.
Please find slightly modified version of your code to get the idea below:
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<input class="button" type="button" name="groupOfDefaultRadios" value="Submit">
</form>
</div>
<div id="result" style="display:none"></div>
<script>
let button = document.querySelector("input.button");
button.addEventListener("click", question1);
function question1() {
var selection = document.querySelector("input[name='groupOfDefaultRadios']:checked");
var result = document.getElementById("result");
if (selection.value == 'yes') {
result.innerHTML = "Thank you for your kindness";
result.style.display = "block";
} else {
var output = "";
output += "We are sorry! Please write to us telling us what was wrong:<br />";
output += "<textarea style='width: 100px; height 100px;'></textarea><br />";
output += "<button>Submit</button>";
result.innerHTML = output;
result.style.display = "block";
}
}
</script>
I think you can create a <textarea id="whatever_you_want" hidden> and you add in the else document.getElementById("whatever_you_want").removeAttribute("hidden")
You can toggle a hidden text field, based on the selection of the radio button.
In the example below, a class is added to the text field to hide it. When the choice is changed to "yes", the class is added; if it is changed to "no", the class is added back.
let submitButton = document.querySelector('input.button');
let radioButtons = document.querySelectorAll('input[type="radio"]');
let hiddenTextArea = document.querySelector('.custom-textarea textarea');
// Add listeners
Array.from(radioButtons).forEach(radio => {
radio.addEventListener('change', (e) => {
let hiddenWrapper = hiddenTextArea.parentElement;
hiddenWrapper.classList.toggle('hidden-field', e.target.value !== 'no');
});
});
submitButton.addEventListener('click', question1);
function question1() {
var selection = document.querySelector("input[name='groupOfDefaultRadios']:checked");
if (selection.value == 'yes') {
alert("Thank you for your kindness");
} else {
alert("We are sorry! Please write to us telling us what was wrong");
}
}
.hidden-field {
display: none;
}
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<!-- Here -->
<div class="custom-control custom-textarea hidden-field">
<textarea name="feedback"></textarea>
</div>
<input class="button" type="button" name="groupOfDefaultRadios" value="Submit">
</form>
</div>
Another approach is to createElement when the user mark the "NO". I put notes inside this general demo:
let radioI = document.querySelectorAll("input[name='groupOfDefaultRadios']"); // get radio in order to attach eventListener:
radioI.forEach((item) => { item.addEventListener("change", question1)}); // add change event that will trigger this function:
function question1() {
var selection = document.querySelector('input[name="groupOfDefaultRadios"]:checked'); // this is your lines
if (selection.value == 'yes') {
alert('Thank you for your kindness');
// and/or submit the form progrematically using submit() etc... and/or redirect the user etc..
} else {
// create textarea element and display the submit button:
var textA = document.createElement('textarea');
textA.setAttribute('name', 'notHelpNote');
textA.setAttribute('required', 'true');
textA.placeholder = 'We are sorry! Please write to us telling us what was wrong';
document.querySelector('#myForm').appendChild(textA);
document.querySelector('#myForm input[type="submit"]').style.display = 'block';
}
}
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<input class="button" type="submit" name="groupOfDefaultRadios" value="Submit" style="display: none;">
</form>
</div>
I guess you can create a:
<input type="hidden" name="message" id="myAwesomeHiddenMessageField">
in your form and replacing your second alert by a prompt displaying the question like this :
let promptMessage = prompt("We are sorry! Please write to us telling us what was wrong");
And on submit or whatever :
document.querySelector('#myAwesomeHiddenMessageField').val(promptMessage);
Or you could use document.createElement to append a textearea to your form when "no" is selected. But I'm to lazy to help you more with this. And if you wan't to do this you gonna have to hide the generated textarea if the user choose "yes" in the end. Not sure if it's the best UX choose to make.
Cheers.

JQuery No radio button checked issue

I have a series of randomly generated textbox and radio-button inputs. It's kinda like a Quiz, so what I would like to do is collect all of the inputs and send them to the server so it can evaluate them.
Now, to make it easier, I put all of the radio-button inputs to the end.
I use the following code to collect the inputs of the textbox-types:
$('#button_submit').click(function() {
var answer_list = '';
$('input:text').each(function(index,data) {
answer_list = answer_list + '$' + $(data).val();
}
...
}
This works perfectly, but after this, I don't know what to do. I could loop through the input:radio:checked elements and add the value of those to my string, which would work perfectly, except if the user decides to submit their answers while leaving one of the radio-button inputs empty. In that case, nothing gets added to the string and the server will be missing the answer to that question and it messes everything up.
So I need to add something to my string when the code realizes that there is a radio-button question, but no answer was chosen, but I have no idea how to do it.
Edit:
HTML example:
<div class="form-group" id="form-group-34">
<label class="control-label " for="question">What is 92848 × 71549?</label>
<input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
<label class="control-label " for="question">Is 194 divisible by 3?</label>
<br><input id="14-answer-0" name="14-answer" type="radio" value="1">
<label for="14-answer-0">Yes</label>
<br><input id="14-answer-1" name="14-answer" type="radio" value="0">
<label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
<label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
<br><input id="35-answer-0" name="35-answer" type="radio" value="1">
<label for="35-answer-0">Monday</label>
<br><input id="35-answer-1" name="35-answer" type="radio" value="2">
<label for="35-answer-1">Tuesday</label>
<br><input id="35-answer-2" name="35-answer" type="radio" value="3">
<label for="35-answer-2">Wednesday</label>
<br><input id="35-answer-3" name="35-answer" type="radio" value="4">
<label for="35-answer-3">Thursday</label>
<br><input id="35-answer-4" name="35-answer" type="radio" value="5">
<label for="35-answer-4">Friday</label>
<br><input id="35-answer-5" name="35-answer" type="radio" value="6">
<label for="35-answer-5">Saturday</label>
<br><input id="35-answer-6" name="35-answer" type="radio" value="0">
<label for="35-answer-6">Sunday</label>
</div>
But the problem is, that these questions are randomly generated. So there can be 5 simple textbox-type inputs, then 5 radio-button type ones, or there might be only 1 radio-button type question, and all of their attributes are generated dynamically, so I can't really put the radio-button group's name in the code, because I don't know it.
You could use this to see if they are all checked:
var allRadios = $('input[name="namevalue"][type=radio]').length;
var allCheckedRadios $('input[name="namevalue"][type=radio]').filter(function() {
return this.checked;
}).length;
if( allRadios == allCheckedRadios){
// do what you need
}
whatever your name is change "namevalue" to that. The same basic logic to get the values can be applied.
Note: performance gain for modern browsers on these selector forms above over $('input:radio') can be had.
EDIT From updated question:
Here I applied the techniques above to walk through each of the form groups looking for radio buttons, and if they exist throw an alert if none are checked within that group. You could also create and return a Boolean value if ANY of the groups have radio selections with none selected. "hasUncheckedRadios" will be either 0 if none are checked or 1 if one is checked - since radio buttons within a group only select one. You could use this logic in your validation to ensure that all of the groups have a valid checked radio button (IF they contain a radio that is);
function checkRadios() {
var allGroups = $('.form-group');
allGroups.each(function() {
var allRadios = $(this).find('input[type=radio]').length;
var hasUncheckedRadios = $(this).find('input[type=radio]').filter(function() {
return this.checked;
}).length;
console.log('total:' + allRadios + ' checked:' + hasUncheckedRadios);
// if allRadios is > 0 then radios exist and hasUncheckedRadios == 0 none are checked
if (allRadios && !hasUncheckedRadios) {
alert("Form Group" + $(this).attr('id') + " has radio buttons unaswered");
}
});
}
$('#checkem').on('click', function() {
console.log('checking...');
checkRadios();
});
fiddle with it here: https://jsfiddle.net/MarkSchultheiss/nv7cjpr2/
I would iterate a bit more: https://jsfiddle.net/Twisty/ghc7u2ab/
HTML
<div class="form-group" id="form-group-34">
<label class="control-label " for="question">What is 92848 × 71549?</label>
<input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
<label class="control-label " for="question">Is 194 divisible by 3?</label>
<br>
<input id="14-answer-0" name="14-answer" type="radio" value="1">
<label for="14-answer-0">Yes</label>
<br>
<input id="14-answer-1" name="14-answer" type="radio" value="0">
<label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
<label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
<br>
<input id="35-answer-0" name="35-answer" type="radio" value="1">
<label for="35-answer-0">Monday</label>
<br>
<input id="35-answer-1" name="35-answer" type="radio" value="2">
<label for="35-answer-1">Tuesday</label>
<br>
<input id="35-answer-2" name="35-answer" type="radio" value="3">
<label for="35-answer-2">Wednesday</label>
<br>
<input id="35-answer-3" name="35-answer" type="radio" value="4">
<label for="35-answer-3">Thursday</label>
<br>
<input id="35-answer-4" name="35-answer" type="radio" value="5">
<label for="35-answer-4">Friday</label>
<br>
<input id="35-answer-5" name="35-answer" type="radio" value="6">
<label for="35-answer-5">Saturday</label>
<br>
<input id="35-answer-6" name="35-answer" type="radio" value="0">
<label for="35-answer-6">Sunday</label>
</div>
<button id="button_submit">Submit</button>
JQuery
$("#button_submit").click(function() {
var answer_list = {};
$(".form-group").each(function(i, v) {
console.log("Index:", i, "ID: [", $(v).attr("id"), "]");
answer_list[$(v).attr("id")] = {};
var ind = $(v).find("input");
$.each(ind, function(i2, el) {
console.log("Type of Element:", $(el).attr("type"));
switch ($(el).attr("type")) {
case "text":
answer_list[$(v).attr("id")][$(el).attr("id")] = ($(el).val() != "") ? $(el).val() : null;
break;
case "radio":
var isAnswered = false;
$(el).each(function(i3, rad) {
if ($(rad).is(":checked")) {
answer_list[$(v).attr("id")][$(rad).attr("name")] = $(rad).val();
isAnswered = true;
}
if (!isAnswered) {
answer_list[$(v).attr("id")][$(el).eq(0).attr("name")] = null;
}
});
break;
}
});
});
console.log(answer_list);
return false;
});
Possible Result
answer_list: {
form-group-34: {
input34: null
},
form-group-35: {
14-answer: 0
},
form-group-36: {
35-answer: null
}
}
This will iterate each group and look for an answer. If one is found, the value is added. If not, null is added as the result.
loop class group that has radio then use .prop("checked")
var frmGroup= 0, checked= 0;
$('.form-group').each(function(index) {
if ($(this).children('input:radio').length > 0) {
frmGroup++;
$(this).children('input:radio').each(function(index) {
if ($(this).prop("checked") == true) {
checked++;
}
});
}
});
if(frmGroup != checked)...
working example: https://jsfiddle.net/nsL3drz5/

Not able to hide, show button based on radio button select using JQuery

I have 6 groups of radio buttons with three choices each and a button to the next step. I want that a radio button in each group must be selected before the button to the next step is displayed. The button to the next step is hidden by default. It concerns a wordpress site and the code is provided by a plugin named: quform
The html code (1 group):
<div class="iphorm-group-row iphorm-clearfix iphorm-group-row-1cols"><div class="iphorm-element-wrap iphorm-element-wrap-radio iphorm_14_12-element-wrap iphorm-clearfix iphorm-labels-above iphorm-element-optional" style="display: block;">
<div class="iphorm-element-spacer iphorm-element-spacer-radio iphorm_14_12-element-spacer">
<label class="iphorm_14_12-outer-label">Group1</label>
<div class="iphorm-input-wrap iphorm-input-wrap-radio iphorm_14_12-input-wrap">
<div class="iphorm-input-ul iphorm-input-radio-ul iphorm_14_12-input-radio-ul iphorm-options-block iphorm-clearfix">
<div class="iphorm-input-li iphorm-input-radio-li iphorm_14_12-input-li">
<label class="iphorm_14_12_1_label">
<div class="radio" id="uniform-iphorm_14_12_523933240794b_1"><span><input type="radio" value="Level-1" id="iphorm_14_12_523933240794b_1" name="iphorm_14_12" class="iphorm-element-radio iphorm_14_12 iphorm_14_12_1"></span></div>
Level-1</label>
</div>
<div class="iphorm-input-li iphorm-input-radio-li iphorm_14_12-input-li">
<label class="iphorm_14_12_2_label">
<div class="radio" id="uniform-iphorm_14_12_523933240794b_2"><span><input type="radio" value="Level-2" id="iphorm_14_12_523933240794b_2" name="iphorm_14_12" class="iphorm-element-radio iphorm_14_12 iphorm_14_12_2"></span></div>
Level-2</label>
</div>
<div class="iphorm-input-li iphorm-input-radio-li iphorm_14_12-input-li">
<label class="iphorm_14_12_3_label">
<div class="radio" id="uniform-iphorm_14_12_523933240794b_3"><span><input type="radio" value="Level-3" id="iphorm_14_12_523933240794b_3" name="iphorm_14_12" class="iphorm-element-radio iphorm_14_12 iphorm_14_12_3"></span></div>
Level-3</label>
</div>
</div>
</div>
<div class="iphorm-errors-wrap iphorm-hidden">
</div> </div>
The Javascript code (6 groups):
$(".iphorm_14_12, .iphorm_14_13, .iphorm_14_14, .iphorm_14_15, .iphorm_14_16, .iphorm_14_17").click(function(){
var show = true;
$(".iphorm_14_12, .iphorm_14_13, .iphorm_14_14, .iphorm_14_15, .iphorm_14_16, .iphorm_14_17").each(function () {
if (!$(this).is(':checked')){
show = false;
}
$(".iphorm_14_12_1, .iphorm_14_12_2, .iphorm_14_12_3, .iphorm_14_13_1, .iphorm_14_13_2, .iphorm_14_13_3, .iphorm_14_14_1, .iphorm_14_14_2, .iphorm_14_14_3, .iphorm_14_15_1, .iphorm_14_15_2, .iphorm_14_15_3, .iphorm_14_16_1, .iphorm_14_16_2, .iphorm_14_16_3, .iphorm_14_17_1, .iphorm_14_17_2, .iphorm_14_17_3").each(function () {
if (!$(this).is(':checked')) {
show = false;
}
if (show) {
$('#btn-step-6').show();
} else {
$('#btn-step-6').hide();
}
});
});
});
Wrap each radio groups with a form or a div :
<div id="food">
<input type="radio" name="group1" value="Milk"> Milk
<input type="radio" name="group1" value="Butter"> Butter
<input type="radio" name="group1" value="Cheese"> Cheese
</div>
<div id="pets">
<input type="radio" name="group2" value="Dog"> Dog
<input type="radio" name="group2" value="Cat"> Cat
<input type="radio" name="group2" value="Dolphin"> Dolphin
</div>
Then in jQuery :
if ($('#food input[type=radio]:checked')[0] != undefined && $('#pets input[type=radio]:checked')[0] != undefined) {
$('#btn-step-6').show();
}
Try this:
<select name="top5" size="3">
<option onclick="showNextStep(this)">Checkbox</option>
</select>
in showNextStep(obj):
// The id of the hidden element -> displaly: none
if ($(obj).prop('checked')) {
$("#nextstep").css('display', "block");
} else {
// To hide if unselect
$("#nextstep").css('display', "none");
}
You can try jsfiddle example (http://jsfiddle.net/Lt92r/), I hope this will help.
$(".test input[type=radio]").click(function(){
$(this).parent("div").find(".btn").css("display","block");
});

Categories