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);
});
});
Related
I am currently working on a filter that displays products categories through Radio Button selection:
<div class="round" id="r-group">x
<label for="r2" class="label-filter">
<input type="radio" id="r1" name="club-selection" value="club-selection">
<span class="label-text">The Club Selection</span>
</label>
<label for="r2" class="label-filter">
<input type="radio" id="r2" name="upholstery" value="upholstery">
<span class="label-text">All Upholstery</span>
</label>
<label for="r3" class="label-filter">
<input type="radio" id="r3" name="casegoods" value="casegoods">
<span class="label-text">All Casegoods</span>
</label>
<label for="r3" class="label-filter">
<input type="radio" id="r4" name="tables" value="tables">
<span class="label-text">All Tables</span>
</label>
<label for="r3" class="label-filter">
<input type="radio" id="r5" name="lighting" value="lighting">
<span class="label-text">All Lighting</span>
</label>
</div>
I want to be able show each category as I select the radio buttons. For example: If I select All Casegoods, I want to only show the div with data-category="casegoods". If I select Tables and Lighting I want to show the div with data-category="tables" and data-category="lighting". These are the basic structure of the divs per category:
<div class="product" data-category="club-selection">
<h4>The Club Selection</h4>
</div>
<div class="product" data-category="upholstery">
<h4>Upholstery</h4>
</div>
<div class="product" data-category="casegoods">
<h4>Casegoods</h4>
</div>
<div class="product" data-category="tables">
<h4>All Tables</h4>
</div>
<div class="product" data-category="lighting">
<h4>Lighting</h4>
</div>
So far, I am able to store the value of the selected radio buttons into an array (selectedValues), but I am not sure what to do next to be able to display only the divs of the categories selected.This is the code that store the values:
$(function(){
var items = $("[data-category]");//get all the elements that has data-categories attribute
items.show(); //show all of the elements we found above
$("input[type=radio]").on("change",function(ev){ //bind onchange event
var selectedValues = []; //this array will hold all of the current categories
$("input:checked").each(function(idx, checkedRadio){//get all of the input radio buttons that are checked and add the value of each of them to the selectedValues array we created above
selectedValues.push($(checkedRadio).val().toLowerCase());
//THIS IS WHERE I´M STUCK. What do I do with the values stored in the array?
});
});
});
EDIT:fixed the ids on the inputs.
You can do something like this:
var elems = $("[data-category]").filter(function() {
return selectedValues.indexOf($(this).data("category")) > -1;
});
elems.show();
I believe you want to use checkbox and not radio, since you cant deselect them again. Else you have to use the same name so you cant select more than one.
Also please note that many of your inputs have the same id, ID should always be unique.
Demo
$(function() {
var items = $("[data-category]"); //get all the elements that has data-categories attribute
items.show(); //show all of the elements we found above
$("input[type=checkbox]").on("change", function(ev) { //bind onchange event
$("[data-category]").hide()
var selectedValues = []; //this array will hold all of the current categories
$("input:checked").each(function(idx, checkedRadio) { //get all of the input radio buttons that are checked and add the value of each of them to the selectedValues array we created above
selectedValues.push($(checkedRadio).val().toLowerCase());
});
var elems = $("[data-category]").filter(function() {
return selectedValues.indexOf($(this).data("category")) > -1;
});
elems.show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="round" id="r-group">
<label for="r2" class="label-filter">
<input type="checkbox" id="r2" name="club-selection" value="club-selection">
<span class="label-text">The Club Selection</span>
</label>
<label for="r2" class="label-filter">
<input type="checkbox" id="r2" name="upholstery" value="upholstery">
<span class="label-text">All Upholstery</span>
</label>
<label for="r3" class="label-filter">
<input type="checkbox" id="r3" name="casegoods" value="casegoods">
<span class="label-text">All Casegoods</span>
</label>
<label for="r3" class="label-filter">
<input type="checkbox" id="r3" name="tables" value="tables">
<span class="label-text">All Tables</span>
</label>
<label for="r3" class="label-filter">
<input type="checkbox" id="r3" name="lighting" value="lighting">
<span class="label-text">All Lighting</span>
</label>
</div>
<div class="product" data-category="club-selection">
<h4>The Club Selection</h4>
</div>
<div class="product" data-category="upholstery">
<h4>Upholstery</h4>
</div>
<div class="product" data-category="casegoods">
<h4>Casegoods</h4>
</div>
<div class="product" data-category="tables">
<h4>All Tables</h4>
</div>
<div class="product" data-category="lighting">
<h4>Lighting</h4>
</div>
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 = '';
}
});
}
I want to have one checkbox that will check all others and I'm stuck. I'm trying to do that with a loop but that returns nothing.
It's an exercise so I cant change the html ids.
HTML:
<p>
Price for adds: <span id="price">0 usd</span>
</p>
</div>
<div class='panel'>
<div class='panel-body'>
<form>
<div class="checkbox">
<label><input type="checkbox">All adds</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="3.50">Additional cheese, 3,50 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="2.20">Salami, 2,20 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="5.00">Additional Ham, 5 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="4.10">pepper, 4,10 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="3.50">Mushroms, 3,50 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox">Clear all</label>
</div>
<br>
<p>
<button class='btn btn-primary'>Submit</button>
</p>
</form>
</div>
</div>
JS:
$(function(){
$('.panel-body').on('change','input',function(e){
if($(this).parent().text()=='All adds'){
var inps = $('.checkbox input');
$(inps).each(function{
$(this).prop('checked', true)
})
var price = $('#price').html()
price = price.replace("USD", "");
price = parseFloat(price)
var add = $(this).attr('data-price')
if ($(this).prop('checked')) {
console.log($(this).text())
var totalPrice = parseFloat(add) + parseFloat(price)
$('#price').html(totalPrice.toFixed(2))
}
else {
var totalPrice = parseFloat(price) - parseFloat(add)
$('#price').html(totalPrice.toFixed(2))
}
})
})
1st you are missing () after function:
$(inps).each(function() {
$(this).prop('checked', true)
})
2nd use trim() to remove whitespace from both sides$(this).parent().text().trim()
3rd the if you have is closed with )} which is wrong, just use )
4th Instead of using each you can just do $('.checkbox input').prop('checked', true):
if ($(this).prop('checked')) {
$('.checkbox input').prop('checked', true)
} else {
$('.checkbox input').prop('checked', false)
}
This allowed you to uncheck all as well.
$(function() {
$('.panel-body').on('change', 'input', function(e) {
if ($(this).parent().text().trim() == 'All adds') {
if ($(this).prop('checked')) {
$('.checkbox input').prop('checked', true)
} else {
$('.checkbox input').prop('checked', false)
}
var price = $('#price').html()
price = price.replace("USD", "");
price = parseFloat(price)
var add = $(this).attr('data-price')
if ($(this).prop('checked')) {
console.log($(this).text())
var totalPrice = parseFloat(add) + parseFloat(price)
$('#price').html(totalPrice.toFixed(2))
} else {
var totalPrice = parseFloat(price) - parseFloat(add)
$('#price').html(totalPrice.toFixed(2))
}
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
Price for adds: <span id="price">0 usd</span>
</p>
</div>
<div class='panel'>
<div class='panel-body'>
<form>
<div class="checkbox">
<label>
<input type="checkbox">All adds</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="3.50">Additional cheese, 3,50 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="2.20">Salami, 2,20 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="5.00">Additional Ham, 5 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="4.10">pepper, 4,10 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="3.50">Mushroms, 3,50 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox">Clear all</label>
</div>
<br>
<p>
<button class='btn btn-primary'>Submit</button>
</p>
</form>
</div>
</div>
You have a typo:
$(inps).each(function{
$(this).prop('checked', true)
})
You should change this:
$(inps).each(function{
To this:
$(inps).each(function(){
Give your main checkbox an id "cAll". and use jQuery:
$("#cAll").click(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
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 have inputs nested inside of anchors nested inside of list items. I'd like to use jquery to iterate through the list items, and if an item was selected display the values in a text field. I'm close, I'm down to the input control, but the "if (checked)" statement is not working.
Can somebody please tell me what I'm doing wrong? :(
function ddDistrictChanged() {
var txt = "nothing selected";
var $inp = $('#ddDistrict').find('input');
$inp.each(function (index) {
$('#txtHere').text($(this).children('li'));
if ($(this).checked) {
txt = txt + ', ' + $(this).text();
}
$('#txtHere2').text(txt);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ddDistrict" class="dropdown-menu">
<li><input name="selCol" type="checkbox" value="1"> District 1 (Porter)</li>
<li><input name="selCol" type="checkbox" value="2"> District 2 (Jones Jr.)</li>
<li><input name="selCol" type="checkbox" value="3"> District 3 (Horne)</li>
<li><input name="selCol" type="checkbox" value="4"> District 4 (Haddaway)</li>
<li><input name="selCol" type="checkbox" value="5"> District 5 (Duncan)</li>
<li><input name="selCol" type="checkbox" value="6"> District 6 (Willner)</li>
<li><input name="selCol" type="checkbox" value="7"> District 7 (Brady)</li>
<li><button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddDistrictChanged();">Submit</button></li>
</ul>
<div id="txtHere"></div>
<div id="txtHere2"></div>
Would make it cleaner if you wrapped the text in an element like <span>
<li><a ><input/><span> District 1 (Porter)</span></a></li>
Next can use :checked pseudo selector to select only checked inputs
function ddDistrictChanged() {
var txt = "nothing selected";
var $items = $('#ddDistrict').find('li has(input:checked)');
if ($items.length) {
txt = $items.map(function() {
return $(this).find('span').text()
}).get().join(', ');
}
$('#txtHere2').text(txt);
}
Working JSFiddle DEMO
To start with, lets refactor your HTML to make it a bit easier to interact with when using JavaScript/jQuery. I have opted to use labels with your inputs instead of <a> tags.
<ul class="ddDistrict dropdown-menu">
<li>
<input type="checkbox" id="cbox1" value="1" checked>
<label for="cbox1" class="small underlineText_No">District 1 (Porter)
</label>
</li>
<li>
<input type="checkbox" id="cbox2" value="2">
<label for="cbox2" class="small underlineText_No">District 2 (Jones Jr)
</label>
</li>
<li>
<input type="checkbox" id="cbox3" value="3">
<label for="cbox3" class="small underlineText_No">District 3 (Horne)
</label>
</li>
<li>
<input type="checkbox" id="cbox4" value="4">
<label for="cbox4" class="small underlineText_No">District 4 (Haddaway)
</label>
</li>
<li>
<input type="checkbox" id="cbox5" value="5">
<label for="cbox5" class="small underlineText_No">District 5 (Duncan)
</label>
</li>
<li>
<input type="checkbox" id="cbox6" value="6">
<label for="cbox6" class="small underlineText_No">District 6 (Willner)
</label>
</li>
<li>
<input type="checkbox" id="cbox7" value="7">
<label for="cbox7" class="small underlineText_No">District 7 (Brady)
</label>
</li>
<li>
<button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddDistrictChanged();">Submit</button>
</li>
</ul>
<div class="txtHere"></div>
I then created some basic JavaScript/jQuery to check if any checkboxes have been checked on load and update the DOM according to what has been checked, and when they are checked.
var $inputs = $('.ddDistrict input');
var $outputWrapper = $('.txtHere');
// Check for boxes that have already been checked and
// append their labels to the DOM.
$inputs.each(function() {
var currentLabel = $(this).next('label').text();
var currentID = $(this).attr('id');
if (this.checked) {
var outputText = $('<p></p>').addClass(currentID).text(currentLabel);
$outputWrapper.append(outputText);
}
});
// This event handler will watch for any changes to the
// checkboxes and will append the value of their labels
// to the DOM on change.
$inputs.change(function() {
var currentLabel = $(this).next('label').text();
var currentID = $(this).attr('id');
if (this.checked) {
var outputText = $('<p></p>').addClass(currentID).text(currentLabel);
$outputWrapper.append(outputText);
} else {
$('.' + currentID).remove();
}
});
It's all relatively simple stuff and the code can be refactored to make it more DRY, but this should definitely put you in the right direction. Let me know if you have any questions.