Appending string to value of array - javascript

Hi Im populating select > options using my json using below code. Here my doubt is I want to add custom attribute only if value is "IN". Anyone can help to achieve this
$.each( data, function( i, val ) {
items.push( "<option value='" + val.countryCode + "'>" + val.countryName + "</option>" );
});

Try something like this
$.each( data, function( i, val ) {
items.push( "<option value='" + val.countryCode +( val.countryCode == "IN" ? "data-attr = 'value'" : "" ;) "'>" + val.countryName + "</option>" );
});

Currently it's only possible with a if condition. You can increase speed by breaking on the first found result, but you need to use a for-loop:
for(var i=0;i<countryArr.length;i++) {
if(countryArr[i].countryCode === "IN") {
items.push( "<option value='" + countryArr[i].countryCode + "'>" + countryArr[i].countryName + "</option>" );
break;
}
});
If you want to use forEach see this post.. But a some expression might be easier:
countryArr.some(function(data) {
var check=countryArr[i].countryCode ==="IN";
if(check) {
items.push("<option value='" + data.countryCode + "'>" + data.countryName + "</option>");
}
return check; //some stops, if it returns true
});
ECMA6 will introduce a find method so you can shortcut this:
items.push(countryArr.find(function(data) {
return data.countryCode === "IN";
});

$.each( data, function( i, val ) {
if(val.countryCode !='IN') {
items.push( "<option value='" + val.countryCode + "'>" + val.countryName + "</option>" );
}
else {
items.push( "<option data-id=1 value='" + val.countryCode + "'>" + val.countryName + "</option>" );
}
});

If I understand your question correctly:
$.each( data, function( i, val ) {
items.push( "<option "+ (val.countryCode === "IN" && "data-id=1" || "") + " value='" + val.countryCode + "'>" + val.countryName + "</option>" );
});`

Related

Jquery populate list freak error

I'm facing a freak problem in jquery. When I try to populate a list from a table it becomes empty if it contains a special character like sid'ahmed. When I change it to sidi ahmed it works perfectly. This is my code to populate two lists:
$.getJSON("get-data.php?dat=driver", function(data) {
var stringToAppend1 = "<option value='" + day_Shift + "'>" + day_Shift + "</option>";
var stringToAppend2 = "<option value='" + night_Shift + "'>" + night_Shift + "</option>";
$.each(data, function(key, val) {
stringToAppend1 += "<option value='" + val.prenom + " / " + val.nom + " : " + val.telephone + "'>" + val.prenom + " / " + val.nom + " : " + val.telephone + "</option>";
stringToAppend2 += "<option value='" + val.prenom + " / " + val.nom + " : " + val.telephone + "'>" + val.prenom + " / " + val.nom + " : " + val.telephone + "</option>";
});
$("#night_Shift_text" + id).html(stringToAppend2);
$("#day_Shift_text" + id).html(stringToAppend1);
});
You should escape the single quote by using replace function as shown below. Use this replace whereever needed.
day_Shift = day_Shift.replace(/'/g, "\\'");
Hope this helps!!

How to add if statement in jQuery to check if property exist in JSON file?

I am trying to add an if statement to check if a particular property exist in JSON file, to write the value, if not, do nothing.
I want that property if exist to be written in HTML between <div class='titleHolder'> and "<div class='posterHolder'>"
Between these two divs i want to have property X, only if exist in JSON file
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id=' + data[ i ].id + '" + <div class="itemsHolder">' +
"<div class='titleHolder'>" +
"<h2 >" + data[ i ].name + "</h2>" +
"</div>"+
"<div class='posterHolder'>" + data[ i ].posterPath + "</div>" +
"<div class='summaryShort'>" + data[ i ].summary + "</div>" +
"<div class='raiting'><p>" + data[ i ].imdb + "</p></div><div class='genderMovie'> " + data[ i ].gender + "</div> " +
"<div class='directorNdScreen'>" + 'Director by ' + " <p class='director'>" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class='screenplay'>" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>")
}
} )
} );
Break your append part in variables and then concate it. may be that can help ?
$(document).ready(function() {
$.getJSON( "js/appjson.json", function(data) {
for (var i = 0; i < data.length; i++) {
var content_append = "normal content";
if(data[i])
{
content_append = "content here with data[i]"
}
$('#jsonLoad').append(content_append);
}
});
});
'<div>' +
(something === something_else)? 'some data1' : 'some data2' +
'</div>'

Ajax Posts Empty Name - Fixed

I have fallowing code parse json files from .json file and works well. when i give it name and trying to post from form data gives me empty post data.
HTML:
<div id="jewels" ></div>
JS:
<script type="text/javascript">
$.getJSON( "include/settings/guild_bank_jevels.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<option name='jewel_name' value='" + key + "'>" + val + "</option>" );
});
$( "<select/>", {
html: items.join( "" )
}).appendTo( "#jewels" );
});
</script>
Thanks in advance for help.
UPDATE Fixed
Script:
<script type="text/javascript">
$.getJSON( "include/settings/guild_bank_jevels.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<option value='" + key + "'>" + val + "</option>" );
});
$("#jewels").html(items);
});
</script>
HTML Part:
<select id="jewels" name="jewel_name">
</select>
Your select doesn't have a name or id. Inputs need to have one of these for forms to post their value.
$( "<select/>", {
id='some_id',
html: items.join( "" )
}).appendTo( "#jewels" );
You have some extra double quotes " in the following line :
items.push( "<option name="'jewel_name'" value='" + key + "'>" + val + "</option>" );
___________________________^____________^
Please try to replace it by :
items.push( "<option name='jewel_name' value='" + key + "'>" + val + key + "</option>" );
Snippet
var items = [];
var data={'first_key': 'first_val', 'second_key': 'second_val'};
$.each( data, function( key, val ) {
items.push( "<option name='jewel_name' value='" + key + "'>" + val + "</option>" );
});
$( "<select/>", {
html: items.join( "" )
}).appendTo( "#jewels" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jewels" ></div>
Hope this helps.

Unable to loop through JSON Data [duplicate]

This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 7 years ago.
I have the following Json data (Please see the image). I am trying to extract the data using the below jQuery code and it's not working. Please help.
var items = [];
$.each($.parseJSON(OnePointData), function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(key, function(key2, val2) {
items.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items);
Here is an image of my console:
And here is additional code from my implementation:
$.getJSON("/Home/GetOnePointData", { Address: ui.item.value },function(OnePointData) {
console.log(OnePointData);
var items = [];
var items2 = [];
$.each($.parseJSON(OnePointData), function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(key, function (key2, val2) {
items2.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items2);
});
If i run the loop once then i get the following result.
The data is in the following format:
{"GetQuestions":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"},
"GetQuestions2":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"}}
As #Barmar says $.getJSON calls $.parseJSON automatically. So, just try removing $.parseJSON function:
$.getJSON("/Home/GetOnePointData", { Address: ui.item.value}, function(OnePointData) {
console.log(OnePointData);
var items = [];
var items2 = [];
$.each(OnePointData, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(val, function (key2, val2) {
items2.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items2);
});
This is an example using data structure posted by you and it works.
var OnePointData = {"GetQuestions":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"},
"GetQuestions2":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"}};
var items = [];
var items2 = [];
$.each(OnePointData, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(val, function (key2, val2) {
items2.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items);
console.log(items2);
Output:
["<li id='GetQuestions'>[object Object]</li>", "<li id='GetQuestions2'>[object Object]</li>"]
["<li id='s1'>Q1,Q2</li>", "<li id='s2'>Q1,Q2,Q3</li>", "<li id='s3'>Q1,Q2,Q4</li>", "<li id='s4'>Q1,Q2,Q4,Q6</li>", "<li id='s1'>Q1,Q2</li>", "<li id='s2'>Q1,Q2,Q3</li>", "<li id='s3'>Q1,Q2,Q4</li>", "<li id='s4'>Q1,Q2,Q4,Q6</li>"]

Building HTML table in javascript, getting "ReferenceError: invalid assignment left-hand side"

I hope someone can help me out with this. I'm trying to dynamically build an HTML table in javascript/jquery based on iterating over an array built by earlier code. I am getting an error on the referenced line below as soon as the page loads:
function BuildForm (allFields) {
var dyndata = "";
var formstart = "<form>\n<fieldset class='fieldset-js'>\n<legend>Choose A Parent</legend>\n<table class='table-js'>\n<tr>\n<th class='th'>ID</th>\n<th class='th'>Name</th>\n<th class='th'>DOB</th>\n<th class='th'>Phone</th>\n</tr>\n<tr>";
$('#PickAParent-Form').append(formstart);
$.each(allFields, function (index, value) {
if ((index + 5) % 5 == 0) {
dyndata = "<tr>\n<td class='td1'><input type='radio' name='pid' value='" = index + "'>" + value + "</td>\n";
error here---------^
$('#PickAParent-Form').append(dyndata);
} elseif ((index +1 ) % 5 == 0) {
dyndata = "<td class='td1'>" + value + "</td>\n</tr>\n";
$('#PickAParent-Form').append(dyndata);
} else {
dyndata = "<td class='td1'>" + value + "</td>\n";
$('#PickAParent-Form').append(dyndata);
}
});
DisplayForm;
}
I have been all over Google and SO this AM but can't figure this one out. Any help is MUCH appreciated!!
This line:
dyndata = "<tr>\n<td class='td1'><input type='radio' name='pid' value='" = index + "'>" + value + "</td>\n";
should be:
dyndata = "<tr>\n<td class='td1'><input type='radio' name='pid' value='" + index + "'>" + value + "</td>\n";
Looks like you had an equals sign instead of a plus sign for variable to string conversion
Change it to:
dyndata = "<tr>\n<td class='td1'><input type='radio' name='pid' value='" + index + "'>" + value + "</td>\n";
Note:
value='" + index + "'
Instead of:
value='" = index + "'

Categories