jQuery - How to use each() in click event jquery? - javascript

Please see my html code:
<form action="#" class="check_opt" id="ckPrice">
<p><input class="niceCheck" type="checkbox" name="" value="0-49">3 millions - 10 millions (21)</p>
<p><input class="niceCheck" type="checkbox" name="" value="50-99"> >10 millions - 15 millions (7)</p>
<p><input class="niceCheck" type="checkbox" name="" value="100">15 millions and above (15)</p>
</form>
And jQuery code:
<script type="text/javascript">
$(document).ready(function() {
$('#ckPrice :checkbox').click(function() {
var price = 'abc';
$(".niceCheck").each(function() {
if ($(".niceCheck").is(":checked")) {
price += $(".niceCheck").value();
}
});
alert(price);
});
});
</script>
The alert function in bottom jQuery code only returns 'abc'. How should I do this?

Change:
if ($(".niceCheck").is(":checked")) {
price += $(".niceCheck").value();
}
to:
if ($(this).is(":checked")) {
price += $(this).val();
}
Your .each() call is looping through the elements you want and you need to refer to them via $(this). Also jQuery uses .val() not .value(). Of course, since you have unusual values your end result will be a string with something like "abc50-99100"
jsFiddle example

Your each function should use this
$(".niceCheck").each(function() {
if ($(this).is(":checked")) {
price += this.value;
}
});

You are checking against the first one
$(".niceCheck").each(function() {
var check = $(this);
if (check.is(":checked")) {
price += check.val();
}
});
alert(price);

Related

How to change the function to limit its action to the id, class or selector

I have a function written in jquery that copies the value of the checkbox to the textarea #msg
$(document).ready(function(){
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Clicking any checkbox on side copies of its value to the #msg field
How to reduce this effect that only checkboxes in the <ul> or a selected div operate in such a manner?
I want this:
<ul>
<input name="foo2" type="checkbox" value="Hello" id="tel_1">
<label for="tel_1">Hello</label>
</ul>
To be copied to the #msg textarea and this :
<input name="foo" value="123123123" id="tel_11" type="checkbox">
<label for="tel_11">Alan</label>
Not to be copied. I played with this :
$("input:checkbox").click(function()
And changed input:checkbox to ul:input:checkbox but I do not want to work.
You could use the id :
$(document).ready(function(){
$("#tel_1").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Or if you want to exclude just #tel_11 you could use :not() selector like :
$(document).ready(function(){
$("input:checkbox:not('#tel_11')").click(function() {
var output = "";
$("input:checked:not('#tel_11')").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Update :
If you have several id's as you sain in the comment (answers example) you could use start with selector like $("[id^='answer_'") ans that will include all of your 18 answers, e.g :
$(document).ready(function(){
$("[id^='answer_'").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Hope this helps.
Use a selector that just matches checkboxes that are children of <ul>.
$("ul > :checkbox").click(function() {
...
});

JQuery: How to return Form output number?

Hi everyone this is my first time using this site please bear with me because I have no experience in javascript coding.
I have the following in my javascript file:
$(document).ready(function() {
$("input").click(function(event) {
updateTotal();
});
});
function updateTotal() {
var total = 13600;
$("#menu input:checked").each(function() {
total += parseFloat(this.value);
});
$('#TotalCost').val("$" + total.toFixed(2));
}
And in my source code I have:
<div class= "checkbox" style="margin-top: 20px" id= "menu">
Cost of Dinner
<p>
<input type="checkbox" value="-200.00" name="Hamburger">Hamburger ($2)<br/>
<input type="checkbox" value="-400" name="French Fries">French Fries ($1)<br/>
<input type="checkbox" value="-1.5" name="Shake">Shake ($3)<br/>
</p>
<p>
Total Cost: <input type="text" name="TotlCost" id="TotalCost" size="10"/>
</p>
<div>
How do I format so the updateTotal() will return a number that has commas?
I found this code online that formats a string with commas
function commas(str) {
return str.replace(/.(?=(?:.{3})+$)/g, '$&,');
}
How do I use it?
Thank you very much for your help.
Try adding that function to your JavaScript file and then changing your code to something like:
function updateTotal() {
var total = 13600;
$("#menu input:checked").each(function() {
total += parseFloat(this.value);
});
var val = commas(total.toFixed(2).toString());
$('#TotalCost').val("$" + val);
}
This sets val to the total with commas.

Grab values from checked checkboxes and put them in an array using Javascript/jQuery

I want to get the values of checked checkboxes with the name="car_type[]" and alert the final array with all the values.
How to do that? So far, I have this code. But it's not working. I don't know how to loop through checked checkboxes properly and add the values to the array car_type_arr. I also cannot alert the final array using alert(car_type_arr);. Thanks for any help.
$().ready(function(){
$('.prettycheckbox').click(function(e) {
e.preventDefault();
var car_type_arr = [];
$("input:checkbox[name=car_type]:checked").each(function()
{
// here I need to add values to array like in php
// e.g. $car_type_arr[] = $the_grabbed_value;
// but using javascript syntax
// How to do that?
});
// then I need to alert the array, how to do that in JS?
alert(car_type_arr);
return false;
});
});
You can use map
var car_type_arr = $("input:checkbox[name=car_type]:checked").map(function() {
return this.value;
}).get();
console.log(car_type_arr);
Try below code:
<input type="checkbox" name="chkBox" value="xxx">
<input type="checkbox" name="chkBox" value="xxx1">
<input type="checkbox" name="chkBox" value="xxx2">
<input type="button" id="btnBox">
$(document).ready(function(){
$("#btnBox").click(function(){
var car_type_arr = [];
$("input:checkbox[name=chkBox]:checked").each(function() {
car_type_arr.push($(this).val());
alert(car_type_arr);
});
});
});
Demo: http://jsfiddle.net/XDpBP/
Try this:
$("input:checkbox[name=car_type]:checked").each(function()
{
car_type_arr.push($(this).val());
});
your code should look like,
$().ready(function(){
$('.prettycheckbox').click(function(e) {
e.preventDefault();
var car_type_arr = [];
$("input:checkbox[name=car_type]").each(function()
{
if($(this).is(':checked')){
car_type_arr.push($(this).val());
}
});
alert(car_type_arr);
return false;
});
});
$("input:checkbox[name=car_type]:checked").each(function() {
car_type_arr.push($(this).val());
});

How to get value of different checkboxes and calculate value of those checked checkboxes and show in the input field?

I have a little problem with getiing the value of diffrent checkboxes when it is checked. Here is my code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="checkbox"]').bind('click',function()
{
var waterdm = $('#waterdm').val();
$("#price").val(waterdm);
});
});
</script>
<p><input type="checkbox" id="waterdm" name="waterdm" value="10" />Water Damage</p>
<p><input type="checkbox" id="screendm" name="screendm" value="20" />Screen Damage</p>
<p><input type="checkbox" id="Chargerdm" name="Chargerdm" value="30" />Charger Damage</p>
<p><input type="checkbox" id="hdphdm" name="hdphdm" value="10" />Headphone Damage</p>
<p>
Calculated Price: <input type="text" name="price" id="price" />
</p>
What I want is whenever user check in checkboxes I need to get those value and show the sum of each checkbox value which is checked in to another input box. It Means I need to sum those value of each checkbox
is checked.And when user unchecked any of the checkboxes then that value should subtracted from the that total. I don't have enough experience in jquery. Please help me.
You would need to iterate over the cheboxes. And change event makes more sense when you are talking in terms of checkboxes..
Use on to attach events instead of bind
$(document).ready(function () {
// cache the inputs and bind the events
var $inputs = $('input[type="checkbox"]')
$inputs.on('change', function () {
var sum = 0;
$inputs.each(function() {
// iterate and add it to sum only if checked
if(this.checked)
sum += parseInt(this.value);
});
$("#price").val(sum);
});
});
Check Fiddle
$(document).ready(function () {
var waterdm = 0;
$('input[type="checkbox"]').bind('click', function (e) {
if (this.checked) {
waterdm += eval(this.value);
} else {
waterdm -= eval(this.value);
}
$("#price").val(waterdm);
});
});
Demo here
Try this
$(document).ready(function(){
var waterdm=0;
$('input[type="checkbox"]').on('click',function()
{
waterdm = waterdm+parseInt($(this).val());
$("#price").val(waterdm);
});
});
Demo
You can use following code
$(document).ready(function(){
$('input[type="checkbox"]').click(function()
{
var val = 0;
$('input[type="checkbox"]:checked').each(function(){
val+=parseInt($(this).val());
});
$("#price").val(val);
});
});
Demo
If you want to sum all checked checkboxes try something like this:
$('input[type="checkbox"]').bind('click',function()
{
var sum = 0;
$('input[type="checkbox"]:checked').each(function(){
var val = parseInt($(this).val());
sum += val;
});
$("#price").val(sum);
});

Add (and remove) group of textelements dynamically from a web form using javascript/jquery

im very new at javascipt (im php developer) so im really confused trying to get this working.
In my web form i have 3 textfields (name, description and year) that i need to let the user add as many he needs, clicking on a web link, also, any new group of text fields need to have a new link on the side for removing it (remove me).
I tried some tutorial and some similar questions on stackoverflow but i dont get it well. If you can show me a code example just with this function i may understand the principle. Thanks for any help!
this is the simplest thing that has come to my mind, you can use it as a starting point:
HTML
<div class='container'>
Name<input type='text' name='name[]'>
Year<input type='text' name='year[]'>
Description<input type='text' name='description[]'>
</div>
<button id='add'>Add</button>
<button id='remove'>Remove</button>
jQuery
function checkRemove() {
if ($('div.container').length == 1) {
$('#remove').hide();
} else {
$('#remove').show();
}
};
$(document).ready(function() {
checkRemove()
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
checkRemove();
});
$('#remove').click(function() {
$('div.container:last').remove();
checkRemove();
});
});
fiddle here: http://jsfiddle.net/Fc3ET/
In this way you take advantage of the fact that in PHP you can post arrays: server side you just have to iterate on $_POST['name'] to access the various submissions
EDIT - the following code is a different twist: you have a remove button for each group:
$(document).ready(function() {
var removeButton = "<button id='remove'>Remove</button>";
$('#add').click(function() {
$('div.container:last').after($('div.container:first').clone());
$('div.container:last').append(removeButton);
});
$('#remove').live('click', function() {
$(this).closest('div.container').remove();
});
});
Fiddle http://jsfiddle.net/Fc3ET/2/
jsFidde using append and live
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var html = "<div>" + '<input name="name{0}" type="text" />' + '<input name="description{1}" type="text" />' + '<input name="year{2}" type="text" />' + '<input type="button" value="remove" class="remove" />' + '</div>',
index = 0;
$(document).ready(function() {
$('.adder').click(function() {
addElements();
})
addElements();
$('.remove').live('click', function() {
$(this).parent().remove();
})
});
function addElements() {
$('#content').append(String.format(html, index, index, index));
index = index + 1;
}
Look at this: http://jsfiddle.net/MkCtV/8/ (updated)
The only thing to remember, though, is that all your cloned form fields will have the same names. However, you can split those up and iterate through them server-side.
JavaScript:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#addnew").click(function(e) {
$("#firstrow").clone() // copy the #firstrow
.removeAttr("id") // remove the duplicate ID
.append('<a class="remover" href="#">Remove</a>') // add a "remove" link
.insertAfter("#firstrow"); // add to the form
e.preventDefault();
});
$(".remover").live("click",function(e) {
// .live() acts on .removers that aren't created yet
$(this).parent().remove(); // remove the parent div
e.preventDefault();
});
});
</script>
HTML:
Add New Row
<form id="myform">
<div id="firstrow">
Name: <input type="text" name="name[]" size="5">
Year: <input type="text" name="year[]" size="4">
Description: <input type="text" name="desc[]" size="6">
</div>
<div>
<input type="submit">
</div>
</form>
Try enclosing them in a div element and then you can just remove the entire div.
Try this
Markup
<div class="inputFields">
..All the input fields here
</div>
Add
<div class="additionalFields">
</div>
JS
$("#add").click(function(){
var $clone = $(".inputFields").clone(true);
$clone.append($("<span>Remove</span").click(functio(){
$(this).closest(".inputFields").remove();
}));
$(".additionalFields").append($clone);
});
There are 2 plugins you may consider:
jQuery Repeater
jquery.repeatable
This question has been posted almost 4 years ago. I just provide the info in case someone needs it.

Categories