I'm looking to update a textbox value when a checkbox is selected, however when a checkbox is selected I get 'NaN'.
Can anyone see where I've gone wrong?
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
var val = parseInt($(this).next().val());
sum += val;
});
$('#sum').val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<div class="targeting">
<h1>Targeting</h1>
<ul>
<li>
<input type="checkbox" name="geographic" value="0.07" id="geographic_checkbox" onclick="GeographicFunction()">Geographic<br>
<p id="geographic_text" style="display:none">+£0.08 CPC</p>
<ul>
<li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" onclick="RegionsFunction()">Regions, Cities & Towns<br></li>
<p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
<li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" onclick="RingfencingFunction()">Ring-Fencing<br></li>
<p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
</ul>
</li>
</ul>
<input id="sum" type="text" />
Why we are using "next()" and "each" together. Also parsing int and passing 0.01 value will always hydrates to 0. Try removing "next()" and parseFloat instead of parseInt
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum += val;
});
$('#sum').val(sum);
});
});
This is how I'd do it with Vanilla Javascript:
const checkBox = document.querySelector("#checkbox")
const textBox = document.querySelector("#textbox")
checkBox.addEventListener("change", () => {
textBox.value = checkBox.checked ? textBox.value = parseFloat(textBox.value) + parseFloat(checkBox.value) : textBox.value = 0
})
<input type="text" id="textbox" value="0">
<input type="checkbox" id="checkbox" for="textbox" value="0.08">
Edit: Updated it after #mplungjan 's comment and your question.
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating-point number.
The toFixed() method formats a number using fixed-point notation.
Learn more about toFixed()
Learn more about parseFloat()
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function(){
sum += parseFloat(this.value);
});
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<input id="sum" type="text" />
It took a while to understand what you meant. You just want to sum all checked checkbox values?
$(() =>
$('input[type=checkbox]').on("click", () =>
$('#sum').val(
$('input[type=checkbox]:checked') // checked boxes
.map((i,fld) => +fld.value).get() // array of values
.reduce((a,b) => a+b) // summed
.toFixed(2) // rounded
)
)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<div class="targeting">
<h1>Targeting</h1>
<ul>
<li>
<input type="checkbox" name="geographic" value="0.07" id="geographic_checkbox" ">Geographic<br>
<p id="geographic_text" style="display:none">+£0.08 CPC</p>
<ul>
<li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" ">Regions, Cities & Towns<br></li>
<p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
<li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" ">Ring-Fencing<br></li>
<p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
</ul>
</li>
</ul>
<input id="sum" type="text" />
Related
My problem is that I want to add the value of input-checkbox. This code is adding the value but not to the same array
$(".ticketAddition").change(function (){
var name = [];
name.toString();
if (this.checked) {
name.push(this.name);
console.log(name);
}
});
You can loop over all the checked items to account for checking and unchecking alike:
$(".ticketAddition").change(function (){
var ticketSelection = [];
$('.ticketAddition:checked').each(function() {
ticketSelection.push(this.getAttribute('name'));
});
document.querySelector('#result').innerText = JSON.stringify(ticketSelection);
// or console.log(ticketSelection)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li><label><input type="checkbox" name="ticket_1" class="ticketAddition" /> Ticket #1</label></li>
<li><label><input type="checkbox" name="ticket_2" class="ticketAddition" /> Ticket #2</label></li>
<li><label><input type="checkbox" name="ticket_3" class="ticketAddition" /> Ticket #3</label></li>
</ul>
Checked tickets: <span id="result"></span>
Try this:
var name = [];
$(".ticketAddition").change(function (){
name.toString(); // Why ?
if (this.checked) {
name.push(this.name);
console.log(name);
} else {
name.splice(name.indexOf(this.name), 1);
}
});
You can select all the checked checkbox using :checked selector. Use map() and get() to loop thru the checkboxes.
$(".ticketAddition").change(function() {
var names = $(".ticketAddition:checked").map(function() {
return this.name;
}).get();
console.log(names)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="ticketAddition" name="apple" value="apple"> apple<br>
<input type="checkbox" class="ticketAddition" name="orange" value="orange"> orange<br>
<input type="checkbox" class="ticketAddition" name="pear" value="pear"> pear<br>
You could instead get checked checkboxes inside your .tickedAddition element, where you map each element selected using $(":checkbox:checked", this) to its value attribute:
$(".ticketAddition").change(function() {
let names = $(":checkbox:checked", this).get().map(({value}) => value);
console.log(names);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="ticketAddition">
<label for="first">Frog</label>
<input type="checkbox" id="frog" name="cb" value="frog"/>
<label for="first">Emu</label>
<input type="checkbox" id="emy" name="cb" value="emu"/>
<label for="first">Bird</label>
<input type="checkbox" id="bird" name="cb" value="bird"/>
</form>
I have nine checkboxes linked to nine images and three of them use the name 'correct' using the code shown below.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"/>
</div>
The remaining six are unnamed using the code shown below.
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4"/>
</div>
I currently have the following code to produce an alert if the three checkboxes with the name "correct" are checked but it isn't working.
<script>
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
</script>
Can anyone help me with this?
Loop over all of the checkboxes, checking their state. Once this is done, create a variable "correct" and initialize it to true. Then go to each state in the variable and, if you find that its name isn't "correct" and it is checked or its name is "correct" and it isn't correct, set the variable to false. Then check if the variable is true and, if it is, display the alert.
View an example here: https://repl.it/GxsE/9
Using ES6:
const correctInputs = [...document.querySelectorAll('input[name="correct"]')];
const alertIfThree = () => {
const checkedCorrectInputs = correctInputs.filter(input => input.checked);
if (checkedCorrectInputs.length > 2) {
alert('Alert');
}
};
correctInputs.forEach(input => input.addEventListener('click', alertIfThree));
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
document.querySelectorAll('input[name="correct"]') gets all inputs with name "correct".
[...CODE] is spread operator, it converts code from previous point to array.
correctInputs.forEach(input => input.addEventListener('click', alertIfThree)) adds click event listener to each of them. That event listener is function alertIfThree().
alertIfThree() filters out those input elements that are not checked and produces alert if there are more than 2 of them.
EDIT
In response to your comment:
// jshint esnext: true
const inputs = [...document.querySelectorAll('input[name="correct"], input[name="incorrect"]')];
const alertIfCorrect = () => {
const checkedInputs = inputs.filter(input => input.checked),
noIncorrectCheckedInputs = checkedInputs.find(input => input.name === 'incorrect') === undefined;
if (checkedInputs.length > 2 && noIncorrectCheckedInputs) {
alert('Alert');
}
};
inputs.forEach(input => input.addEventListener('click', alertIfCorrect));
<p>Correct:
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
</p>
<p>Incorrect:
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
</p>
const is ES6 constant. "The value of a constant cannot change through re-assignment, and it can't be redeclared".
[...CODE_HERE] is so called spread syntax. Here, it turns what it contains after ellipsis into an array. Other way to do it would be to use Array.from().
() => { and input => CODE_HERE are arrow functions. They are ES6's syntactic sugar for function declaration.
What stands before => are parameters. () stands for 0 parameters. If you wanted function that takes few parameters, those braces would need to have those few parameters inside them. For one parameter, parameter's name can replace braces altogether (like in second code in this bullet point).
What stands after => is either expression or group of statements. Statements are surrounded by curly brackets ({}). If you omit them, you are writing an expression that your function will return. For example input => input.checked is equivalent to function(input) { return input.checked; }.
filter() and find() are methods of array prototype. They respectively filter and search an array using condition defined in a function that is passed to them as a parameter. Read more by following those two links.
If you need something else explained, let me know. Those functions and structures here are pretty... fresh, so you can just not know them yet.
I put this in a JSfiddle and it works for me. I just wrapped your JS in a function and added an onclick event.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"onclick="validate()"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4" onclick="validate()"/>
</div>
<script type=text/javascript">
function validate()
{
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
}
</script>
It will require some javascript. You will need o check the checkboxes each time one changes. So to start with you will need to check your checkboxes, assuming they have an assigned class of 'chk'. This can be done with a querySelector.
Each time a checkbox changes, the function 'check_checkboxes()' is called. This function will see for each checkbox with name='correct' if it is checked and then increment 'count'
var checkboxes = document.querySelectorAll(".chk");
var correct = document.querySelectorAll("[name=correct]");
function check_checkbox() {
var count = 0;
[].forEach.call(correct, function(item) {
if (item.checked) {
count++;
}
});
if (count >= 3) {
alert("count of 3 or more");
}
}
[].forEach.call(checkboxes, function(item) {
item.addEventListener("change", function() {
check_checkbox();
}, false);
});
<div class="nine">
<label for="correct1"><img class="picture1" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
Check the loop. Use for (i = 0; i < correct.length; i++) { instead for (i = 0; i <= correct.length; i++) {
var i, correct = document.getElementsByName('correct');
var correct_answers = [];
function validate(){
correct_answers = [];
for (i = 0; i < correct.length; i++) {
var element = correct[i].getAttribute("id");
var checked = correct[i].checked;
correct_answers.push({element,checked});
}
}
function show(){
document.getElementById('results').innerHTML ="";
for(var e=0;e<correct_answers.length;e++){
var box = document.createElement('div');
box.innerHTML = correct_answers[e].element+ " " + correct_answers[e].checked+ "<br>";
document.getElementById('results').appendChild(box);
}
}
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct1" name="correct"/>
</div>
<div class="nine">
<label for="correct2"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct2" name="correct"/>
</div>
<div class="nine">
<label for="correct3"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct3" name="correct"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect4"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect5"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect6"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect7"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect8"/>
</div>
<button onclick="show();">show results</button>
<div id="results"></div>
Use document.querySelectorAll('input[name]=correct') in your code.
Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>
Scenario:
Three unchecked check-boxes, each with different id and value.
An empty paragraph (or label) with id = par.
[CB1] has value 1.
[CB2] has value 2.
[CB3] has value 3.
Now, when I click cb1 -> 'par' gets and prints the value of cb1.
Clicking on cb3, 'par' gets the value of cb1+cb3.
Clicking cb1, 'par' subtracts the value of cb1 and so on.. I think you get the point.
How can I achieve this with only HTML and JavaScript (without jQuery).
<input type="checkbox" id="1" value="1" />
<input type="checkbox" id="2" value="2" />
<input type="checkbox" id="3" value="3" />
<p id="par"></p>
This will do it: jsfiddle example (updated to remove alert)
HTML:
<input type="checkbox" id="1" value="1" onclick='checkClicked(event)'/>
<input type="checkbox" id="2" value="2" onclick='checkClicked(event)'/>
<input type="checkbox" id="3" value="3" onclick='checkClicked(event)'/>
<p id="par"></p>
JavaScript:
function checkClicked(element)
{
var targetElement = element.target;
var newVal = targetElement.value;
if( !targetElement.checked )
{
newVal *= -1;
}
var currentVal = document.getElementById('par').innerHTML;
if( currentVal )
{
newVal = parseInt(currentVal) + parseInt(newVal);
}
document.getElementById('par').innerHTML = newVal;
}
<label>
<input type="checkbox" id="check1" value="check1" onchange="alterP(this);"/>check1
</label>
<label>
<input type="checkbox" id="check2" value="check2" onchange="alterP(this);"/>check2
</label>
<label>
<input type="checkbox" id="check3" value="check3" onchange="alterP(this);"/>check3
</label>
<p id="par"></p>
js Code
function alterP(obj) {
var par = document.getElementById('par');
var txt = (obj.checked) ? obj.value : "";
par.innerHTML = txt;
}
<script>
document.getElementById("1").addEventListener("click", processCheck);
document.getElementById("2").addEventListener("click", processCheck);
document.getElementById("3").addEventListener("click", processCheck);
function processCheck() {
var theParagraph = document.getElementById("par");
var currentValue = 0;
if (!isNaN(parseInt(theParagraph.textContent))) {
currentValue = parseInt(theParagraph.textContent)
}
if (this.checked) {
theParagraph.textContent = currentValue + parseInt(this.value);
}
else {
theParagraph.textContent = currentValue - parseInt(this.value);
}
}
</script>
For instance, radiobutton one = value 1, radiobutton two = value 2.
Here is the code I have:
Script file:
<script type="text/javascript">
$(document).ready(function () {
$("div[data-role='footer']").prepend('Back');
$(".Next").click(function () {
$.mobile.changePage("#" + $("#Answer").val());
});
$("input[type=radio]").click(function () {
var answer = $(this).val();
$("#Answer").val(answer);
});
$('.Answer').live("click", function () {
var NextQuestionID = $(this).attr('NextQuestionId');
if (NextQuestionID == '') {
location.href = "/Surveys/Index";
}
$("#survey").load('/Questions/GetQuestion', { Id: NextQuestionID }, function () {
$('#answerInput').textinput();
$(".Answer").button();
});
});
});
and here is my markup:
<input type="radio" name="Answer" id="radio-choice-1" value="Question2" />
<input id="Answer" class="Answer" type="hidden" value="first" />
<div class="innerspacer">
Next
</div>
How do I assign the radio button as value from 1 to 4 and sum up the value for all the question?
There is a lot going on in your question and it is unclear what you want. I'm taking a guess and assuming you have a say 5 radio buttons and you want the 5th radio button value to be the sum of the other 4 values. Is that correct?
Here is an example of doing that: jsfiddle
HTML:
<div id="container">
<label>
<input type="radio" name="something" value="1">
A?
</label>
<label>
<input type="radio" name="something" value="3">
B?
</label>
<label>
<input type="radio" name="something" value="5">
C?
</label>
<label>
<input type="radio" name="something" value="">
All?
</label>
</div>
JavaScript:
$(document).ready(function() {
var choices = $('input[name="something"]');
var total = 0;
choices.each(function() {
var choice = $(this);
var value = parseInt(choice.val(), 10);
if (!isNaN(value)) {
total += value;
}
});
choices.filter(':last').val(total);
});
You will need to adapt this to your HTML.