I currently have a json object, that I loop through and output a list of links.
See fiddle:
http://jsfiddle.net/jasonday/hzZ8j/
each link is given an id based upon the storeID in the json.
What I want to do, is when a link is clicked it finds the id in the json, and then writes the sibling element "otherData" to #otherDataDiv
I've worked with traversing xml, but I'm not sure how to accomplish this with json.
Any help would be appreciated. thanks.
You just have to loop over, like this:
var target = "store17",
foundStore = {};
for(var k1 in object.state){ var state = object.state[k1];
for(var k2 in state.store){ var store = state[k2];
if (store.storeid == target){
foundStore = store;
break;
}
}
}
However, if you were using jQuery templates then you could just look for 'tmplItem' in the data array on the element.
Additionally, if you weren't building the HTML manually for this, I would suggest using jQuery data here for this project. It would solve your problem immensely.
to store: $(selector).data('unique name here',data);
to retrieve: var usefulname = $(selector).data('unique name here');
and then in your onclick for each link you could:
var otherData = $(this).data('unique name here').otherData;
Related
I have a problem in deleting data from a JSON object in javascript. I'm creating this JSON dynamically and the removal shall also take place dynamically. Below is my JSON and the situation I'm in to.
{brands:[51,2046,53,67,64]}
Now, I have to remove 53 from this which I am calculating using some elements property, but I'm not able to remove the data and unable to find the solution for this situation. Please help me folks, thank you.
Try to use Array.prototyp.splice,
var data = { brands:[51,2046,53,67,64] };
data.brands.splice(2,1);
Since you want to remove an element from an array inside of a simple object. And splice will return an array of removed elements.
If you do not know the position of the element going to be removed, then use .indexOf() to find the index of the dynamic element,
var elementTobeRemoved = 53;
var data = { brands:[51,2046,53,67,64] };
var target = data.brands;
target.splice(target.indexOf(elementTobeRemoved),1);
You could write the same thing as a function like below,
function removeItem(arr,element){
return arr.splice(arr.indexOf(element),1);
}
var data = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);
I am using JQuery to push data to Google Analytics when the Ajax code is fired.
I need some help in capturing checkboxes with the same ID name. Basically, it's overwriting previous values with the last checkbox selected. Can someone help modify my code below to see if the checkbox is checked, and instead of overwriting, appending the value?
for (i = 0; i < arr.length; i++) {
// If the decode flag is present, URL decode the set
var item = decode ? decodeURIComponent(arr[i]) : arr[i];
var pair = item.split(spl);
var key = trim_(pair[0]);
var value = trim_(pair[1]);
if (key && value) {
obj[key] = value;
}
}
This is what part of my URL parameters looks like:
/ordersearch?soldToList=1001014377%7C1000%7CSP&shipToList=1001000903%7C1000%7CSH&startDate=03%2F22%2F2016&endDate=03%2F23%2F2016&orderStatus=Complete&
_orderStatus=on& orderStatus=Cancelled&
_orderStatus=on& orderStatus=Open&
_orderStatus=on& productStatus=COMPLETE&
_productStatus=on& productStatus=Cancelled&
_productStatus=on& productStatus=OPEN&
_productStatus=on& ponumber=8940324& materialnumber=98574395& ordernumber=7493278
Thank you.
Firstly I don't see any jQuery and thus I'm advising you to stick with dom selectors for this.
You can use document.getElementById('checkboxId').checked, which returns a boolean value, to see if the checkbox with checkboxId is checked.
Appending elements can be achieved like so; div.innerHTML = div.innerHTML + 'Extra stuff';
Your question and code combination are vague at best so I would recommend getting your logic right and only concentrating on syntax once you know exactly how you're going to achieve your goal.
I've imported some XML files inside InDesign (you can see the structure in the picture below) and I've also created a script to get some statistics concerning this hierarchy.
For example, to count the "free" elements:
var items = app.activeDocument.xmlElements.everyItem();
var items1 = items.xmlElements.itemByName("cars");
var cars = items1.xmlElements.everyItem();
var c_free = cars.xmlElements.itemByName("free");
var cars_free = c_free.xmlElements.count().length;
I also have apartments in my structure that's why I'm using itemByName.
The code above returns the correct number of free cars in my structure.
What I'm trying to do - without any luck so far - is to target those free items (inside cars) and either delete all of them or a specific number.
My last attempt was using:
var del1 = myInputGroup2.add ("button", undefined, "Delete All");
del1.onClick = function () {
cars.xmlElements.everyItem().remove();
}
inside a dialog I've created.
Any suggestions will be appreciated cause I'm really stuck here.
I would probably use XPath for this. You can use evaluateXPathExpression to create an array of the elements you want to target. Assuming your root element is cars and it contains elements called cars1, and you want to delete all free elements within a cars1 element, you could do something like:
var myDoc = app.activeDocument;
//xmlElements[0] is your root element, in this case "cars". The xPath expression is evaluated from cars.
//evaluateXPathExpression returns an array of all of the free elements that are children of cars.
var myFrees = myDoc.xmlElements[0].evaluateXPathExpression("cars1/free");
for (var i = myFrees.length - 1; i>=0; i--){
myFrees[i].remove();
}
Tweaking this would require some knowledge of xPath, but it's not terribly hard to learn the basics and it does seem like the simplest approach.
I think your main problem was that XMLElements hasn't a itemByName method. You can only reference XMLElements through their indeces or ids.
Secondly you assume that you got xmlElements from XPath expression but it's likely that you got nothing as your xpath seems uncorrect.
var myFrees = myDoc.xmlElements[0].evaluateXPathExpression("./cars1/free");
var n = myFrees.length;
if ( !n ) {
alert("Aucun élément trouvé");
}
else {
while (n--) myFrees[n].remove();
}
You need to start your expression by setting the origin of your xpath. Here a dot "./" is used to tell you want to look for cars1/free xml elements at the "root" of the xmlelement. Using "//" on the contrary would have returned any cars/free items unregardingly of their locations.
When making a JavaScript script to iterate through a set of elements with the same class name, you can alter each of their properties individually.
How does the script know which element to edit if they don't have unique IDs? If they do in fact have unique ID's, how do you retrieve them? Using alert(); to display what is held in the node array from a simple document.getElementsByClassName(''); seems to display the type of element.
Could I actually store these results in an array for later use?
If on the documents load, I fetch an array of elements with a certain class name:
<script>
var buttonArray = document.getElementsByClassName('button');
</script>
Then iterate through this, and add the result at 'r' position to an object:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
}
</script>
Would I be able to find the array for each individual element with classname 'button' like so:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
function changeCol(buttonID)
{
var red = buttonObject[buttonID][0];
var green = buttonObject[buttonID][1];
var green = buttonObject[buttonID][2];
buttonID.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
buttonArray[r].onclick = function(){ changeCol(this); };
}
</script>
I thought the this part of onclick = function(){ changeCol(this); }; would hold the same unique ID as I stored in the buttonObject object, as the variable name that held the array?
Should this work? I can't seem to get it to on my web page, so instead, I used the buttons innerHTML in the buttonObject as the variable name that held the array for that object. The problem with that, is that I will probably need two or more buttons to have the same innerHTML.
Here's the webpage as it currently is:
http://www.shadespeed.com
I need to re-make the script to allow buttons to have the same name.
Any tips / advice would be greatly appreciated.
Many thanks!
- Dan. :)
Let's say I have a deck of cards spread out on my desk, face up. I want to flip over all the red ones. I might do this:
desk.getCardsByColour("red").forEach(flipit);
// note, obviously not real JavaScript for a not real situation :p
So I scan through my cards, finding all the red ones. Then I flip them over. What you're asking is basically "how do I know which cards to flip over if they don't have unique IDs?" Well, do I need an ID to iterate through a collection of objects, in this case a set of cards? Of course not.
(Note that while cards in a deck do have a unique property in their content, let's just assume that's the element's content and not an id attribute, kay?)
Now, here's how I'd do what you're doing:
for( r=0; r<buttonArray.length; r++) {
buttonArray[r].buttonObject = [r*5,r*5,r*5];
buttonArray[r].onclick = changeCol;
}
function changeCol(button) {
var red = button.buttonObject[0];
var green = button.buttonObject[1];
var blue = button.buttonObject[2];
button.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}
Say I have variables that I acquire in one html page, such as a UserName or a url or something. And in another html page I have input boxes for these variables and I want to autocomplete them by sending the data from the first html page to the input boxes in the second one. Can anyone indicate to me how I can achieve this?
Use JavaScript to create the equivalent collection for use by other JS code:
Code:
<script type="text/javascript">
var querystring = [ ];
var qs = location.search;
if ( qs.length > 1 )
{
qs = qs.substring(1); // skip past the ?
var pairs = qs.split( /\&/g ); // get all the name=value pairst
for ( var p = 0; p < pairs.length )
{
var pair = pairs[p];
querystring[ pair[0] ] = unescape( pair[1].replace(/\+/g," ");
}
}
</script>
Then, anyplace in your page where in ASP code you might use
Code:
var foo = Request.QueryString("foo");
you instead simply do
Code:
var foo = querystring["foo"];
CAUTION: "foo" will be case sensitive, unlike in ASP. If you wish, you could replace
Code:
querystring[ pair[0] ] = unescape( pair[1].replace(/\+/g," ");
with
querystring[ pair[0].toLowerCase() ] = unescape( pair[1].replace(/\+/g," ");
and then always use lower case names ("foo" in place of "Foo" or "FOO") when finding values.
Untested, though I have used this same code before. If there's a goof, it's just a typo.
You can use JQuery for that. Assuming you are not using any server side code.
Pass the value as a param to the next page.
Like myurl?param=xyz
Then you can get the value in the next page like this,
See this answer and sourcecode
var xyz = jQuery.url.param("param_in_url");
For this you can use php session .store that variable in session and get them in any page.or if you are calling that page from the page where u have values say username call like
next page
You should use $_SESSION variable in php. OR you can use sessionStorage of javascript.