Jquery & JSON: Replace section of JSON array - javascript

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);

Related

Joining two text values to form hyperlink

I'm prefacing this with the fact that coding is most definitely not my strong suit.
I'm currently trying to join two pieces of text to form a link sitting behind an image. The first piece of text is defined (https://www.example.mystore.com/customers/) with the second part being from a datatable (<span id="customcontent752">[Link ID]</span>). Question is - how do I get both of these pieces of information to join to form
https://www.example.mystore.com/customers/[Link ID]? I figure it's something simple I can drop into the source code, but can't for the life of me work it out.
Cheers in advance!
var firstPiece = "https://www.example.mystore.com/customers/";
var secondPiece = $("#customcontent752").text().trim();
var result = firstPiece + secondPiece; //"https://www.example.mystore.com/customers/[Link ID]"
Simply use the + operator if both are strings.
i.e
"https://www.example.mystore.com/customers/" + link_id
should get you what you want.
you can use concat :
var x = "https://www.example.mystore.com/customers/"
var y ="[link ID]"
var result = x.concat(y)

Jquery Appended Button Not Displaying Correctly

I am working with Jquery/javascript/html. I am trying to display a button inside of tags in my table. I am appending the information into/onto a section on my html page. Code is as follows:
<html>
<body>
<p id="report_area"></p>
</body>
</html>
Javascript file below
$('#report_area').append('<table>');
$('#report_area').append('<tr>');
$('#report_area').append('<th>' + view + '</th><th>' + col_1 + '</th><th>' + col_2 + '</th><th>' + col_3 + '</th>');
$('#report_area').append('</tr>');
var btn=$('<button/>');
btn.text('View');
btn.val=item.SURVEY_JOB_ID;
btn.id=item.SURVEY_JOB_ID;
// recently added code - start
btn.click(function()
{
window.localStorage.setItem("MyFirstItem", 10);
window.location = 'GoToThisOtherPage.htm'
}
// recently added code - end
$('#report_area').append('<tr><td>'+ btn +'</td><td>' + item.JOB_NUMBER +
'</td><td>' + item.TITLE + '</td><td>' + item.MODIFICATION_NUMBER + '</td></tr>');
$('#report_area').append('</table>');
THis seems to work correctly however, the button is not showing up correctly. It shows up as an object. All the other data displays correctlyMy table row is displayed as :
[object Object] 12 New Job Title 0
[object Object} 30 Title Help Me 1
I'm not sure why it is displaying as [object Object]. When I do something as simple as:
$('#report_area').append(btn);
the button shows up on the page correctly. Any help on this would be greatly appreciated. Thanks in advance.
To understand why this does not work, you have to look at the documentation for append.
Type: htmlString or Element or Array or jQuery
append is able to except any of those types, and handle each of them differently, so when you pass it an element (actually jQuery collection), it is able to intelligently convert it into the desired html.
However, in your case, you are passing it a string, so it will naively treat the string as html. The reason that this produces [object Object], is because it is relying on native JavaScript to convert the element into a string. You'll produce the same output with console.log(btn).
// append recieves a jQuery collection, calls appropriate methods to obtain html
$('#report_area').append(btn);
// append receives a string, blindly assumes that it is already the desired html
$('#report_area').append(btn + '');
Solution 1 - Append separately
From your comments on other answers, it doesn't seem like this solution works. I think this is because append will automatically add the close tags for the tr and td when appending, causing the button to be added afterwards. You could check if this was the case by looking at the html produced in the developer tools of your browser.
$('#report_area').append('<tr><td>', [btn, '</tr></td>'])
Solution 2 - Convert to string properly
$('#report_area').append('<tr><td>'+ btn[0].outerHTML +'</td><td>')
Solution 3 - Constructing everything as jQuery collections
I think the main problem you have been having is to do with mixing elements and strings. I've written a working jsfiddle solution that constructs everything as jQuery collections.
var table = $('<table>');
var btnRow = $('<tr>');
var btnCell = $('<td>');
var btn=$('<button>');
btn.text('View');
btn.val('val');
btn.attr('id', 'id');
btn.on('click', function()
{
window.alert('Click');
});
btnCell.append(btn);
btnRow.append(btnCell);
table.append(btnRow);
btnRow.append('<td>1</td><td>2</td><td>3</td>');
$('#report_area').append(table);
JavaScript is converting btn to a string because you're concatenating several strings to it.
It should work if you do this.
$('#report_area').append('<tr><td>');
$('#report_area').append(btn);
$('#report_area').append('</td><td>' + item.JOB_NUMBER +
'</td><td>' + item.TITLE + '</td><td>' + item.MODIFICATION_NUMBER + '</td></tr>');
$('#report_area').append('</table>');
You're attempting to set native DOM properties on a jQuery object. Remember, a jQuery object is a superset of a native DOM object. Alter your code to use the .val() and .attr() jQuery methods like so:
var btn=$('<button/>');
btn.text('View');
btn.val(item.SURVEY_JOB_ID);
btn.attr('id', item.SURVEY_JOB_ID);
Alternately, you can chain these methods together for convenience:
var btn= $('<button/>')
.text('View')
.attr('id', item.SURVEY_JOB_ID)
.val(item.SURVEY_JOB_ID);
Finally, alter your use of the .append() method to append the content like so:
$('#report_area').append(
'<tr><td>',
[
btn,
'</td><td>' + item.JOB_NUMBER + '</td><td>' + item.TITLE + '</td><td>' + item.MODIFICATION_NUMBER + '</td></tr></table>'
]);

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.

Javascript post data order

I've got a bit of a funny problem that i'm sure others here will find easy to solve. I need to hash an entire query string, then include that hash value in the post data.
After trying it a few other ways, i'm trying to do this with javascript. Somehow it seems like the order in which the string is pulled together from the form to be hashed differs from the way that it is pulled together when it is submitted.
I'm excluding a hidden element with a specific class to build up the query string to be hashed, then setting that hidden element with the hash value before the final submit.
Any idea what i might be doing wrong, or how i could ensure the order of elements is the same both on building the string and the submit?
The relevant snippet:
var allFormDat = document.getElementById("frmPayment").elements;
var hashingString ='';
var hashVal;
for (i=0;i<allFormDat.length;i++) {
if (allFormDat[i].className!="nohash"){
hashingString+=allFormDat[i].name+'='+allFormDat[i].value+'&';
}
}
hashingString.substring(0, hashingString.length - 1);
hashingString += '[salt]';
hashVal=SHA1(hashingString);
frm.hashValue.value=hashVal;
document.getElementById('frmPayment').submit();
First of all, you're not URI-encoding the components. You probably should:
var field = allFormDat[i];
hashingString += encodeURIComponent(field.name) + '='
+ encodeURIComponent(field.value) + '&';
substring does not work in-place. You'll have to reassign:
hashingString = hashingString.substring(0, hashingString.length - 1);

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

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

Categories

Resources