I have a ul-li block for image listing.On clicking on an corresponding images should delete and a value inside a <span>,which is sibling of image should be stored in a variable.Each time when I click,img should delete and each <span>'s value should be appended to jquery array variable.I did it,but when I alert the array variable it shows the single value of the current click only.ie not appending values generated through the previous click.
My JavaScript:
function delImg(newthis){
var Ids= [];
$(newthis).parent().hide();
var Id = $(newthis).siblings('.hidden').html();
Ids.push(Id);
alert(Ids);
return Ids;
}
The problem is alert(Ids) gives single variable instead of array.
Put the declaration of the array outside of the function (so you're not resetting it every time):
var ids = []
function delImg(newThis){
$(newThis).parent().hide();
var id = $(newThis).siblings('.hidden').html();
ids.push(id);
return ids;
}
Also, naming conventions suggest that you should camelCase your variable names, so I have done that.
You need to declare your array outside the function
var Ids = [];
function delImg(newthis){
// ...
}
Related
This is a pretty simple (Well simple to the point that I am not sure how to make it work) little issue.
I have an object that contains an array of data that I need to utilize inside my each statement and to my surprise... I can't just directly reference it. I have read that specifying an
var something = this;
before the if would allow it to be called and that was no good.
Current Code:
var exsistingshifts = response.data.ExsistingEvents;
var eventdata = this;
$(".shiftdiv").each(function (index) {
var currdiv = $(this).children();
var info = eventdata.exsistingshifts;
})
Expected result info = my array of delicious data
Current result info = undefined
For people wanting Context, shiftdiv class divs are built dynamically by a query and have a data value in their ID that link them to a certain set of events. The array contains ALL events and their data keys, so for each shift div I need to capture the ID which is easy enough, compare it to the array and pluck out the values I need from that array to mess with that particular div.
As for page context of the $(this) this is being called inside of an onclick function. The onclick function sets response.data.ExsistingEvents
If I am not wrong , you are using this code inside ajax Success function (I can see response object so.)
Now if you are doing so, you are doing a mistake by assigning this object to eventdata.
line var eventdata = this will store $.ajax object in eventdata,
and this object (means that your ajax object) doesn't contain any value for key exsistingshifts , So eventdata.exsistingshifts is undefined.
change your code to following should work
$(".shiftdiv").each(function (index) {
var currdiv = $(this).children();
var info = response.data.ExsistingEvents[index].exsistingshifts;
});
I'm trying to store multiple items based on this function:
onclick="s(iId)"
This is the function that I'm using:
function s(i_id) {
var items = [];
items.push(i_id);
localStorage.setItem("i", JSON.stringify(i));
}
The problem is that it is only storing one id when the button is clicked and refreshed every time is clicked. How can I make it store multiple ids?
The problem is, you're creating a new array, pushing a single id in it, and then saving it every time the function is called. Two things you could do is move the items array outside of the function, and simply push to it, before saving them. The second option is, getting the already stored value, parsing it with JSON.parse and pushing a new item in it, before saving it again.
I suggest going with option 1, even if it creates a global variable. It's much faster.
var items = [];
function store(item_id) {
items.push(item_id);
localStorage.setItem("item", JSON.stringify(items));
}
You have to call the onclick like this:
onclick="store([itemId1, itemId2, itemId3])"
and the function:
function store(item_ids) {
var items = [];
for(var i = 0; i < item_ids.length; i++) {
items.push(item_ids[i]);
}
localStorage.setItem("item", JSON.stringify(items));
}
Considering if you want to add new array to storage on every click...
I have a problem while adding values to a JavaScript object: the value to add is a key,value pair. Here is sample:
//JavaScript object
var cart=new Object();
function add()
{
var rating="1"
var category="somecat";
var user="user1";
if(cart[user]==null)
cart[user]={category:rating};
else
cart[user][category]=rating;
}
What I was expecting is that if user exists in cart object then value for his particular should get replaced, and if user doesn't exist then new user and category should be added.
The code is working fine when user already exists. Problem is, when I am adding a new element with cart[user]={category:rating} then its adding the variable name as key i.e. category , not the value inside it ("somecat").
Is there any way to do this using json, jquery or javascript itself?
Is there any way to assign value inside the variable?
There is no way to use a variable to define a property name inside object literal notation. It accepts identifiers or strings, but both identify property names, not variables.
You have to create the object then add the property:
if(!cart[user]) {
cart[user] = {};
}
cart[user][category] = rating;
You will need to replace
{category:rating}
with
var obj = {};
obj[category] = rating;
When creating an object literal the key must be a string, so in your code it will be "category". If instead you do:
var rating="1"
var category="somecat";
var user="user1";
if( !cart[user] ) {
cart[user]={};
}
cart[user][category]=rating;
That will initialise a non existing user to an empty object and then add the category.
I am refactoring some code where I grab the values inputted into textboxes and use said values for calculations. The problem is rather than using document.getElementByID multiple times I want to loop through each textbox on the page and assigning each value to this object which I will pass to my calculation functions. I would also like to set the property names of this object by looking at the input textbox IDs and using the ID strings for the object property names.
See code below:
$(document).ready(function() {
var calcObj = new Object();
$("input[id^='txt']").each(function(i, val) {
calcObj[i] = this.value;
});
$.each(calcObj, function(i, val) {
// alert(val);
});
});
As you can see when document is ready, object is created. There is a jquery .each loop to go through every input with id that contains txt. I am assigning this.value to object where index is i.
So I want to some how name the properties of this object and assign value so I can reference object property name elsewhere in the code where I pass this object to another function.
Thanks.
As far as I understand, you want:
calcObj[this.id] = this.value;
I don't exactly get what you're asking for, because it seems like you're already doing what I think you're asking.
Right now, you're doing:
calcObj[i] = this.value;
That's no different from assigning it like:
calcObj['foo'] = this.value;
// and later we can access that via
alert( calcObj.foo ); // or calcObj['foo']
You can be dynamic with that as well, like:
calcObj[this.id] = this.value;
Outside of a for I declare a variable using var list;. I use this variable inside of my for loop like so:
// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());
item is a cloned jquery object build from a $('list_template').clone(); call (list_template is a div with <li> elements inside). What I am doing is creating a list, which I will then appendTo() where I need it.
Right now this code works fine, but it doesn't seem right to me. Unfortunatly, I cannot seem to figure out how to correctly declare the list variable to be an empty Jquery object. I have tried both:
var list = $([]);
var list = $('');
Both of those cause the append to not work correctly (or as expected) with list.html() being null. Is there a way to initialize my variable to an empty jquery object, so all I have to do is list.append(item.contents()); without the if/else statements?
Edit: Ok to lessen confusion here is the whole javascript function that currently works fine:
var list;
// Loop through all of the objects
var objects = data.objects;
for (x = 0; x < objects.length; x++) {
// Clone the object list item template
var item = $("#object_item_list_template").clone();
// Setup the click action and inner text for the link tag in the template
item.find('a').bind('click', { val: objects[x].Id }, function (e) { ShowObjectDetails(e.data.val); })
.html(objects[x].Name);
// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());
}
// set the list of the topics to the topic list
$("#object_list").empty();
$('<ul>').appendTo("#object_list").append(list.contents());
The object list template is as follows:
<div id="object_item_list_template" style="display:none">
<li class="object_item"></li>
</div>
This all works correctly by cloning the list item, setting up the click action, and adding it to the list on the display.
I am trying to get rid of the if/else statement. I can't just do list.append() because if list is undefined (or not a Jquery object), it throws an exception.
An empty jQuery object is declared as:
$();
Docs for jQuery object creation: http://api.jquery.com/jQuery/
EDIT:
It sounds like you're trying to eliminate the if/else statement by extending list whether or not it has any content.
Is that right?
If so, try something like this:
list = $( list.get().concat(item.get()) );
or
$.extend(list, item);
(Assumes list is starting out as an empty jQuery object.)
EDIT:
Since you're creating elements in a loop, you can always push() then into a jQuery object.
Try something like this:
var list = $(); // Start off with empty jQuery object.
...
list.push(item.find('li').get(0)); // A jQuery object is an Array. You can `push()` new items (DOM elements) in.
...
('<ul>').appendTo("#object_list").append(list);
(I edited from the original to only push the DOM element into the jQuery object.)
Should add the current item in the loop to your list.
You could eliminate the find() calls in your code if you just cloned the children of #object_item_list_template:
$('li', '#object_item_list_template').clone(); // Clone the `li` without the `div`.
Now you have a clone of the li itself. No need to do a find.