code not executing after for loop -- javascript - 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)
}

Related

jQuery: Reset classes once the field is empty

NOTE:
The following solution comes from THIS TOPIC, please see that first.
I have 11 inputs:
<input type="text" class="[something]-input inputs">
(Where [something] is a name, different for every input)
$(document).on("change", ".inputs", function(){
var thisclass = $(this).attr('class').split("-")[0];
if($(this).val() == ''){
//
}
highlightInputNumbers(thisclass, 0);
});
The highlightInputNumbers function goes this way:
function highlightInputNumbers(classe, stepcount, empty){
var all= $("td[class*="+classe+"]");
var index = all.length-1;
var concat_steps = $(all[index]).html().split('.')
//var due_serie = $(all[index]).html().split('.')
var due_serie = $('.'+classe+'-input').val().split('.')
for (var i = index; i >= (index-stepcount)+2; i--) {
due_serie = due_serie.concat($(all[i-1]).html().split('.'));
};
//Rimuovo i doppioni
var serieCompleta = [];
$.each(due_serie, function(i, el){
if($.inArray(el, serieCompleta) === -1) serieCompleta.push(el);
});
//Ottengo dati
for(var s = 0; s < index-(stepcount-1); s++){
var bar = $(all[s]);
var barnum = bar.html().split('.');
bar.html('');
var found = 0;
for(i = 0; i<= barnum.length-1; i++){
for(n = 0; n<= serieCompleta.length-1; n++){
if(i != 4){ var punto = '.' }else{ var punto = ''}
/* Problem here:*/
if(barnum[i] == serieCompleta[n]){
bar.append('<span class="highlight">'+barnum[i]+'</span><span class="fade">'+punto+'</span>');
found = barnum[i];
}
}
if(barnum[i] != found){
bar.append('<span class="fade">'+barnum[i]+punto+'</span>');
}
}
}
}
Where I commented /*Problem here*/ is where I highlight the numbers in the column (that I have inserted), but if I remove the numbers in the input they stay highlighted... If I change them it keeps the old ones..
As you can see here: https://dl.dropboxusercontent.com/u/2276958/Cols_and_rows.mov
Small addition in your code.
Let me try to explain what was happening in your code.
At first try:
your code gets the input values (eg. 89.30.20)
Loop through all available values in the table
Split each value by '.'
Then loop through these spitted values to check for match and highlight
Replace the matched number to highlighted span (i.e 20 to 20 and unmatched number to faded span.
This all works for first time. But at the second try, your code breaks from step 3. As in step 3 code tries to split values by '.' but the values were replaced with Span values in your first try. So now to rectify this issue I added small check and 2-3 lines of extra code to extract actual values from Span values.
That extra code is:
// Check if values bar already contains Span tags (means already processed in first try
var hasSpans = bar.find('span').length>0;
if(hasSpans)
{
//If yes then extract the actual values from these span tags without '.' (This will work for all tries after FIRST)
barnum=bar.find('span').map(
function() {
if($(this).html() != '.')
return $(this).html().replace('.','');
}).get();
}
// else normal case, split the values by '.' (This will for very FIRST try)
else barnum = bar.html().split('.');
$(document).on("change", ".inputs", function(){
var thisclass = $(this).attr('class').split("-")[0];
if($(this).val() == ''){
//
}
highlightInputNumbers(thisclass, 0);
});
function highlightInputNumbers(classe, stepcount, empty){
var all= $("td[class*="+classe+"]");
var index = all.length-1;
var concat_steps = $(all[index]).html().split('.')
//var due_serie = $(all[index]).html().split('.')
var due_serie = $('.'+classe+'-input').val().split('.')
for (var i = index; i >= (index-stepcount)+2; i--) {
due_serie = due_serie.concat($(all[i-1]).html().split('.'));
};
//Rimuovo i doppioni
var serieCompleta = [];
$.each(due_serie, function(i, el){
if($.inArray(el, serieCompleta) === -1) serieCompleta.push(el);
});
//Ottengo dati
for(var s = 0; s < index-(stepcount-1); s++){
var bar = $(all[s]);
var barnum;
var hasSpans = bar.find('span').length>0;
if(hasSpans)
{
barnum=bar.find('span').map(
function() {
if($(this).html() != '.')
return $(this).html().replace('.','');
}).get();
}
else barnum = bar.html().split('.');
bar.html('');
var found = 0;
for(i = 0; i<= barnum.length-1; i++){
for(n = 0; n<= serieCompleta.length-1; n++){
if(i != 4){ var punto = '.' }else{ var punto = ''}
/* Problem here:*/
if(barnum[i] == serieCompleta[n]){
bar.append('<span class="highlight">'+barnum[i]+'</span><span class="fade">'+punto+'</span>');
found = barnum[i];
}
}
if(barnum[i] != found){
bar.append('<span class="fade">'+barnum[i]+punto+'</span>');
}
}
}
}
span.highlight{
color:green;
font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>02/05/2015</td><td class="bari1">89.10.86.30.65</td></tr>
<tr><td>30/04/2015</td><td class="bari2">96.11.73.36.13</td></tr>
<tr><td>02/05/2015</td><td class="bari3">78.34.50.72.11</td></tr>
<tr><td>30/04/2015</td><td class="bari4">34.78.69.60.22</td></tr>
<tr><td>02/05/2015</td><td class="bari5">12.29.30.69.33</td></tr>
<tr><td>30/04/2015</td><td class="bari6">59.10.20.96.44</td></tr>
<tr><td colspan="2"><input type="text" class="bari-input inputs"></td></tr>
</table>
<table>
<tr><td>02/05/2015</td><td class="vari1">89.10.86.30.65</td></tr>
<tr><td>30/04/2015</td><td class="vari2">96.11.73.36.13</td></tr>
<tr><td>02/05/2015</td><td class="vari3">78.34.50.72.11</td></tr>
<tr><td>30/04/2015</td><td class="vari4">34.78.69.60.22</td></tr>
<tr><td>02/05/2015</td><td class="vari5">12.29.30.69.33</td></tr>
<tr><td>30/04/2015</td><td class="vari6">59.10.20.96.44</td></tr>
<tr><td colspan="2"><input type="text" class="vari-input inputs"></td></tr>
</table>

Failed to sum variable in 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.

Value of Radio buttons using Loop and add HTML text to it

Please see the fiddle link at the bottom. I have two questions:
How to add HTML text to these radio buttons. I have to give them $ and % value (for the user).
Find the values of every radio button selected. For example, the user added 10 rows (each having 2 radio buttons). I have iterated a loop to find the input type and see if the button is checked and then find its value.
NOT WORKING, guide me what wrong am I doing.
FIDDLE
var i=0;
window.myAdd = function(){
var x = i;
var butts = document.createElement("INPUT");
butts.setAttribute("type", "radio");
butts.setAttribute("name", "currency"+x);
butts.setAttribute("value", "%");
butts.setAttribute("id", "radio"+i);
//var node = document.createTextNode("%");
//butts.appendChild(node);
i=i+1;
//console.log(butts);
var butts_1 = document.createElement("INPUT");
butts_1.setAttribute("type", "radio");
butts_1.setAttribute("name", "currency"+x);
butts_1.setAttribute("value", "$");
butts_1.setAttribute("id", "radio"+i);
i=i+1;
//console.log(butts_1);
var row = document.createElement("TR");
//document.getElementById('tab').appendChild(butts);
//document.getElementById('tab').appendChild(butts_1);
row.appendChild(butts);
row.appendChild(butts_1);
document.getElementById('tab').appendChild(row);
x=x+1;
}
window.myfunction = function(table){
//var x = String(document.getElementById('radioP').value);
//alert(x);
for(var i=0;i<table.elements.length;i++){
if(table.elements[i].type =='radio'){
if(table.elements[i].checked == true){
alert(table.elements[i].value);
}
}
}
}
I have corrected your script to work:
var i = 0;
window.myAdd = function() {
var x = i;
var butts = document.createElement("INPUT");
butts.setAttribute("type", "radio");
butts.setAttribute("name", "currency" + x);
butts.setAttribute("value", "%");
butts.setAttribute("id", "radio" + i);
//var node = document.createTextNode("%");
//butts.appendChild(node);
i = i + 1;
//console.log(butts);
var butts_1 = document.createElement("INPUT");
butts_1.setAttribute("type", "radio");
butts_1.setAttribute("name", "currency" + x);
butts_1.setAttribute("value", "$");
butts_1.setAttribute("id", "radio" + i);
i = i + 1;
//console.log(butts_1);
var row = document.createElement("TR");
//document.getElementById('tab').appendChild(butts);
//document.getElementById('tab').appendChild(butts_1);
row.appendChild(butts);
row.appendChild(butts_1);
document.getElementById('mytable').appendChild(row);
x = x + 1;
}
window.myfunction = function(table) {
//var x = String(document.getElementById('radioP').value);
//alert(x);
//debugger;
for (var i = 0; i < table.rows.length; i++) {
var row = table.rows[i];
for (var j = 0; j < row.childNodes.length; j++) {
if (row.childNodes[j].type == 'radio') {
if (row.childNodes[j].checked == true) {
alert(row.childNodes[j].value);
}
}
}
}
}
<button onclick='myAdd()'>Add Radio Buttons</button>
<table id="mytable" name="mytable"></table>
<button onclick='myfunction(document.getElementById("mytable"))'>GET VALUE</button>
1) You have to use <label> element, e.g.:
<input id="radio_1" type="radio" value="1" />
<label for="radio_1">$</label>
<input id="radio_2" type="radio" value="2" />
<label for="radio_2">%</label>
2) You have to iterate through them. Considering all of the radios are within some div with class "container", you'll need something like this:
document.getElementById('get_values').addEventListener('click', function() {
var radios = document.querySelectorAll('.container input[type="radio"]');
values = {};
for(i=0; i<radios.length; i++) {
var radio = radios[i];
var name = radio.getAttribute('name');
if(radio.checked) {
values[name] = radio.value;
} else {
values[name] = values[name] || null;
}
}
alert(JSON.stringify(values));
});
See this fiddle: http://jsfiddle.net/andunai/gx6quyo0/

Duplicate check in javascript before inserting a new record

I have a javascript which appends a string like 222222222222222 to another field (which will either be blank or already have numbers like 222222222222222 33333333333333) with a click of a button. Actually it's 15 digit IMEI of the phone. User has the option of submitting a single IMEI or bulk IMEI. When more then one IMEI is added to the bulk field by pressing the button from myVar1, the new IMEI gets inserted below the previous IMEI in the bulk field(myVar2).
Currently, I am using the below script to do this and it's working perfectly fine. The problem is that it doesn't check for duplicates before appending.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}
I have modified the script now as below (updated to include the first response, thanks to Brian) to check for duplicates, but it's not working. Request experts to have a look into it.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
var flag = 0;
var wordsarr = myVar2.split("\r\n");
for(var i = 0; i < wordsarr.length; i++)
{
if(wordsarr[i].value == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}}
Here is the html of the page:
<html>
<body>
<input id="myVar1_value" type="text" maxlength="15" name="myVar1_value">
<input id="IMEI_ADD" class="button_gray" type="button" onclick="append_myVar1_to_myVar2()" value="Add this IMEI to bulk entry" name="IMEI_ADD">
<p id="imei_bulk_field" class="form-row notes">
<textarea id="myVar2_value" class="input-text" rows="2" cols="5" placeholder="If you have more than one IMEI, insert them here by pressing the button above." name="myVar2_value"></textarea>
</p>
</body>
</html>
for(var i = 0; i < (myVar2.split("\r\n")).length; i++)
{
//here is wrong
if(myVar2[i].value == myVar1)
{
flag = 1;
}
You should change to
var wordsarr = myVar2.split("\n");
for(var i = 0; i < worsarr.length; i++)
{
if(wordsarr[i] == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
Store splitted chunks ,and iterate over them:
var chunkArray = myVar2.split("\r\n");
for(var i = 0; i !== chunkArray.length; i++){
if(chunkArray[i] == myVar1){
flag = 1;
break;
}
}
var myVar2 = document.getElementById('myVar2_value').value;
Later...
if(myVar2[i].value == myVar1)
It looks like you are adding .value when you don't need to. Try:
if(myVar2[i] == myVar1)
This could be of assistance
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
you could change the if with:
haystack[i].value == needle

How to manipulate form field values in javascript

I'm trying to get the value of a few checkboxes and enter them in a hidden form field.
My checkboxes look like this:
<form>
<input type="checkbox" name="chicken" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="meat" id="meat" value="meat"/>Meat
</form>
<form method="post" action="">
<input type="hidden" name="my-item-name" value="" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I only need to submit the hidden field data so I'd like the value of the hidden field change when the checkbox is ticked. So if the first checkbox is ticked I'd like the value of the hidden field to become chicken and if both of them are ticked the value should be chicken,meat.
I'm using the following javascript
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++)
{
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
but when I add the items, it adds both of them, it doesn't check which one's been checked, is there a way to fix that, so when the first item is checked it'll only add that item and if both of them are checked, it'll add 2 items separated by comma,
for(i = 0; i < checks.length; i++)
{
if (!checks[i].checked)
continue;
....
}
You need to give the checkboxes the same name to have them grouped:
<input type="checkbox" name="food[]" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="food[]" id="meat" value="meat"/>Meat
And in your JavaScript function:
function SetHiddenFieldValue() {
var checks = document.getElementsByName("food[]");
var hiddenFieldVal = "";
for (var i=0; i<checks.length; i++) {
if (checks[i].checked) {
if (hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
You forgot to test for checks[i].checked
function SetHiddenFieldValue() {
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++) {
if (checks[i].checked) {
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
Hi your best to put the values into an array, makes it easier to then create the comma separated value. Also makes it a lot easier if you add more options later.
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var foods = new Array();
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
foods[i] = checks[i].value;
}
}
document.getElementById('my-item-name').value = foods.join(",");
}

Categories