I'm assigning values to array in forloop But it gives an error that array variable is undefine. following is my code.
$(document).ready(function(){
$("#SubmitBtn").live('click',function(){
var cnt = $("#TotalCnt").val();
var data = [];
for(var i=1; i<=cnt; i++)
{
var fname = $('#fname_'+i).val();
var lname = $('#lname_'+i).val();
var address = $('#address_'+i).val();
data[i]["fname"] = fname;
data[i]["lname"] = lname;
data[i]["address"] = address;
}
});
});
when I'm assigning value to array it gives error "data[i] is undefined"
Try to create an empty object first, because initially data[i] is undefined. And undefined does not contains any property under it.
$(document).ready(function(){
$("#SubmitBtn").live('click',function(){
var cnt = $("#TotalCnt").val();
var data = [];
for(var i=1; i<=cnt; i++)
{
var fname = $('#fname_'+i).val();
var lname = $('#lname_'+i).val();
var address = $('#address_'+i).val();
data[i] = {};
data[i]["fname"] = fname;
data[i]["lname"] = lname;
data[i]["address"] = address;
}
});
});
Related
I want my array to be updated as soon as I run the replace function. What actually happens is that all the elements of my array get deleted here is the code:
var Person = [];
var editPersonId = 0;
var Details = [];
function AddPerson() {
this.Details[0] = document.getElementById("fname").value;
this.Details[1] = document.getElementById("lname").value;
this.Details[2] = document.getElementById("age").value;
this.Details[3] = document.getElementById("mobil").value;
this.Details[4] = document.getElementById("adress").value;
Person.push(this.Details);
}
function Clear(){
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("age").value ="";
document.getElementById("mobil").value = "";
document.getElementById("adress").value = "";
}
function ShowContacts(){
var testIt= document.getElementById("search").value;
var i=0, k=0, indx=[], msg;
for ( i=0; i < Person.length; i++)
{
for ( k=0; k<=4; k++)
{
if (Person[i][k] === testIt)
{
document.getElementById("newFname").value = Person[i][0];
document.getElementById("newLname").value = Person[i][1];
document.getElementById("newAge").value = Person[i][2];
document.getElementById("newMobil").value = Person[i][3];
document.getElementById("newAdress").value = Person[i][4];
console.log(1);
editPersonId = i;
break;
}
}
}
}
function Replace(){
Person[editPersonId][0] = document.getElementById("newFname").value;
Person[editPersonId][1] = document.getElementById("newLname").value;
Person[editPersonId][2] = document.getElementById("newAge").value;
Person[editPersonId][3] = document.getElementById("newMobil").value;
Person[editPersonId][4] = document.getElementById("newAdress").value;
}
function Run(){
this.AddPerson();
this.Clear();
}
You override the contents of your Person insde of replace().
Person[editPersonId][0] = ...
While editPersonId is 0, means that the item you inserted in AddPerson will be overriden. And before replace(), you run clear(), which empties your inputs. So the elements don't get 'deleted', you replace them with an empty string.
You might wanna look into this article
So right now this is my current code and I'm trying to figure out a way to loop through the variables I've already declared (Assuming variables 1-9 already have values). I just wanted to know whether this was possible at all?
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
Output I want if we printed out the looped code:
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
var obj = {'briefs' : brief};
if(localStorage.getItem('briefs') != null) {
var tmp1 = JSON.parse(localStorage.getItem('briefs'));
for(var i = 0;i<tmp.length;i++) {
briefs.push(tmp[i]);
}
}
briefs.push(obj);
localStorage.setItem("briefs", JSON.stringify(briefs));
var obj = {'hovers' : hover};
if(localStorage.getItem('hovers') != null) {
var tmp2 = JSON.parse(localStorage.getItem('hovers'));
for(var i = 0;i<tmp.length;i++) {
hovers.push(tmp[i]);
}
}
hovers.push(obj);
localStorage.setItem("hovers", JSON.stringify(hovers));
...etc
If the code is running in a browser, then you can do something like:
for(key in window) { console.log(window[key]) } // print all variables
The variables are associated to the global namespace. That is to say the upmost "this" reference or the window object.
You're almost there with the code you have. If you look at your "desired output" examples, you'll see that the only thing that really differs between each element of your "unrolled loop" is the key for local storage ('titles', 'briefs', 'hovers').
With that in mind, you could use an Object to map the keys to the variables you have at the top level. So this:
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...
Becomes (UPDATE: with the initializer values preserved):
var key_to_collection = {
'titles': [title],
'briefs': [brief],
'hovers': [hovers],
'whatTitles': [whatTitles],
'whatDescs': [whatDescs],
}
Then, you loop over the values of this object:
Object.keys(key_to_collection).forEach(function(key) {
var obj = {};
collection = key_to_collection[key];
obj[key] = collection;
if(localStorage.getItem(key) != null) {
var tmp = JSON.parse(localStorage.getItem(key));
for(var i = 0;i<tmp.length;i++) {
collection.push(tmp[i]);
}
}
collection.push(obj);
localStorage.setItem(key, JSON.stringify(collection));
});
If your variable name is title for example, then you can access it using window['title']. This means that if you define an array of your global variable names:
const varNames = ['title', 'brief', 'hover', ...]
Then you can do a loop like the following
for(const name of varNames) {
const value = window[name]
// do whatever you want using the variable name and value
}
I hope this solves your issue :)
I need to get the var i need to be appended to the left side of the object declaration. I am unable to find how to append that. Kindly help me to get rid of the Error.
If any Other Solution available also i will follow it up.
I have tried the below code
<script type="text/javascript">
var text_count=5;
var textbox = new Object();
for (var i = 1; i<=text_count; i++)
{
textbox.meta_key_textbox='Meta Key';
textbox.meta_key_value_textbox='Meta Value';
};
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
</script>
I get the last Value alone in this. But I am unable to get all the Values that are in the Loop.
But when i do this method manually it works. Kindly Clarify on this.
<script type="text/javascript">
var text_count=5;
var textbox = new Object();
textbox.meta_key_textbox='Meta Key';
textbox.meta_key_value_textbox='Meta Value';
textbox.meta_key_textbox1='Meta Key One';
textbox.meta_key_value_textbox1='Meta Value One';
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
</script>
you assign the same value in each iteration, use the below code:
<script type="text/javascript">
var text_count=5;
var textbox = new Object();
for (var i = 1; i<=text_count; i++)
{
var text = "meta_key_textbox" + i;
var value_text = "meta_key_value_textbox" + i;
textbox.text='Meta Key';
textbox.value_text='Meta Value';
};
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
</script>
var text_count=5;
var textbox = new Object();
var arrKey = [];
var arrValue = [];
var values = ["one", "two", "three", "four"];
for (var i = 1; i<text_count; i++) {
arrKey.push({key: "textbox.meta_key_textbox" + i, value: values[i-1]});
arrValue.push({key: "textbox.meta_key_value_textbox" + i, value: values[i -1]});
}
textbox.meta_key_textbox='Meta Key';
textbox.meta_key_value_textbox='Meta Value';
for (var i = 1; i<text_count; i++)
{
textbox[arrKey[i-1].key]= 'Meta Key ' + arrKey[i-1].value;
textbox[arrValue[i-1].key]= 'Meta Value ' + arrValue[i-1].value;
};
var textbox_string = JSON.stringify(textbox);
alert(textbox_string);
I'm doing a cart and I want to increment the qty if the item_id exising in localStorage.
<button data-item_id="1" data-item_name="cake" data-item_price="2 dollar">Add to cart</button>
Not sure why my below code doesn't work, it added a new object instead of increment the qty value.
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
if(arr.length === 0){ // first time insert
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
}else{
$(arr,function(i){
//doesn't work here
obj.item_qty[i] = parseInt(this.qty) + 1;
});
}
arr.push(obj);
localStorage.setItem('cart',JSON.stringify(arr));
});
});
debug for few hours couldn't solved.
Use {} instead of [] making the arr contain one object per item_id and each object will get 1 added to the qty each time it is called. There is no remove in this code
$(function(){
$('button').on("click",function(e){
var item_id = $(this).data("item_id");
var item_name = $(this).data("item_name");
var item_price = $(this).data("item_price");
var cart = JSON.parse(localStorage.getItem('cart')) || {};
var currentObj = cart[item_id];
if(currentObj){
currentObj.qty++; // increase the qty by one
}
else { // item_id had not been stored before, create it
cart[item_id]= {
"item_name" :item_name,
"item_price":item_price,
"item_qty" :1
}
}
localStorage.setItem('cart',JSON.stringify(cart));
});
});
Then you have to do like this:
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
detectchange = 'no';
$.each(arr,function(i){
if(this.item_id == obj.item_id){
this.item_qty = parseInt(this.item_qty) + 1; detectchange = 'yes'; }
});
if(detectchange =='no'){
arr.push(obj); }
localStorage.setItem('cart',JSON.stringify(arr));
});
});
Please check the script below.
Dynamic form, so the script also dynamic, I have to calculate when the form data changes. during this i am getting some problem.
am getting the value from the variable Final_price1, Final_price2 .....,Final_price7, Final_price8 and then am calculating the total of those.
During this calculation, am concatenating the following concat("Final_price",i); to get the values of the above. This concatenated correctly, but the above variables values are not coming. I dont know why the values are not getting there. So check the script and update me.
function assign_body()
{
var a_7= document.getElementById("option[280]").value;
var spl_7 = a_7.split("_");
//alert(spl);
var cr_7 = spl_7[1];
var operator3_7 = cr_7.split("[");
var symbol7 = operator3_7[0];
var dtt_7 = operator3_7[1];
var myarr_7 = dtt_7.split("$");
var symbol_st_7 = myarr_7[1];
//alert(symbol_st);
//alert(symbol_s);
//var symbol_a = symbol_s.split("(");
//var symbol = symbol_a[1];
//alert(symbol);
var split_value_7 = myarr_7[1];
//alert(split_value);
var final_value_7 =symbol_st_7.split(".");
var Final_price7 =final_value_7[0];
var a_8= document.getElementById("option[281]").value;
var spl_8 = a_8.split("_");
//alert(spl);
var cr_8 = spl_8[1];
var operator3_8 = cr_8.split("[");
var symbol8 = operator3_8[0];
var dtt_8 = operator3_8[1];
var myarr_8 = dtt_8.split("$");
var symbol_st_8 = myarr_8[1];
//alert(symbol_st);
//alert(symbol_s);
//var symbol_a = symbol_s.split("(");
//var symbol = symbol_a[1];
//alert(symbol);
var split_value_8 = myarr_8[1];
//alert(split_value);
var final_value_8 =symbol_st_8.split(".");
var Final_price8 =final_value_8[0];
var j=8;
var total_amount=0;
for(var i=1; i<=j; i++)
{
final_prices=concat("Final_price",i);
alert(final_prices);
symbol_prices=concat("symbol",i);
alert(symbol_prices);
if(isNumber(final_prices)){
alert("number");
/*if(symbol_prices =='+') {
alert("plus");
var total_amount+=parseInt(original_prices)+parseInt(final_prices);
calculated_price_element.innerHTML=total_amount;
alert(total_amount);
} else if(symbol_prices =='-') {
alert("minus");
var total_amount+=parseInt(original_prices)-parseInt(final_prices);
calculated_price_element.innerHTML=total_amount;
alert(total_amount);
}*/
//alert('test');
}
}
}