jQuery creating setting a page and save the changes - javascript

I am trying to develop a setting page in jQuery for an app. in this page i have five check box as:
<input type="checkbox" name="checkbox1" id="checkbox1_0" class="custom" value="1"/>
<label for="checkbox1_0">One</label>
<input type="checkbox" name="checkbox1" id="checkbox1_1" class="custom" value="2"/>
<label for="checkbox1_1">Two</label>
<input type="checkbox" name="checkbox1" id="checkbox1_2" class="custom" value="3"/>
<label for="checkbox1_2">Three</label>
<input type="checkbox" name="checkbox1" id="checkbox1_3" class="custom" value="4"/>
<label for="checkbox1_3">Four</label>
<input type="checkbox" name="checkbox1" id="checkbox1_4" class="custom" value="5"/>
<label for="checkbox1_4">Five</label>
now how its possible to have a save button which by clicking, it saves the status of each check box and the sum of their values. so when the app is closed and then is opened again the changes are saved. for example one may chose check-boxes 1, 2 and 3 which should be saved and checked. also their sum in a constant like A = 1+2+3 = 6;
i would be really thankful if anyone could help me

<script type="text/javascript">
$(document).ready(function () {
$('.custom').click(function () {
var sum = 0;
$('.custom:checked').each(function () {
sum += parseFloat($(this).val());
});
alert(sum);
});
});
</script>
Instead of alert, you may set the sum value to anywhere you need

Related

Count total number of checkboxes what are checked and show on page via JS

I want to show the total number of checkboxes that user has selected on the page. Here is my code.
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected = <p>
Please provide the javascript code needed to achieve this. I know this has been asked before but i failed to benefit from those answers as they required me to edit the JS code to fit to my HTML, which i am not capable of at this point.
You could use .querySelectorAll() method to select all the elements you want to target then use length method that will return the number of cheched element like :
document.querySelectorAll('input[name="fruit"]:checked').length;
_______________________________________________^^^^^^^ //Used to select just checked inputs
NOTE: The use of name selector input[name="fruit"] target just the desired input's instead of all the document checkbox's.
Live example using jQuery :
$('input[name="fruit"]').click(function() {
console.log(document.querySelectorAll('input[name="fruit"]:checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
You can use a querySelector.
document.querySelectorAll("input:checked").length;
Note that this will select all checkboxes in the document. If you just want to refer to a certain group of checkboxes, give all the checkboxes in the group the same name and refer to them like this:
document.querySelectorAll("input[name='name']:checked").length;//replace 'name' with the name of the checkboxes
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p id="result">Total Number of Items Selected = <p>
<script>
showChecked();
function showChecked(){
document.getElementById("result").textContent = "Total Number of Items Selected = " + document.querySelectorAll("input:checked").length;
}
document.querySelectorAll("input[name=fruit]").forEach(i=>{
i.onclick = function(){
showChecked();
}
});
</script>
While you've requested a JavaScript solution, this can be achieved with CSS alone:
/* specifies the named counter that will be incremented by
each checked check-box: */
input[type=checkbox]:checked {
counter-increment: checked;
}
/* shows the counter in the '::after' pseudo-element of the
sibling <p> element: */
p::after {
content: ' ' counter(checked);
}
<input type="checkbox" name="fruit" />A
<input type="checkbox" name="fruit" />B
<input type="checkbox" name="fruit" />C
<p>Total Number of Items Selected =</p>

ID.length doesnt return the expected value

i have 3 checkbox with same ID. When I try to do following in the javascript I get the output as 9. Can you see where am I going wrong?
onclick of checkbox; I calling a function --> chkBoxCount(this);
function chkBoxCount(chk){
alert(chk.id.length;}
EDIT:
<input type="checkbox" name="f_seizure" id="f_seizure_1" onclick="chkBoxCount(this);" value="0"> No known episode
<input type="checkbox" name="f_seizure" id="f_seizure_2" onclick="chkBoxCount(this);" value="1"> EEG
<input type="checkbox" name="f_seizure" id="f_seizure_3" onclick="chkBoxCount(this);" value="2"> Suspected/Clinical
You said that you expected 3 as result, so if i'm understanding, you want to count the number of checkboxes with the same name. This is how to do it, enjoy ^^
chkBoxCount = function() {
alert($("input[name=f_seizure]").length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="f_seizure" id="f_seizure_1" onclick="chkBoxCount();" value="0"> No known episode
<input type="checkbox" name="f_seizure" id="f_seizure_2" onclick="chkBoxCount();" value="1"> EEG
<input type="checkbox" name="f_seizure" id="f_seizure_3" onclick="chkBoxCount();" value="2"> Suspected/Clinical
It should be:
<input type="checkbox" name="vehicle" value="Bike" id="bike" onclick="chkBoxCount(this)" > I have a bike</input>
function chkBoxCount(chk){
var id = chk.id;
id = id.split("");
alert(id.length);
}
What this does is get the passed element's id, substring it into indivual characters, and then alert the number of characters. This has been tested; It works! Hope this helped!

add checkbox on input type number change

I would like to know how to add checkboxes on input type number change.
By default I have :
HTML CODE
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onkeydown="change_cb()"/>
<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">
If I change my checkbox number to 2, I would like javascript/ajax add
<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">
Same as if I change my change number to 1, it has to remove one checkbox.
I already did same thing but with table (add one row or remove one row) but here i don't know how to add new element (on my first script I don't add new table, just new row)...
Need help to write my JS function change_cb()
EDIT TO GIVE YOU MY ANSWER
I find how to do this with DADE help (thank you DADE) :
HTML CODE (same)
<label for="cb_number">How many checkboxes ?</label>
<input id="cb_number" name="cb_number" type="number" size="1" maxlength="1" value="1">
<div class="my_cb_result"></div>
jQuery CODE
$(window).ready(function() {
$('#cb_number').on('keyup mouseup', function() {
var number = parseInt($(this).val());
$('input[type="checkbox"]').remove();
$('label[class="to_del"]').remove();
for (var i=1;i<=number;i++) {
var data = '<label for="checkbox" class="to_del">Label of my checkbox</label><input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="'+i+'">';
}
$('.my_cb_result').append(data);
});
});
JSFiddle with comments
Try this:
var ele = '<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">';
document.getElementById("yourElementID").appendChild(ele);
HTML:
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="0">
<div class="inputs"></div>
JS:
$('#checkbox_number').on('keyup mouseup', function() {
var number = parseInt($(this).val());
$('input[type="checkbox"]').remove();
for (var i=1;i<=number;i++) {
var data = '<input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="cb'+i+'">';
$('.inputs').append(data);
}
});
JSFiddle with comments
Do you mean if checkbox_number's value is set to "2" that you'd like to render the second checkbox?
If so, you should use onblur or similar on checkbox_number to run a function that will render the new one via a getElementById and appendChild.
IE:
<script type="text/javascript">
function change_cb() {
var secondCheckbox = '<input id="checkbox_number2" name="checkbox_number" type="number" size="1" maxlength="1" value="1" />";
document.getElementById("yourForm").appendChild(secondCheckBox);
}
</script>
<div id="yourForm">
<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onblur="change_cb()"/>
<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">
</div>
edit: From what you're posting, you shouldn't need Ajax, by the way.

display selected checkbox options on the page

was wondering if i could get a little help. I have 3 checkboxes and want to display the text before each checkbox back to the user.
<form id="extras" onchange="calculate()">
option 1<input type="checkbox" name="box" value="2000" id="snow" onchange="calculate()" checked><br>
option 2<input type="checkbox" name="box" value="500" id="water" onchange="calculate()" checked><br>
option 3<input type="checkbox" name="box" value="150" id="air" onchange="calculate()"><br><br>
</form>
so i can say you have selected option 1 and option 2 if they are both selected. Ive managed to to this for my dropdown using innerHTML but am unsure how to achieve this for the checkboxes. any ideas on how i can do this? thanks for any advice.
HTML
<form id="extras">
<label id="lbl_1">option 1</label><input type="checkbox" name="box" value="2000" id="1" onchange="calculate()"><br>
<label id="lbl_2">option 2</label><input id="2" type="checkbox" name="box" value="500" onchange="calculate()"><br>
<label id="lbl_3">option 3</label><input type="checkbox" name="box" value="150" id="3" onchange="calculate()"><br><br>
</form>
<span id="txt"></span>
Calculate function
function calculate()
{
document.getElementById("txt").innerHTML = "";
var checkBoxes = document.getElementsByName("box");
for(var i=0; i < checkBoxes.length;i++)
{
if(checkBoxes[i].checked)
{
document.getElementById("txt").innerHTML += document.getElementById("lbl_" checkBoxes[i].id).innerHTML
}
}
}
And JsFiddle
Here you go. I wrote this in jQuery, but you can convert it to vanilla JS.
http://jsfiddle.net/P2BfF/
Essentially you need to create labels for your checkboxes:
<label for='snow'>option 1</label>
Then based on checked, you can display the innerHTML of that element.
Here is my JS:
var checkboxes = $('#extras').find('input[type=checkbox]');
checkboxes.on('click',function() {
var selected = [];
checkboxes.each(function(idx,item) {
if (item.checked)
selected.push( $('label[for="' + item.id + '"]').html() );
});
return alert(selected);
});

Javascript not Un-Hiding Content

(I was unsure what title to use so i took what i felt described it if it doesnt fit please tell me/change it)
So i've been making this league of legends site for a while now and ran into a trouble.
I've been making a Filter menu that filters the "Champions"(Hero's) to only show those with the correct role/ability.
So i got an on-click script on checkboxes that should show the correct Champions when clicked on. but it doesnt seem to work.
When i uncheck the textbox it correctly takes back all of the champions, but when i "Check" it all champions disappears (should do this) but it doesnt show those wich apply to the filter. (I got all the correct id's on the DIV's, i know this since i have a search bar that works for filtering aswell but i want checkboxes for it since its simpler)
Checkboxes:
AD<input type="checkbox" name="adcarry" value="adcarry" id="check1" class="check1" onclick="boxchanged()">
AP<input type="checkbox" name="apcarry" value="apcarry" id="check2" class="check2" onclick="boxchanged()">
Carry<input type="checkbox" name="carry" value="carry" id="check3" class="check3" onclick="boxchanged()">
Tank<input type="checkbox" name="tank" value="tank" id="check4" class="check4" onclick="boxchanged()">
Support<input type="checkbox" name="support" value="support" id="check5" class="check5" onclick="boxchanged()">
Jungler<input type="checkbox" name="jungler" value="jungler" id="check6" class="check6" onclick="boxchanged()">
Burst<input type="checkbox" name="burst" value="burst" id="check7" class="check7" onclick="boxchanged()">
<button type="button" onclick="boxchanged()">Reset</button>
Affected divs are designed as following: (The classes changes depending on what the champion can do)
<div class="champion apcarry mid" id="ahri" onclick="OnClickChampion(this.id)"><img src="img/champions/ahri.jpg"> Ahri </div>
Script:
function boxchanged ( )
{
$("#num1").val("Search..");
if ($("[type='checkbox']:checked").length == 0)
{
$(".champion").show(200);
}
else
{
$(".champion").hide(200);
for (var i = 1;i < 7; i++)
{
var name = "check"+i;
console.log(name)
var name2 = document.getElementById(name);
console.log(name2)
if (name2.checked == true)
{
var name3 = name2.name;
$("."+name3).show();
}
}
}
};
You should stop any animation
$("."+name3).stop().show();
Here is your code much simplified
DEMO
$(function() {
$(".champion").on("click",function() {
// put OnClickChampion here
});
$(".check").on("click",function() {
$("#num1").val("Search..");
var checked = $("[type='checkbox']:checked");
console.log(checked.length);
if (checked.length == 0) {
$(".champion").stop().show(200);
}
else {
$(".champion").hide(200);
checked.each(function() {
var klass = $(this).val();
$("."+klass).stop().show(200);
});
}
});
});
using
<form>
<label for="check1">AD</label>
<input type="checkbox" value="adcarry" id="check1" class="check"/>
<label for="check2">AP</label>
<input type="checkbox" value="apcarry" id="check2" class="check"/>
<label for="check3">Carry</label>
<input type="checkbox" value="carry" id="check3" class="check"/>
<label for="check4">Tank</label>
<input type="checkbox"value="tank" id="check4" class="check"/>
<label for="check5">Support</label>
<input type="checkbox" value="support" id="check5" class="check"/>
<label for="check6">Jungler</label>
<input type="checkbox" value="jungler" id="check6" class="check"/>
<label for="check7">Burst</label>
<input type="checkbox" value="burst" id="check7" class="check"/>
<button type="reset" class="check">Reset</button>
</form>
<div class="champion apcarry mid" id="ahri"><img src="img/champions/ahri.jpg"> Ahri </div>
To show only the ones with more than one class
var klasses=[]
checked.each(function() {
klasses.push("."+$(this).val())
});
$(".champion").not(klasses.join(",")).stop().hide(200);

Categories