Failed to sum variable in javascript - javascript

I have script to sum amount that I get from ID's of html element, this is the script :
<script type="text/javascript">
$(document).ready(function() {
/* var sum=0; */
$('#checkAll').click(function(event) { //on click
if(this.checked) { // check select status
var i = 0;
var sum = 0;
$('.checkItem').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
sum = sum + parseInt($('#amount'+i).val());
i++;
});
}else{
$('.checkItem').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
sum=0;
i=0;
}
$('#totalRecord').val(i);
$('#totalAmount').val(sum);
$('#totalAmountFake').val(ChangeToRupiah(sum));
});
});
</script>
function ChangeToRupiah(angka){
var rev = parseInt(angka, 10).toString().split("").reverse().join("");
var rev2 = "";
for(var i = 0; i < rev.length; i++){
rev2 += rev[i];
if((i + 1) % 3 === 0 && i !== (rev.length - 1)){
rev2 += ".";
}
}
return rev2.split("").reverse().join("") + ",00";
}
But when i run it, i got this message in my result element :
I guess it's about limitation of javascript variable, but it's not, I use Internet Explorer 9.

Related

show a rows depending on the number input

I need to dynamic add(clone)/remove div with inputs depends on the user input.
If the user changes input number to 4 or 10 it must show div 4 or 10 times.
Also, I need to modify the input name in cloned div (just like name_1).
Now I trying to do it in this way:
var $row = $('.row-with-fields');
var $clone = $row.clone();
$(".qty").on("keyup keydown change",function(event){
$qty = $(this).val(); // how many rows I needs
for(var i = 0; i < $qty; i++){
$row.after($clone.addClass('row_'+i));
}
});
You should consider two cases:
1-Clone() function is reference to element
2-You should check the number of event firing (i only use change event)
var $row = $('.row-with-fields');
$(".qty").on("change",function(event){
$qty = $(this).val(); // how many rows I needs
for(var i = 0; i < $qty; i++){
var $clone = $('.row-with-fields:first').clone();
$row.after($clone.addClass('row_'+i));
}
});
Finally I did it like that:
var $row = $('.rsvp-qty-fields');
$(".tribe-ticket-quantity").on("keyup keydown change",function(event){
$qty = $(this).val();
$rowsExist = $('.rsvp-qty-fields').length;
if ($rowsExist < $qty) {
for(var i = $rowsExist; i < $qty; i++){
var $clone = $('.rsvp-qty-fields:first').clone().removeClass('receiver');
$clone.find('.receiver').remove()
$row.after($clone.addClass('row_'+i));
}
console.log('add');
} else if($rowsExist > $qty) {
for(var i = $rowsExist; i > $qty; i--){
if (!($rowsExist <= 1)) {
$('.rsvp-qty-fields-wraper').children('.rsvp-qty-fields').last().remove();
} else {
console.log('stop remove');
}
}
console.log('remove');
} else {
console.log('equal');
}

Not able add multiple option to select

function successCallback(caRecords) {
var x = document.getElementById("custAccount"); // select
var option1 = document.createElement("option"); //options
//var accno = 0;
// caRecords i am fetch from MS CRM
var count = caRecords[0].results.length;
if (caRecords != null && count > 0) {
alert("records are not null");
for (var i = 0 ; i < count; i++)
{
var text = caRecords[0].results[i].new_name;
// alert(text + "J=" + j);
option1.text = text;
option1.value = j;
x.add(option1);
j++;
}
}
I got six records and try to insert that values into select as option. It showing last value of my 6 values.
Can anyone help me to improve my code?
You can iterate your values like this...
function successCallback(caRecords) {
var x = document.getElementById("custAccount"); // select
var options = "";
var count = caRecords[0].results.length;
if (caRecords != null && count > 0) {
alert("records are not null");
for (var i = 0; i < count; i++) {
options += "<option value=" + j + ">" + caRecords[0].results[i].new_name + "</option>";
j++;
}
x.innerHTML = options;
}

code not executing after for loop -- javascript

I'm writing a function that is supposed to loop through all my checkboxes and load the "value" of the checkboxes that are checked into an array, however nothing is executing beyond the first for loop. I'm completely stumped here, what am I missing?
function saveSettings(){
var count = 1; //count for db
var checked=[]; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for(var i=0; i<=2; i++) { //loads checked array with checked values
if(document.getElementById("check"+i).checked == true){
checked[inc] = document.getElementById("check"+i).value;
alert(checked[inc]) // <------ executing as expected
inc++;
}
}
alert("made it") // <------ not executing
if(checked.length>0){ // loads checked values into dataString
for(var i=0; i == checked.length; i++){
if(i == 0){
dataString = "co_" + count +"="+checked[i]
}
else {
dataString = dataString +"&co_" + count +"="+checked[i]
}
count++;
}
}
alert(dataString)
From your description of the problem, I think the problem is the number of checkboxes, if you have only 2 checkboxes then the condition i<=2 will cause problem because docuement.getElementById('check2') will be undefined causing an error like Uncaught TypeError: Cannot read property 'checked' of null in your console.
Since you are trying to deal with dynamic number of elements try to use a class to select the checkboxs of interest like
function saveSettings() {
var checked = [];
var dataString = "x";
var checks = document.getElementsByClassName('check');
//if you can't add a class then fetch all the checkboxes in the page
//var checks = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked == true) {
checked.push(checks[i].value);
}
}
console.log("made it: ", checked)
if (checked.length > 0) {
dataString = '';
for (var i = 0; i < checked.length; i++) {
dataString += (i == 0 ? '' : '&') + "co_" + i + "=" + checked[i]
}
}
alert(dataString)
}
<input type="checkbox" class="check" id="check0" value="1" />
<input type="checkbox" class="check" id="check1" value="2" />
<input type="checkbox" class="check" id="check2" value="3" />
<br />
<button onclick="saveSettings()">Test</button>
in this line
if(document.getElementById("check"+i).checked == true){
//...
the getElementById will return an undefined value, and undefined does not have the .checked property.
how many checkboxes do you have in the document?
your second for loop had a mistake
function saveSettings(){
var count = 1; //count for db
var checked=[]; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for(var i=0; i<=2; i++) { //loads checked array with checked values
if(document.getElementById("check"+i).checked == true){
checked[inc] = document.getElementById("check"+i).value;
alert(checked[inc]) // <------ executing as expected
inc++;
}
}
alert("made it") // <------ not executing
if(checked.length>0){ // loads checked values into dataString
for(var i=0; i < checked.length; i++){
if(i === 0){
dataString = "co_" + count +"="+checked[i]
}
else {
dataString = dataString +"&co_" + count +"="+checked[i]
}
count++;
}
}
alert(dataString)
}
<input type="checkbox" id="check0"/>
<input type="checkbox" id="check1"/>
<input type="checkbox" id="check2"/>
<button onclick="saveSettings()">Run</button>
Try below working solution. Second for loop condition in your code (i == checked.length) is wrong. It should be i < checked.length)
function saveSettings() {
var count = 1; //count for db
var checked = []; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for (var i = 0; i <= 2; i++) { //loads checked array with checked values
if (document.getElementById("check" + i).checked == true) {
checked[inc] = document.getElementById("check" + i).value;
inc++;
}
}
if (checked.length > 0) { // loads checked values into dataString
for (var i = 0; i < checked.length; i++) {
if (i == 0) {
dataString = "co_" + count + "=" + checked[i]
}
else {
dataString = dataString + "&co_" + count + "=" + checked[i]
}
count++;
}
}
alert(dataString)
}

Display the value on click of check box in an array

I have an array of 10 checkboxes. onclick of checkbox i want to get the value of that particular checkbox. That I am able to achieve using my code.When I click in serial order it is working fine. When I click on checkbox 5 after clicking on checkbox 7 the value of checkbox 5 ie..5 is getting added befor 7. I dont want in that order. I want the values to displayed in whatever order I click. My js file is as follows
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
function test() {
$('#catalog_table input:checkbox').change(function() {
var emails = [];
$('#catalog_table input:checkbox:checked').each(function() {
emails.push($(this).val());
});
var textField = document.getElementById("root");
textField.value = emails;
});
}
My HTML code is something like this
<table id="catalog_table"> </table>
<textarea id="root"></textarea>
Can any one please tell me how to do this?
Demo
Its messy, but it works:
http://jsfiddle.net/za7m8/1/
var selected = new Array();
$(document).ready(function(){
$("input[type='checkbox']").on('change', function() {
// check if we are adding, or removing a selected item
if ($(this).is(":checked")) {
selected.push($(this).val());
} else {
for(var i = 0; i<selected.length;i++) {
if (selected[i] == $(this).val()) {
// remove the item from the array
selected.splice(i, 1);
}
}
}
// output selected
var output = "";
for (var o = 0; o<selected.length; o++) {
if (output.length) {
output += ", " + selected[o];
} else {
output += selected[o];
}
}
$("#root").val(output);
});
});
You just have to change your javascript like this.
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
var emails = [];
function test() {
$('#catalog_table input:checkbox').change(function() {
if (this.checked)
{
if ( emails.indexOf( $(this).val() ) === -1 )
{
emails.push($(this).val());
}
} else
{
if ( emails.indexOf( $(this).val() ) !== -1 )
{
var index = emails.indexOf( $(this).val() );
emails.splice(index, 1);
}
}
var textField = document.getElementById("root");
textField.value = emails;
});
}
You need to clear up your code a bit, like this:
I assume that unchecking removes the value from the array, and checking adds.
var selected = new Array(); // What for is this here ?
$(document).ready(function () {
checkBoxTest();
});
function checkBoxTest() {
for (i = 0; i < 10; i++) {
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' + i + ' "/><td></tr>');
}
test();
}
function test() {
var emails = [],
textField = document.getElementById("root");
$('#catalog_table input:checkbox').change(function () {
var val = $(this).val();
// if you don't want removal of values on `uncheck`, comment out everything below excluding `emails.push(val)` and the last line
if(this.checked){ // if checked
emails.push(val); // add it
}else{
emails.splice(emails.indexOf(val), 1); // remove it if not checked
}
textField.value = emails; // set the value
});
}
DEMO

Change variable value when option is selected, return previous value when not selected anymore

I need to update the value of a variable (which I called "tot" in the example) according to what option of a dropdown menu is selected. If I select option 1 or 2 tot must be increased of 10, if I select option 3 variable "tot" must NOT be increased. If i select option 1, and then I change my mind and select option 3 the value of Tot must be restored.
Here's the html of the select
<select name='hello' id='hello'>
<option>Select an option...</option>
<option id='one'>One</option>
<option id='two'>Two</option>
<option id='three'>Three</option>
</select>
And here's the jquery script I wrote. I guess I didn't understand the functioning of .change function, because it doesn't work as I expected.
var extra = 0;
var tot = 0;
$(document).ready(function () {
$('#hello').change(function(){
if($('#one').is(':selected')) {
extra = 10;
}
else if($('#two').is(':selected')) {
extra = 10;
}
else if($('#three').is(':selected')) {
extra = 0;
}
tot = tot + extra;
});
});
Or (if I've understood what you're after correctly)....
var tot = 120; //some number picked at random
var helloed = false; // flag for whether incremented
$(document).ready(function(){
$("#hello").change(function(){
var sel = $(this).find(":selected").attr("id")
if (sel == "one" || sel =="two" ) {
if (!helloed) {
tot += 10;
helloed = true;
}
} else { // 'three' selected
if (helloed) {
tot -= 10;
helloed = false;
}
}
alert ("Tot is now " + tot);
});
});
If there were more options I'd go for a switch rather than an IF but that will do for this example
var extra = 0;
var tot = 0;
var initialTot = tot;
$(document).ready(function () {
var previous = 0;
var selected = 0;
$('#hello').change(function(){
if($('#one').is(':selected')) {
previous = selected;
selected = 1;
extra = 10;
}
else if($('#two').is(':selected')) {
previous = selected;
selected = 2;
extra = 10;
}
else if($('#three').is(':selected')) {
previous = selected;
selected = 3;
extra = 0;
}
tot = tot + extra;
if(previous === 1 && selected === 3) {
tot = initialTot;
}
});
});

Categories