Dynamic values and parameters in url or cookies query, how to? - javascript

I am trying to figure out how to add, change or remove values and parameters in specific parts of query.
I have a cookie $.cookie('productsInBasket', '&i=' + productId + '&q=' + productQty + '&c=' + productSize); where productId, productQty and productSize should be added and removed dynamically.
So it can be &i=2441&q=1&c=2521 or &i=2441,2442,2443&q=1&c=2521 or &i=2441,2442,2443&q=1,3,14&c=2521,2522,2523 or... well you've got the point.
What would be the way to achieve that?
Thank you!
P.S. That should be jQuery or Javascript solution.

I will not say that my way is right, but this is mine own workaround.
I simple create 4 cookies, 3 for &i=, &q=, &c= and 4th for merging them together.
The code for that is:
$.cookie('productsInBasketItems', productId);
$.cookie('productsInBasketQty', productQty);
$.cookie('productsInBasketColors', productSize);
$.cookie('productsInBasketMerge', '&i=' + $.cookie('productsInBasketItems') + '&q=' + $.cookie('productsInBasketQty') + '&c=' + $.cookie('productsInBasketColors'));
That way I can manipulate each of the value and its options across my pages.
Of course I think there is more elegant ways as .split() inside .split(), but my knowledge does not allow me to spend much time on that.
Hope that will help anyone.

Let's say you have your values in arrays,
​var i = [1,2,3];
var q = [5,10,15];
var c = [100,200,300];
A simple function can build your cookie from the arrays:
function createCookie(i,q,c){
return ("&i="+i.join(',')+"&q="+q.join(',')+"&c="+c.join(','));
}
DEMO

Related

R string replacing part of javascript

I'm sure this is a noob question but I couldn't figure out how you would insert a R string object inside a javascript. For example,
trackname <- "audiotrack1"
into
tag$script(var url = 'audioResources/' + trackname + '.wav')
Where I would want to replace the "trackname" with "audiotrack1". I'm sure paste0 isn't the best way to do this. What is the standard way to go about doing this?
Many thanks.
This is not correct. You can do:
tags$script(HTML(sprintf("var url = 'audioResources/%s.wav'", trackname)))
An option with glue
library(glue)
tags$script(HTML(glue::glue("var url = 'audioResources/{trackname}.wav'")))

Don't seem to get $().attr('src') to do its job

First post here, so please be gentle ;-)
I've been learning coding over the last couple of weeks by making a dummy page, and been implementing what i learn on it incrementaly as i progress, hence it's a mixed bag where the functionality/code is according to when i wrote it, based on pure html/CSS, inline javascript, external javascript, and finally jquery.
So i mostly wrapped it up and i'm now cleaning up the mess, and part of my mission is to cull functions and lines of codes, and in one of them i'm kind of stuck.
The before was 30 buttons calling to 30 different functions onclick like so:
function cell3() {
document.getElementById('base3').src='images/1/3/' + x + '.png';
document.getElementById('base3b').src='images/1/3/' + x + '.png';
document.getElementById('v2base3').src='images/2/3/' + x + '.png';
document.getElementById('v2base3b').src='images/2/3/' + x + '.png';
document.getElementById('cell3').style.backgroundColor= x ;
}
Where a global variable (x) defines the folder paths for images to replace the images within some divs when clicking the button (cell3). It also changes the bGroung color of it. Sorry if the naming is a bit confusing...
So i'm removing all 30 functions and the 30 onclick calls with this bit of jquery:
$('button').click(function(){
var eyeD = $(this).attr("id");
var newURLa = 'images/1/' + eyeD + '/' + x + '.png';
var newURLb = 'images/2/' + eyeD + '/' + x + '.png';
$('base' + eyeD).attr('src', newURLa);
$('base' + eyeD + 'b').attr('src', newURLa);
$('v2base' + eyeD).attr('src', newURLb);
$('v2base' + eyeD + 'b').attr('src', newURLb);
$(this).css( "background-color", x );
document.getElementsByid('check').innerhtml = eyeD;
});
For that to 'work' i changed the button's names from 'cell1', 'cell2, etc. to '1', '2', etc.
Now the thing is, when clicking on the buttons the var 'eyeD' takes the value from the button ok. ('1', '2', etc.). The elements ID's are formed correctly ('base1', 'base2'... 'base1b', base2b'...), and the URL's are formed correctly. (The last line in the code is a p element that displays values so i could try to troubleshoot it) The background color also changes as expected. But the images do not get replaced.
Tried adding commas to the resulting URL's in case it was a syntax issue, but nothing happens. i even went freestyle and tried it with the =url() on it, different commas in different places, etc. So basically scraping the barrel here. Also wrote a url without variables to see if that would work, but still nothing. Also getting no errors when looking at the console.
It's probably a basic 'DOH!' thing, but right now i have a mental block...
Also, is there a way to keep the original naming and just retrieve the numbering part of the ID's? Thought about using the [4] identifier to get the 5th digit, but that won't work when running double digit numbers. (10, 11, etc)
Thanks!
Your jQuery lines accessing the elements are missing the # sign.
Change these...
$('base' + eyeD).attr('src', newURLa);
To this...
$('#base' + eyeD).attr('src', newURLa);
Also, your last line where you use plain JS, can be done in jQuery as well with less code.
document.getElementsByid('check').innerhtml = eyeD;
To...
$("#check").html(eyeD);
However, you should always use distinct ID's for elements. If you need to use multiple elements at the same time, use a class instead.
$(".check").html(eyeD);
You're grabbing an element incorrectly.
Either Grab an element by it's class name like so:
$('.v2base' + eyeD + 'b').attr('src', newURLb);
Or by its ID:
$('#v2base' + eyeD + 'b').attr('src', newURLb);
Problem solved!! It was indeed calling the id with the hash, but also it has to be called with double quotation marks. Single inverted commas won't work.
So the working format is
$("#v2base" + eyeD + "b")
but it won't work like so
$('#v2base' + eyeD + 'b')
Thanks everyone, it's been emotional

How to retrieve integer value from url of "example_3.html"

Title says it all. Basically I am looking to retrieve the end of the url using jQuery to add one to the selection and go to that page. I had some help from someone else on her but I want to understand how it is working/ why it's not working:
var urlFrags = window.location.href.replace(".html", "").split("_"),
curPage = parseInt(urlFrags[urlFrags.length]),
nextPage = "example_" + (curPage + 1) + ".html";
It could be an error somewhere else, but I am working down the line trying to bug-fix it.
I understand pretty much everything going on, except I don't understand parseInt() and stuff.
Would it be possible to '.getAsIntiger(urlFrags)' ? (I have tried this but I may have implemented wrong.)
The error there is here:
curPage = parseInt(urlFrags[urlFrags.length]);
You should be doing
curPage = parseInt(urlFrags[urlFrags.length-1]);
Since if you have a length of 2 in your array, you cannot access Array[2] because it doesn't exist. You have to access Array[1] because the array index starts in 0.
Why not do a var num = parseInt(/.+?_(\d+)\.html/.exec(window.location.href)[1])

Jquery & JSON: Replace section of JSON array

I've been reading a ton on this and can't seem to find a solution that works for me. I am building a drag and drop menu system and saving the structure to the db as JSON.
I have a hidden field as part of a form that submits to the db. This hidden field has the full JSON string in it.
When I update a particular node/menu item, I want to search the value of the hidden text field, find the 'section' of JSON I want to update and replace it with the new values.
What is the best solution for this? grep? replaceWith?
Example before and after JSON
// This is the full json string
[{"title":"Cool link","link":"link","cssclass":"","cssid":"","id":"1399209929525"},{"title":"New link","link":"new-link.html","cssclass":"","cssid":"","id":"1399209790202"},{"title":"Another link","link":"cool","cssclass":"","cssid":"","id":"1399209834496"}]
// This is the updated section
[{"title":"Another link changed","link":"cool","cssclass":"","cssid":"","id":"1399209834496"}]
So I have the updated section with a unique ID to search against.
A simple solution would be something like this, but it doesn't work like that.
var currentsection = /'{"title":"' + edittitle + '","link":"' + editurl + '","cssclass":"' + editcssclass + '","cssid":"' + editcssid + '","id":"' + editid + '"}'/;
var newsection = /'{"title":"' + updatedtitle + '","link":"' + updatedlink + '","cssclass":"' + updatedcssclass + '","cssid":"' + updatedcssid + '","id":"' + updatedid + '"}'/;
$("#menu_items").val().find(currentsection).replaceWith(newsection);
What do you think the best approach is? Many thanks for taking the time out to help. I really appreciate it.
I think you should create your JSON object, and work with it. In this way it would be easy to change values and also save it as you want ;)
For example :
var json = YOUR JSON HERE;
var obj = JSON.parse(json);
// now you can update values as you want
// for example with example title
obj[0].title = "updatetitle";
And then, before sending your JSON, you may want to convert it in plain text
var json = JSON.stringify(obj);

Use String as object in javascript?

Here I am dynamically getting a string like this:
var datN="{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336";
I want to use it in HighChart api as graph data but this is not working. I have tried and got this that if the code was like this it would work:
var datN=[{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336];
so how can I convert the first variable to work like the second one? I am new to javascript please help?
UPDATE
All I want is to convert the first string to object like second one (Second one is working correctly) . I have already tries JSON.parse and eval but they didnt work. So please help?
var datArr = JSON.parse("[" + datN + "]");
This may not work across browsers because JSON.parse is not supported by all browsers. I think you could use jquery
var datArr = $.parseJSON("[" + datN + "]");
If it still does not work, you may try
var datArr = eval("[" + datN + "]");
Although this solution is not recommended.

Categories

Resources