jquery how to search and fulfill divs contents with object content - javascript

I am getting stacked with inserting the content returned by an ajax call.
I have a set of divs, each div has a different id example:
<div id ="first_name"> content </div>
<div id ="last_name"> content </div>
<div id ="email"> content </div>
on the other hand I have an object with key => value example:
{"first_name" : "value", "last_name" : "value", "email" : "value"}
the keys of the object match the div's ids.
how can I on $(document).ready() search for the matching ids and object keysand put their values in jquery?

Original answer:
for(val in entries) {
if(entries.hasOwnProperty(val)) {
$("#"+val).html(entries[val]);
}
}
Edited to address question in comments:
You want this to happen automatically? When you receive new data from an ajax call?
$.getJSON(url, function(entries) {
for(val in entries) {
if(entries.hasOwnProperty(val)) {
$("#"+val).html(entries[val]);
}
}
}

for(key in myObject) {
$('#' + key).html(object[key]);
}

You can set the content of a DIV using .html();
For example:
$("#first_name").html('Thomas');
or using your object depending on how you're hydrating the JSON.
$("#first_name").html(yourobject.first_name);

Related

How to fetch querySelector for name containing numerics

I have the below url
<h1 id="header_2" title="mytitle" data-id="header_title" class="sampleclass " xpath="1">mytitle<span aria-label="sometest" class="sampleclass ">- Saved</span></h1>
Based in the id(header_2)I wabt to fetch title.
My id may also contains like this id="header_mdfa3fad" but for sure after "_" it is numeric.HOw do I write querySelector for it
You can apply regex to filter like this
var divs = [].slice.call(document.querySelectorAll("[id^='header_']")).filter(function(el){
return el.id.match(/^header_[0-9]+/i);
});
console.log(divs);
<div id="header_1"></div>
<div id="header_2"></div>
<div id="header_3"></div>
<div id="header_abc"></div>
<div id="header_xyz"></div>
You can use this solution:
const headers = document.querySelectorAll("[id^='header_']");
const titles = [];
headers.forEach((header) => titles.push(header.getAttribute('title')));
// Do something you want with titles array
If I understand you correctly, try something like this:
#select h1 elements with id attribute whose value begins with "header"
headers = document.querySelectorAll("[id^='header_']");
#loop through the elements and extract the part of the attribute value following "_"
for (let header of headers) {
target = header.getAttribute('id').split('_')[1]
#check for the presence of a digit
if (/\d/.test(target)) {
console.log(header.getAttribute('title'))
}
}

Comparing query string fields to display JSON using JS Render

I have a working JS Render template that pulls in a different JSON file based on the values of a query string. I am trying to figure out how to change the value of the JS Render element (id_1) based off of the query string field "source".
So if my url ends with "?market=ab&source=index", I want
"{{:id_1}}" to display "index_id_1" from the ab.JSON file.
HTML
<script type="text/x-jsrender" id="logoTempl">
<div id="cta-div">
Button
</div>
</script>
<div class="mainContainer">
</div>
JSON
[{"assets" : {
"field1" : "value",
"field2" : "value"
},
"ids" : {
"index": {
"id_1": "index_id_1",
"id_2": "index_id_2",
"id_3": "index_id_3"
},
"email": {
"id_1": "email_id_1",
"id_2": "email_id_2",
"id_3": "email_id_3"
}
}
}
]
JS
if (market == 'ab' && source == 'index') {
$.getJSON('data/ab.json', function(data) {
var logoField = logo.render(data);
var id1 = data[0].ids.index.id_1
$(".mainContainer").html(logoField);
$("{{:id_1}}").html(id1);
})
}
If I understand correctly you want the template to show the value ids[source].id_1.
You can pass in source as a helper, e.g.
...logo.render(data, {idgroup: source});
and then in the template, write:
{{:ids[~idgroup].id_1}}
or you can create a getId helper function, e.g.:
...logo.render(data, {getId: function(index) {
return data[index].ids[source];
}});
and then in the template, write:
{{:~getId(#index).id_1}}

How to submit dynamically created hidden variables using Jquery

I have created a dynamic table. DEMO to my project.
I have placed this dynamic table in the form under a div named 'box'
<div id="box">
</div>.
I am creating dynamic hidden variables table using Jquery which I need to store in DB. This is how I am creating the hash to submit to server.
criteria = $('form_name').serialize(true);
criteria = Object.toJSON(criteria);
// Build the object to store the parameters for the AJAX post request
parameters = {
title : $('report_title').value,
description : $('report_description').value,
criteria : criteria
}
// Make the AJAX post request
new Ajax.Request( URL, {
method: 'post',
parameters: parameters,
onSuccess: function( response ) {
$('messageSpan').innerHTML = response.responseText;
$('spinner').style.display='none';
}
});
I am not able to capture the dynamically created values in the criteria.
How to solve this?
In the dynamically created section, I tried adding a submit button and see if the values can be fetched. I am able to fetch and iterate all the hidden variables.
$('#jquerysaveButton').click(function(){
jsonObj = [];
$("input[id=rubric_cell]").each(function () {
var id = "cell_" + row + "_" + col;
item = {}
item["id"] = id;
item["selected_rubric"] = $(this).val();
jsonObj.push(item);
});
console.log(jsonObj); //I am getting the required values here
});
How to get these values in the criteria = $('form_name').serialize(true);. Am I doing some thing wrong? Please help me. thanks in advance.
DEMO to my project
You need to make sure that your hidden input fields have a name attribute set otherwise $.serialize will not process them.

Populate items into SELECT with Jquery

I'm having trouble populating a SELECT with jquery, when the user writes the zipcode or part of it, it searches the database and returns this:
{"success":1,"id":"50","street":"Central One"},{"success":1,"id":"60","street":"Central Two"}
One success for each street it finds. For a single street and using a text input I'm using this
UPDATE 1 - FULL CODE
$(document).ready( function() {
$('#zip').blur(function(){
$.ajax({
url : '../../controller/zip.php',
type : 'POST',
data: 'zip=' + $('#zip').val(),
dataType: 'json',
success: function(data){
if(data.sucesso == 1){
$('#id').val(data.id);
$('#street').val(data.street);
}
}
});
return false;
})
});
How can I change this so I can populate a select box.
Thanks
What is being passed back for a single address is a single object from which you can grab the information. When there are multiple responses you need to go through each of them and handle them.
When we look at MDN's article it shows that we need a parent <select> tag and then we need to populate the children. The process would look like this:
Find / create parent select
[Optional] Remove previous child <option> tags
Loop through responses
Create a new <option> element
Populate the <option> with the appropriate value and content
Append it to the parent <select>
Some things to be aware of, if you're clearing the previous addresses each time you get a response from the database you'll want to remove these previous <option>s. This can be done either by .empty() if there are no other children in the parent or starting with the parent <select> and removing all child <options>.
Use this for adding items to select box dynamically:
var $selectBox = $('#selectboxId');
$selectBox.empty();
$.each(data, function (idx, val) {
if (val.success) {
$selectBox.append($('<option>', {
value: val.id,
text: val.street
}));
}
});
I would not encourage to do so; you're better off using a html-templating engine like mustache or handlebars.
Doing this kind of stuff in plain JS (string concatenation) is gross. It pollutes your sourcecode.
Anyways, this would do the trick to generate the necessary HTML:
function generateHTML(data){
return data.reduce(function(o,n){
return o+"<option value='"+n.id+"'>"+n.street+"</option>";
},"");
}
Here is the Fiddle to play with. If you need to filter for success, you could add a filter()
function generateHTML(data){
return data.filter(function(x){
return !!x.success;
}).reduce(function(o,n){
return o+"<option value='"+n.id+"'>"+n.street+"</option>";
},"");
}
You could easily use $("#selectBoxId").html(generateHTML(data)) to insert it to the DOM.
To fit it into your codebase, you should add it in the success handler:
success: function(data){
function generateHTML(data){
return data.reduce(function(o,n){
return o+"<option value='"+n.id+"'>"+n.street+"</option>";
},"");
}
$("select").html(generateHTML(data))
}
For the inner workings of Array.prototype.reduce() take a look at MDN and for Array.prototype.filter()
If the JSON being returned is a list [{...}, ..., {...}], then you can use Array.forEach. Here is the success callback:
function(data) {
data.forEach(function(item) {
if (item.success) {
// use item.id and item.street
}
});
}
If you have a <select> element, then you will want to be populating it with <options>, by appending an <option> element under each successful "if" branch in the forEach.
Assuming you already have the select element on the page and the data that is coming back from the server is an array of objects, this should work:
$.ajax({
url : '../../controller/zip.php',
type : 'POST',
data: 'zip=' + $('#zip').val(),
dataType: 'json',
success: function(data) {
var $items = [];
$.each(data, function(street) {
if(data.success === 1) {
$items.push($('<option />').attr({
value: street.id
}).text(street.street));
}
});
$('#your-select-element').append($items);
}
});
Notice this isn't setting the value for one option, it is creating <option> tags for each of the response's streets and appending them to a <select> element.

too much HTML in an ajax script?

I read from this page that appending a lot of elements is bad practice and I should build up a string during each iteration of the loop and then set the HTML of the DOM element to that string. Does the same go for using too much HTML in the loop?
I have an AJAX script that parses JSON data. It requires adding data to different existing elements, like this:
$.ajax({
url: "url",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(''+ingredient+'')
$('.'+ title+'_age').html(''+age+'')
$('.'+ title+'_background').html(''+background+'')
});
},
error: function () {}
});
HTML:
<div class="A_ingredient"></div>
<div class="B_ingredient"></div>
<div class="C_ingredient"></div>
<div class="D_ingredient"></div>
<div class="A_age"></div>
<div class="B_age"></div>
<div class="C_age"></div>
<div class="D_age"></div>
<div class="A_background"></div>
<div class="B_background"></div>
<div class="C_background"></div>
<div class="D_background"></div>
Is it necessary to build up a string first? If so, can you show me how to do that?
It is purely about the time it takes to process calls to html() so they simply recommend you reduce the number of calls. In this case you could build them once in a loop then sets the div html once for each.
Update:
Based on your update, aside from all the extra trailing quotes you don't need to add (a string is a string is a string), your code is fine as is. You only hit each item once.
e.g.
$.ajax({
url: "url",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(ingredient);
$('.'+ title+'_age').html(age);
$('.'+ title+'_background').html(background);
});
},
error: function () {}
});
Note: If your item properties (Age, Background, Ingredient) are simple values (not objects or arrays), yo do not need the leading ''+s either.
Previous
Assuming you actually want to concatenate the results (you are only keeping the last ingredient at the moment), you could do something like this:
e.g.
$.ajax({
url: "url",
success: function (data) {
var ingredients = '';
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredient = item.Ingredient;
ingredients += ingredient;
});
$('.aclass').html(ingredients);
$('.bclass').html(ingredients);
$('.cclass').html(ingredients);
$('.dclass').html(ingredients);
},
error: function () {}
});
Which can be reduced to:
$('.aclass,.bclass,.cclass,.dclass').html(ingredients);
The contents of each div are identical in your example, so you only need a single string.
In this instance you would probably need some form of delimiter between ingredients, but your example is too vague.
e.g.
ingredients += ingredient + '<br/>';
In your example, you're setting the HTML on many different document elements.
If they're grouped in some way, for example all in a Div with ID #Container, you could build a string of the HTML and set the content of the whole Div at the end of it, something like this:
$.ajax({
url: "url",
success: function (data) {
var sHTML="";
$(data.query.results.json.json).each(function (index, item) {
var title = item.title,
background = item.background,
ingredient = item.Ingredient;
// not sure what your actual HTML is (div/span/td etc) but somethign like this?
sHTML+="<div>"; // an opening container for this item
sHTML+='<div class="'+title+'_ingredient">'+ingredient+'</div>')
sHTML+='<div class="'+title+'_age">'+title+'</div>')
sHTML+='<div class="'+title+'_background">'+background+'</div>')
sHTML+="</div>";
});
$("#Container").html(sHTML);
},
error: function () {}
});
Note I haven't tested this code, but you see the principal hopefully.
That is, build a string of the HTML then set one element at the end with the content.
I have done this a lot in a recent project and haven't seen any speed issues (maybe 50 'items' to set in my case).
HTML will initially look like this :
<div id="container">
</div>
Then end up like this (2 x items in this example) :
<div id="container">
<div>
<div class="<sometitle1>_ingredient">ingredient 1</div>
<div class="<sometitle1>_age">age 1</div>
<div class="<sometitle1>_background">background 1</div>
</div>
<div>
<div class="<sometitle2>_ingredient">ingredient 2</div>
<div class="<sometitle2>_age">age 2</div>
<div class="<sometitle2>_background">background 2</div>
</div>
</div>
subsequent calls will replace the element's content with new values, replacing the old items.
Building a string is, I would imagine, less processor-heavy than setting the html() on lots of elements individually. Each time you use html() I'm guessing that the browser has to go some way towards working out any knock-on effects like expanding the width of an element to accomodate it or whether events will still work as they did, etc - even if actual rendering is only run at the end of the process. This way you use html() once, although what you're setting is more complex.
Hope this helps.

Categories