I'm having trouble getting my var to accept more than one input.
When I select one checkbox, it shows me the value, however, when I select anymore I got an undefined error.
JavaScript
window.onload = function() {
var input= document.querySelectorAll('input#add2basket');
var radio= document.querySelectorAll('input#hi');
for (var j=0; j < radio.length; ++j){//loops over buttons
radio[j].onclick = function (){// find radio button
var input = findChecked(this.name);
alert (input.value)
return false;
// determine pizza size
//var size = input.value==='1'?‘Small':(input.value==='2'?'Regular':'Large');
// determine pizza price
//var price =Number(input.getAttribute('data‐price'));
// add a ‘new’ pizza to the basket
//addToBasket(newPizza(this.name,size, price));
};
};
function findChecked(name){
var css = 'input#hi[name="'+name+'"]';
var inputs = document.querySelectorAll(css);
var checked = _.filter(inputs, function (input){
document.write('<pre>'+input.checked+'</pre>')
return input.checked;
});
return checked.length===1?checked[0]:null;
}
}
HTML
<div>
<fieldset>
<legend class="Topping">Topping</legend>
<ul>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="1"> <label class=
"box">Double Cheese</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="2"> <label class=
"box">Peppers</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="3"> <label class=
"box">Pepperoni</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="4"> <label class=
"box">Olives</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="5"> <label class=
"box">Beef</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
</ul>
</fieldset>
</div><!-- end topping -->
</form>
<div id="actionbtn">
<!--== action buttons==-->
<input class="apply" type="button" value=
"Back To Menu">
<input class="apply" name="top" id="add2basket" id="actionbtn2" type="button"
value="Proceed">
</div><!--==end of action buttons==-->
When I print the input.checked, it shows the selected boxes as true but where do i go from there
JavaScript solutions only please.
The attribute id must be unique across the whole document.
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
updated code:
<li class="lastset"><input class="cbox" id="hi_1" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
(do this for every li and give each li its own id, if you really need an id in a li tag
To get all your inputs, use a different selector, like the class-attribute:
var css = 'input.cbox[name="'+name+'"]';
var radio= document.querySelectorAll('input.cbox');
Just select checkboxes by class name (and don't duplicate id's):
window.onload = function () {
var input = document.querySelectorAll('input#add2basket');
var radio = document.querySelectorAll('input.cbox');
for (var j = 0; j < radio.length; j++) {
radio[j].onchange = function () {
var input = findChecked(this.name);
return false;
};
};
function findChecked(name) {
var css = 'input.cbox:checked';
var inputs = document.querySelectorAll(css);
return inputs;
}
}
Pluss you can simplify selection of the checked only using :checked pseudo selector.
http://jsfiddle.net/BPFTp/1/
Related
When I click on Select, a box opens and we select many options, including father and child.When options are selected
After selection, immediately display the ID numbers on the input. When we click OK, the box will be hidden. I want each of the boxes to be done separately in the input .This is My Html:
<button class="btn-select">Select one ...</button>
<div class="box" style="display:none">
<input type="checkbox" class="checkbox" value="1">Check Box 1
<input type="checkbox" class="checkbox" value="2">Check Box 2
<input type="text" class="input input-1" value="">
<button class="btn-ok">Ok</button>
</div>
<button class="btn-select">Select Two (Father/Children) ...</button>
<div class="box" style="display:none">
<ul class="father">
<li>
<input type="checkbox" class="checkbox" value="1">Part 1
<ul class="children">
<li><input type="checkbox" class="checkbox" value="5">Check Box 5</li>
</ul></li>
<li>
<input type="checkbox" class="checkbox" value="2">Part 2
<ul class="children">
<li><input type="checkbox" class="checkbox" value="7">Check Box 7</li>
<li><input type="checkbox" class="checkbox" value="8">Check Box 8</li>
</ul></li></ul>
<input type="text" class="input input-2" value="">
<button class="btn-ok">Ok</button>
</div>
.
...Select Three...
..Select Four..
..
.
This is My JS (Children and Father):
handleChildren = function() {
var $checkbox = $(this);
var $checkboxChildren = $checkbox.parent();
$checkboxChildren.each(function() {
if ($checkbox.is(":checked")) {
$(this).prop("checked", "checked");
} else {
$(this).removeProp("checked");
}
});
};
handleParents = function(current) {
var $parent = $(current).closest(".children").closest("li").find("> input[type=checkbox]");
if ($parent.parent().find(".children input[type=checkbox]:checked").length > 0) {
$parent.prop("checked", "checked");
} else {
$parent.removeProp("checked");
}
handleParents($parent);
}
$("ul.father").find("input[type=checkbox]").each(function() {
$(input).on("click", handleChildren);
$(input).on("click", function() {
handleParents(this);
});
});
This is My JS:
$(document).on('click', '.btn-ok', function(){
$('.box').hide()
});
$(document).on('click', '.btn-select', function(){
$('.box').hide()
$(this).next().show();
});
$(".checkbox").change(function() {
var text = "";
$(".checkbox:checked").each(function() {
text += $(this).val() + ",";
});
text = text.substring(0, text.length - 1);
$(this).next().val(text);
});
Now an error is shown by the console that says:
Uncaught InternalError: too much recursion
closest file:///var/www/html/jquey.js:1
Your handleParents calls itself unconditionally.
I'm quite new to JS + HTML but basically i want 4 radio buttons, each with a different name like this
o PS4
o Xbox
o Nintendo DS
When one of these is clicked/checked, i want to output the price which will be held in a "p" next to them, as shown
o PS4 £400
""
""
The price is then hidden when the next is clicked, and the corresponding price for that is then shown, ive spent hours and hours trying to search for this and test things, but nothing seems to work, so ANY help is greatly appreciated
Thanks,
Dan
Here is a plain JavaScript example:
<form id="form">
<label>
<input name="console" type="radio" value="400">PS4</label>
<label>
<input name="console" type="radio" value="350">XBox</label>
<label>
<input name="console" type="radio" value="200">Nintendo DS</label>
</form>
<br>
<div>Price:
<div id="price"></div>
</div>
JavaScript (Using ES6)
document.getElementById('form').addEventListener('change', () => {
const radios = document.getElementsByName('console');
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
price = document.getElementById('price');
price.innerHTML = `<p>£${radios[i].value}</p>`;
}
});
});
Sample:
JsFiddle
Here is the code that works perfectly fine:
$(document).ready(function(){
$(".price").hide();
$("input").click(function(){
$(".price").hide();
$(this).siblings().show();
});
});
<form id="form">
<span>
<input type="radio" name="drink" value="vodka"/>Vodka <span class="price">$40</span><br />
</span>
<span>
<input type="radio" name="drink" value="beer"/>Beer <span class="price">$50</span><br />
</span>
<span>
<input type="radio" name="drink" value="juice"/>Juice <span class="price">$20</span><br />
</span>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or try this jsfiddle directly here:
https://jsfiddle.net/balyancoder/dbgkfw0f/
Here is an example using plain javascript and paragraph tag along with every radio button:
HTML:
<ul>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 1
<p class="parag">price 1</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 2
<p class="parag">price 2</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 3
<p class="parag">price 3</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 4
<p class="parag">price 4</p>
</li>
</ul>
Javascript:
var radios = document.getElementsByClassName("radio_btn");
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener(
'click',
function() {
var parags = document.getElementsByClassName("parag");
for (var i = 0; i < parags.length; i++) {
parags[i].style.display = "none";
}
this.nextElementSibling.style.display = "inline-block";
}
);
}
Here is the sample on JSFiddle
Consider the following radio buttons in html:
<tr>
<td> Lighting </td>
<td> <label for="lighting1"> Off </label>
<input id = "lighting1" name="lighting" type="radio" value="0"> </td>
<td> <label for="lighting2"> Low </label>
<input id = "lighting2" name="lighting" type="radio" value="1"> </td>
<td> <label for="lighting3"> High </label>
<input id = "lighting3" name="lighting" type="radio" value="2"> </td>
</tr>
I need a javascript statement that will assign the radio button's label on a variable instead of its value, ie 'Off', 'Low' or 'High' instead of '0', '1' or '2'. when the radio button is checked.
It seems so simple and straightforward yet I fail to achieve it no matter what I try. I haven't found any working answers on the forum either. Please spare me of stating all non workable trials and enlighten me with just a single line of code that works.
You can fetch radios using common name and update values using input.value = newValue
function updateValues(){
var radios = document.querySelectorAll('[name="lighting"]');
for(var i = 0; i< radios.length; i++){
var id = radios[i].getAttribute('id');
radios[i].value = document.querySelector('label[for="'+id+'"]').textContent.trim()
}
}
function registerEvents(){
var radios = document.querySelectorAll('[name="lighting"]');
for(var i = 0; i< radios.length; i++)
radios[i].addEventListener("change", handleChange)
}
function handleChange(){
console.log(this.value)
}
registerEvents();
<tr>
<td> Lighting </td>
<td> <label for="lighting1"> Off </label>
<input id="lighting1" name="lighting" type="radio" value="0"> </td>
<td> <label for="lighting2"> Low </label>
<input id="lighting2" name="lighting" type="radio" value="1"> </td>
<td> <label for="lighting3"> High </label>
<input id="lighting3" name="lighting" type="radio" value="2"> </td>
</tr>
<p id="selectedValues"></p>
<button onclick="updateValues()" >Update Values</button>
var radioButtons = document.querySelectorAll("input[type='radio']");
for(var i = 0; i< radioButtons.length; i++)
{
radioButtons[i].addEventListener("click", (e)=>{
var radioButton = e.target || e.srcElement;
var label = document.querySelector("label[for='" + radioButton.id + "'");
alert(label.innerText.trim());
});
}
EDIT: Removed the jquery snippet that I initially added. As the user is looking only for a javascript solution, retaining that alone.
I have a small script that checks for selected boxes and ads them up.
Some boxes are worth two some are worth one.
I can get them to add up, but only if I select one of two pointers first or vice versa.
Html
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">Some blah blah text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="two">Text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">text</label>
</div>
The Javascript
$(".two").change(function() {
var classes = $("input[type='checkbox'].two:checked").map(function() {
return this.className;
}).get().length * 2;
document.getElementById("program_management2").innerHTML = " Score:" + " " + Math.floor(classes) ;
$(".one").change(function() {
var classes2 = $("input[type='checkbox'].one:checked").map(function() {
return this.className;
}).get().length;
document.getElementById("program_management").innerHTML = " Score:" + " " + Math.floor(classes2 + classes) ;
});
});
If you only want to add the value of each checked checkbox, you should use the value attribute.
Since the value is a string, you have to parse it to an integer to use it in an addition.
$("input[type='checkbox']").click(function(){
var result = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1">This box value is 1<br>
<input type="checkbox" value="2">This box value is 2<br>
<input type="checkbox" value="5">This box value is 5<br>
<br>
<br>
The checked total is: <span id="total">0</span>
EDIT
I added a "checked class" count.
$("input[type='checkbox']").click(function(){
var result = 0;
var classOne = 0;
var classTwo = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
if( $(this).hasClass("one") ){
classOne++;
}
if( $(this).hasClass("two") ){
classTwo++;
}
$("#totalOne").html(classOne);
$("#totalTwo").html(classTwo);
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<br>
<br>
The checked total value is: <span id="total">0</span><br>
Class "one" checked total : <span id="totalOne">0</span><br>
Class "two" checked total : <span id="totalTwo">0</span><br>
The idea is to filter divs by comparing dynamically generated classes for divs and dynamically generated id's for checkboxes, where only divs with classes matching id's of checked checkboxes would show.
First subnav filters everything fine. However, subnav2 dosen't do anything.
Simplified html of it
<div class="itemswrap">
<div class="inditem dynamic1 dynamic12"></div>
<div class="inditem dynamic2 dynamic22"></div>
<div class="inditem dynamic3 dynamic32"></div>
<div class="inditem dynamic2 dynamic42"></div>
</div>
<ul class="subnav">
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic1" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic2" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic3" />
<label for="dynamic1">whatever label</label>
</li>
</ul>
<ul class="subnav2">
<li class="lifilter2">
<input type="checkbox" class="filtercheck2" id="dynamic12" />
<label for="dynamic12">whatever label</label>
</li>
<li class="lifilter2">
<input type="checkbox" class="filtercheck2" id="dynamic22" />
<label for="dynamic12">whatever label</label>
</li>
<li class="lifilter2">
<input type="checkbox2" class="filtercheck2" id="dynamic32" />
<label for="dynamic12">whatever label</label>
</li>
</ul>
And the js i've got so far.
var $filters = $('.filtercheck').change(function() {
var $items = $('.inditem').hide();
var filters = $filters.filter(':checked').map(function() {
return '.' + this.id;
}).get();
if (filters.length) {
$items.filter(filters.join()).show();
} else {
$items.show();
}
});
var $filtersb = $('.filtercheck2').change(function() {
var $itemsb = $('.inditem').hide();
var filtersb = $filtersb.filter(':checked').map(function() {
return '.' + this.id;
}).get();
if (filtersb.length) {
$itemsb.filter(filters.join()).show();
} else {
$itemsb.show();
}
});
I see that you fixed it but I had created a jsfiddle for your problem, akin to one I had to face in another project. Basically, you create a string from the checked checkboxes IDs and use that to show only those items that match the elements you checked. If no elements are checked, all items are shown (i.e. no filters are applied).
$("input[type='checkbox']").change(function()
{
var list = "";
$("input[type='checkbox']").each(function()
{
if(this.checked)
{
list = list + '.' + $(this).attr('id');
}
});
if(list !=='')
{
$("div.inditem").hide();
$(list).show();
}
else {
$("div.inditem").show();
}
});