I am working on some code that takes the selected value of the radio button and passes it to the next group of radio buttons to be used as input. The code works well when passing the first time, but any subsequent time, instead of passing the value, it passes "on." I think it's just something silly, but I haven't been able to figure it out.
Link to JS Fiddle: https://jsfiddle.net/hc3bracf/6/
Here is the HTML and JS:
<div class="container">
<ul class="aaa">
<li>
<input type="radio" name="g1" id="i1" value="s#1" data-target="r65">
<label id="r1" for="i1">s#1</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" name="g1" id="i2" value="s#16" data-target="r65">
<label id="r2" for="i2">s#16</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<div class="container">
<ul class="aaa">
<li>
<input type="radio" name="g2" id="i3" value="s#8" data-target="r66">
<label id="r3" for="i3">s#8</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" name="g2" id="i4" value="s#9" data-target="r66">
<label id="r4" for="i4">s#9</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<div class="container">
<ul class="aaa">
<li>
<input type="radio" name="g33" id="i65" data-target="r97">
<label id="r65" for="i65"></label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" name="g33" id="i66" data-target="r97">
<label id="r66" for="i66"></label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<div class="container">
<ul class="aaa">
<li>
<input type="radio" name="g49" id="i97" data-target="r113">
<label id="r97"></label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" name="g49" id="i98" data-target="r113">
<label id="r98"></label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
JS
const inputs = document.querySelectorAll("input[type=radio]");
for (let inp of inputs) {
inp.addEventListener("change", function() {
let targetLabel = document.getElementById(inp.dataset.target);
let targetRadio = targetLabel.previousSibling;
targetLabel.innerHTML = inp.value;
targetRadio.value = inp.value;
targetRadio.checked = false;
//while there is a next target clear it
while (targetLabel.previousSibling.hasAttribute) {
targetLabel = document.getElementById(targetRadio.dataset.target);
targetRadio = targetLabel.previousSibling;
targetRadio.checked = false;
targetLabel.innerHTML = '';
}
});
}
The previousSibling property returns the previous node of the specified node, in the same tree level.
The returned node is returned as a Node object.
The difference between this property and previousElementSibling, is that previousSibling returns the previous sibling node as an element node, a text node or a comment node, while previousElementSibling returns the previous sibling node as an element node (ignores text and comment nodes).
const inputs = document.querySelectorAll("input[type=radio]");
for (let inp of inputs) {
inp.addEventListener("change", function() {
let targetLabel = document.getElementById(inp.dataset.target);
console.log(targetLabel);
let targetRadio = targetLabel.previousElementSibling;
targetRadio.value = inp.value;
targetLabel.innerHTML = inp.value;
targetRadio.checked = false;
//while there is a next target clear it
while (targetLabel.previousElementSibling.hasAttribute) {
targetLabel = document.getElementById(targetRadio.dataset.target);
targetRadio = targetLabel.previousSibling;
targetRadio.checked = false;
targetLabel.innerHTML = '';
}
});
}
Related
new to js and trying to get a total number of input tags in a div element then display the total.
Thanks for the help and sorry if this is a repeat question.
<div class="card-body">
<span>0</span> / <span id="total-inputs"></span>
<ul>
<li>
<input type="checkbox" id="input-1" class="sum" value="1" >
<label for="input-1">
Input 1
</label>
</li>
<li>
<input type="checkbox" id="input-2" class="sum" value="1" >
<label for="input-2">
Input 2
</label>
</li>
</ul>
</div>
const element = document.getElementsByClassName("card-body");
const nodes = element.getElementsByTagName("input");
document.getElementById("total-inputs").innerHTML = nodes.length;
Getting this error:
TypeError: element.getElementsByTagName is not a function
const element = document.getElementsByClassName("card-body") should be const element = document.getElementsByClassName("card-body")[0] since getElementsByClassName() returns an array:
const element = document.getElementsByClassName("card-body")[0];
const nodes = element.getElementsByTagName("input");
document.getElementById("total-inputs").innerHTML = nodes.length;
<div class="card-body">
<span>0</span> / <span id="total-inputs"></span>
<ul>
<li>
<input type="checkbox" id="input-1" class="sum" value="1" >
<label for="input-1">
Input 1
</label>
</li>
<li>
<input type="checkbox" id="input-2" class="sum" value="1" >
<label for="input-2">
Input 2
</label>
</li>
</ul>
</div>
You can use the new function querySelector and querySelectorAll.
Example:
var div = document.querySelector('div.card-body');
var inputs = div.querySelectorAll('input');
var inputLenth = inputs.length;
console.log(inputLenth);
Reference
Document.querySelector()
I am trying to get to <label> tag right under the <input> tag for later styling purposes. I tried with .firstElementChild, which gives me a null value. How can I get to label tag of clicked checkbox field? This is my code:
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
console.log(checkboxes[i]);
checkboxes[i].addEventListener('change', (e) => {
var targetCb = e.target;
console.log(targetCb.firstElementChild);
});
}
<ul>
<li class="title mb-3">STYLISTIC SET</li>
<li>
<input type="checkbox" id="sSet1" name="sSet1" value="sSet1" />
<label for="sSet1">Stylistic set 1</label>
</li>
<li>
<input type="checkbox" id="sSet2" name="sSet2" value="sSet2" />
<label for="sSet2">Stylistic set 2</label>
</li>
<li>
<input type="checkbox" id="sSet3" name="sSet3" value="sSet3" />
<label for="sSet3">Stylistic set 3</label>
</li>
<li>
<input type="checkbox" id="sSet4" name="sSet4" value="sSet4" />
<label for="sSet4">Stylistic set 4</label>
</li>
</ul>
It seems like you quite don't know what child elements and siblings are.
Consider the following for children:
<div id="parent">
<div id="child">I'm the child of my parent.</div>
</div>
And the following for siblings:
<div id="sibling1"></div>
<div id="sibling2">I'm the sibling of sibling1.</div>
In your code, those labels are siblings of your input elements.
So in your script, change console.log(targetCb.firstElementChild); to console.log(targetCb.nextElementSibling);
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkboxes.length; i++) {
console.log(checkboxes[i]);
checkboxes[i].addEventListener('change', (e) => {
var targetCb = e.target;
console.log(targetCb.nextElementSibling);
});
}
<ul>
<li class="title mb-3">STYLISTIC SET</li>
<li>
<input type="checkbox" id="sSet1" name="sSet1" value="sSet1" />
<label for="sSet1">Stylistic set 1</label>
</li>
<li>
<input type="checkbox" id="sSet2" name="sSet2" value="sSet2" />
<label for="sSet2">Stylistic set 2</label>
</li>
<li>
<input type="checkbox" id="sSet3" name="sSet3" value="sSet3" />
<label for="sSet3">Stylistic set 3</label>
</li>
<li>
<input type="checkbox" id="sSet4" name="sSet4" value="sSet4" />
<label for="sSet4">Stylistic set 4</label>
</li>
</ul>
Change
var targetCb = e.target;
to var targetCb = e.target.nextElementSibling;
My javascript code like this :
$(function(){
$('input[type="radio"]').click(function(){
var txt = $(this).parent().text();
var $radio = $(this);
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
$('#result-select').text('');
}
else{
$radio.data('waschecked', true);
$('#result-select').text(txt);
}
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
});
Demo and full code like this : https://jsfiddle.net/oscar11/m7by6zcw/21/
I want to :
If I select chelsea, madrid and juve the result like this :
Chelsea - Madrid - Juve
If I select chelsea and madrid the result like this :
Chelsea - Madrid
So if I check radio button, it display the text. If I uncheck radio button, it not display the text
How can I do it?
Update :
The radio button can be unchecked
For example :
If I select chelsea, madrid and juve the result like this :
Chelsea - Madrid - Juve
Then I uncheck madrid, the result like this :
Chelsea - Juve
Updated fiddle: https://jsfiddle.net/m7by6zcw/37/
Basically like Justinas's answer but with the checking/unchecking available.
The only part I really changed was how the text was being outputted, shown below:
let output = [];
$('input[type="radio"]:checked').each( function() {
var txt = $(this).parent().text();
output.push(txt);
});
$('#result-select').text(output.join(' - '));
You need to reset the data of everything else when something checks:
$(`input[name=${name}]:not(:checked)`).data('waschecked', false);
You have to gather all values from :checked radio buttons, later use .join to convert array to string and place to results field
$(function(){
$('input[type="radio"]').click(function(){
var result = $('#result-select');
var results = [];
$('input[type="radio"]:checked').each(function () {
results.push($(this).closest('label').text());
});
result.text(results.join(' - '));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<ul class="list-unstyled">
<li><strong>England</strong></li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="england" class="radio"> Chelsea
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="england" class="radio"> Mu
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="england" class="radio"> Arsenal
</label>
</div>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-unstyled">
<li><strong>Spain</strong></li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="spain" class="radio"> Madrid
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="spain" class="radio"> Barcelona
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="spain" class="radio"> Atletico
</label>
</div>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-unstyled">
<li><strong>Italy</strong></li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="italy" class="radio"> Juve
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="italy" class="radio"> Milan
</label>
</div>
</li>
<li>
<div class="checkbox">
<label>
<input type="radio" name="italy" class="radio"> Inter
</label>
</div>
</li>
</ul>
</div>
<span id="result-select">Result</span>
You need to first get the text value of the result : var str = $('#result-select').text();, then when you check a radio button, you just append the value to the result text str += txt; $('#result-select').text(str);.
And if you uncheck a radio button, you just replace it's value with an empty string str = str.replace(txt,'');.
$(function(){
$('input[type="radio"]').click(function(){
var txt = $(this).parent().text();
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
var str = $('#result-select').text();
str = str.replace(txt,'');
$('#result-select').text(str);
}
else{
$radio.data('waschecked', true);
var str = $('#result-select').text();
str += txt;
$('#result-select').text(str);
}
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
});
I want a variable (chanceoflive) to be stored with localStorage. Then, I have radio buttons. I want it so that depending on which radio button is selected, the variable chanceoflive will be changed. This is what I have:
var chanceoflive = 0;
var user;
function choose(choice){
user = choice;
}
function changechanceoflive(){
if (user == brick) {
chanceoflive += 1;
}
else if (user == wood) {
chanceoflive +=3
}
else if (user == stone) {
chanceoflive +=2
}
localStorage.setItem("chanceoflive", chanceoflive);
}
function test(click){
alert(chanceoflive);
}
<div id="radiobuttons" class="container" name="buttons" align=center>
<h2>I Want my Building to be Made of:</h2>
<ul>
<li>
<input type="radio" id="brick-option" name="material" value="1" onClick="choose('Bricks')">
<label for="brick-option">Bricks</label>
<div class="check"></div>
</li>
<li>
<input type="radio" id="wood-option" name="material" value="3" onClick="choose('Wood')">
<label for="wood-option">Wood</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" id="stone-option" name="material" value="2" onClick="choose('Stone')">
<label for="stone-option">Stone</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<form action="chooseheight.html">
<div class="wrapper">
<button class="button" onClick="test();changechanceoflive()" align=center>Submit</button>
</div>
</form>
Although, it always just alerts 0. Is it a problem with localStorage or something else?
I fixed your code:
<ul>
<li>
<input type="radio" id="brick-option" name="material" value="1" onClick="choose('bricks')">
<label for="brick-option">Bricks</label>
<div class="check"></div>
</li>
<li>
<input type="radio" id="wood-option" name="material" value="3" onClick="choose('wood')">
<label for="wood-option">Wood</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" id="stone-option" name="material" value="2" onClick="choose('stone')">
<label for="stone-option">Stone</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
JS
var chanceoflive = 0;
var user;
function choose(choice){
user = choice;
}
function changechanceoflive(){
if (user == 'bricks') {
chanceoflive += 1;
}
else if (user == 'wood') {
chanceoflive +=3
}
else if (user == 'stone') {
chanceoflive += 2
}
localStorage.setItem("chanceoflive", chanceoflive);
}
function test(click){
alert(chanceoflive);
alert(localStorage.chanceoflive);
}
But with your code, if the user reload the page and then didn't select any radio, the localStorage variable will be reset to 0 because your have
var chanceoflive = 0;
If you want to keep the last saved value, you must replace that line by:
var chanceoflive = localStorage.chanceoflive;
To answer your part about LocalStorage, just set/get your variables like a regular Javascript object. More info: mrkdown.io/t32iomd
I'm making an exercise where the user has to check correct answers from a list then press submit to see how well he/she did. However, my submit button does not seem to be working. Nothing happens when it is clicked. Here is the script:
<script>
//Returns how many correct answers were checked
$('#submitButton').click(function(){
var arrayScore = [];
var tempScore = 0;
$('.confirmContainer').remove();
$('.toggleConfirmList:checked').each(function(){
arrayScore.push($(this).val());
});
for(var i=0; i<arrayScore.length; i++)
{
tempScore = arrayScore[i] + tempScore;
}
$('feedback').show();
$("#scoreArea").val(tempScore);
});
</script>
Basically I want to disable the input container and then display the feedback after calculating the users score.
Here is the HTML code that the script uses:
<ol class="toggleConfirmList" start="1">
<!-- Start of toggleConfirm question -->
<li class="toggleConfirm">
<p class="question">What is your citizenship?
</p>
<div class="toggleInputContainer">
<input type="checkbox" value="1">
</div>
</li>
<li class="toggleConfirm">
<p class="question">What is the purpose of your trip</p>
<div class="toggleInputContainer">
<input type="checkbox" value="1">
</div>
</li>
<li class="toggleConfirm">
<p class="question">How long will you be staying in Canada?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">Where will you be staying?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">What is your occupation?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">Do you have any family in Canada?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="1">
</div>
</li>
<li class="toggleConfirm">
<p class="question">How will you support yourself in Canada?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">Do you intend to work or study while you are in Canada?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">Have you ever been convicted of a criminal offence?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">Do you suffer from any medical conditions?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">Have you ever been refused a visa to Canada?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="0">
</div>
</li>
<li class="toggleConfirm">
<p class="question">In which country do you reside permanently?</p>
<div class="toggleInputContainer">
<input type="checkbox" value="1">
</div>
</li>
</ol>
<div class="confirmContainer">
<input type="button" id="submitButton" value="Submit">
</div>
<div class="feedback">
<strong>Answer:</strong>In the exercise you checked <span id="scoreArea">0</span> correct questions
</div>
for setting value to a span element you should use text() method instead of val():
//Returns how many correct answers were checked
$('#submitButton').click(function(){
var arrayScore = [];
var tempScore = 0;
$('.confirmContainer').remove();
$(':checkbox:checked').each(function(){ // for selecting checkboxes you can use ":checkbox" selector
arrayScore.push(parseInt($(this).val())); // parseInt() the values
});
for(var i=0; i<arrayScore.length; i++)
{
tempScore = arrayScore[i] + tempScore;
}
$('.feedback').show(); // class selectors should have '.'
$("#scoreArea").text(tempScore); // use text() instead of val()
});
http://jsfiddle.net/EWgzq/2/
Try wrapping your code in $(document).ready(function(){...});. It may be that it is executing before the DOM is ready.
<script>
//Returns how many correct answers were checked
$(document).ready(function(){
$('#submitButton').click(function(){
var arrayScore = [];
var tempScore = 0;
$('.confirmContainer').remove();
$('.toggleConfirmList:checked').each(function(){
arrayScore.push($(this).val());
});
for(var i=0; i<arrayScore.length; i++){
tempScore = arrayScore[i] + tempScore;
}
$('feedback').show();
$("#scoreArea").val(tempScore);
});
});
</script>
<script>
//Returns how many correct answers were checked
$('#submitButton').click(function(){
var arrayScore = [];
var tempScore = 0;
$('.confirmContainer').remove();
$('.toggleInputContainer input[type="checkbox"]:checked').each(function(){
arrayScore.push($(this).val()*1); // See the *1
});
for(var i=0; i<arrayScore.length; i++)
{
tempScore = arrayScore[i] + tempScore;
}
$('div.feedback').show(); // added div. it was missing.
$("#scoreArea").html(tempScore); // it should be .html() or .text() not .val(). The .val() works only for form elements
});
</script>