How to append data for each div separately - javascript

Simple but I dont know how to do it. I am trying to append data for each div separately $. Each function is looping and assigning whole data to the same div.
These are my two div.
<div class="div1">
<div class="div2">
// whole javascript code is here
</div>
</div>
The whole code is something like this:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData += item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/> ";
});
$(".div2").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
return false;
});
});
Div1 contains outer CSS for that particular div2. I want to generate multiple div2 for each data returned from the server. I have tried using return false but still same result. Please tell me how to do it.

This may help you. I have change the code to make it simple.
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
//make parent div blank
$(".div1").html("");
$.each(data, function (i, item) {
//make html for div2
var html += "<div class='div2'>";
html += item.PostedByName;
html += "<img src='" + item.PostedByAvatar + "'height='100' width='100'/>"
html += "</div>";
//append all div2 to parent div1
$(".div1").append(html);
});
});
});

$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData +="<div class='div2'> item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/></div> ";
});
$(".div1").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
//return false;
});
});

Related

jquery onchange function is not calling

i have the following piece of code:
function teamAuswaehlen() {
$.post("Auswahl_Abteilung?_=" + new Date().getTime(), function(data) {
eintraege = "<div class='col-md-12 col-xs-12'>" +
"<div class='form-group'>" +
"<select class='form-control' id='teams' title='Wählen Sie hier ihre Teamansicht'>"
if (data.length > 1) {
$("#kalenderAuswahl .modal-body").empty();
$.each(JSON.parse(data), function(key, value) {
eintraege += "<option id='" + value.Team_ID + "'>" + value.TE_Kurzbezeichnung + "| " + value.TE_Langbezeichnung + "</option>";
});
eintraege += "</select>" +
"</div>" +
"</div>";
}
if (data.length > 1) {
$("#kalenderAuswahl .modal-body").append(eintraege);
$("#kalenderAuswahl").modal("show");
}
}).done(function() {
$("#teams").change(function() {
getId(this);
});
});
}
The Modal is build dynamicly at the start of the programm.
So the onchange event i want to call if a user change the select box is store in the done block.
But if i trie the code, nothing happens so the onchange event is not fired.
So how can i handle that ?
Here is code snippet for your change event.
$('body').on('change', '#teams', function(e) {
e.preventDefault();
// do your stuff
});
You can write this change event code in below section
Before body tag end Or
You can write in $(document).ready(function() {})
you can remove done method and paste your code to body.
select event with body tag as like $('body').on('change', '#teams'
or
just use like this $('body').on('change', '#teams' in done method.
No need to place code in done().place the following code anywhere in tag
$(document).on('change','#teams',function() {
getId(this);
});

Why always getting last row from json array result when iterate through with Jquery

I have json data in this structure
here is my json code
https://jsonblob.com/309e8861-7f26-11e7-9e0d-cf3972f3635e
and here is my jquery code example
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
$.each(data, function(index, val) {
$("#result").html("<p>" + val.name + "</p>");
});
});
});
HTML file
<button id="getJsonData">Load role list</button>
<div id="result"></div>
I don't get this, I get every value from json in console when do console.log, but when use html method to display result as html in screen it just showing last value from ending last json array. What is wrong here?
jquery .html always overrite previous html so we cant use html in loop section instead of that we can use append it simply append your p tag in result div
Instead of using this:-
$("#result").html("<p>" + val.name + "</p>");
use like this:-
$("#result").append("<p>" + val.name + "</p>");
You are overwriting the html with the code
$("#result").html("<p>" + val.name + "</p>");
Instead you can store the result in variable and then you write it to the element.Like this
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var html = '';
$.each(data, function(index, val) {
html +="<p>" + val.name + "</p>";
});
$("#result").html(html);
});
});
Your code should be :
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var listHtml="";
$.each(data, function(index, val) {
listHtml=listHtml+ "<p>" + val.name + "</p>";
});
$("#result").html(listHtml);
});
});
And Html should be same as your
<button id="getJsonData">Load role list</button>
<div id="result"></div>
Working example is here

MVC Dropdownlist Cascade - how to fire event on third ddl when first ddl selection changes?

I have three DDL's in a view. I fire a javascript function on 'onchange' of the first DDL to populate the second, and of the second to populate the third. Works fine.
Problem is, when first DDL is set to unselected i.e. "Select a Value", the second DDL gets fired and sets itself to "Select a Value", but the second DDL 'onchange' event does not fire, so the third DDL remains populated with the data that it got from the previous selection.
How do I get the second DDL to fire an event I can use to refresh the third DDL? Or is there another way?
Code below:
#{
ViewBag.Title = "CascadingList";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{Html.EnableUnobtrusiveJavaScript(true);}
<script type="text/javascript">
$(document).ready(function () {
getMarket();
});
function getMarket() {
var url = '#Url.Content("~/Strategies/MarketList")/';
$.getJSON(url, function (data) {
var items = "<option>Select a Market</option>";
$.each(data, function (i, market) {
if (market.Value.indexOf("\'") > -1) {
s = market.Value + " " + market.Text;
alert(s + ": Market.Value cannot contain \'")
}
items += "<option value='" + market.Value + "'>" + market.Text + " </option>";
});
$('#MarketsID').html(items);
});
}
function getShareType() {
var url = '#Url.Content("~/Strategies/ShareTypeList")/' + $('#MarketsID').val();
$.getJSON(url, function (data) {
var items = '<option>Select an Asset Type</option>';
$.each(data, function (i, shareType) {
items += "<option value='" + shareType.Value + "'>" + shareType.Text + " </option>";
});
$('#ShareTypesID').html(items);
});
}
function getShare() {
var url = '#Url.Content("~/Strategies/ShareList")/' + $('#MarketsID').val() + '|' + $('#ShareTypesID').val();
$.getJSON(url, function (data) {
var items = '<option>Select a Share</option>';
$.each(data, function (i, share) {
items += "<option value='" + share.Value + "'>" + share.Text + "</option>";
});
$('#SharesID').html(items);
});
}
</script>
<h2>Strategy</h2>
<div id="MarketsDivID">
<label for="Markets">Markets</label>
<select id="MarketsID" name="Markets" onchange="getShareType()"></select>
</div>
<div id="ShareTypesDivID">
<label for="ShareTypes">ShareTypes</label>
<select id="ShareTypesID" name="ShareTypes" onchange="getShare()" ></select>
</div>
<div id="SharesDivID">
<label for="Shares">Shares</label>
<select id="SharesID" name="Shares" ></select>
</div>
Try selecting a value for the select after populating it using $('#selectID').val(), if that doesn't work trigger onchange like this ; $('#selectID').trigger('change')
Thanks - I tried that and went around in circles - but it made me think differently. Fixed it by adding a call to the function that populates the third DDL in the function that populates the second DDL - that way it always gets called.
function getShareType() {
var url = '#Url.Content("~/Strategies/ShareTypeList")/' + $('#MarketsID').val();
$.getJSON(url, function (data) {
var items = '<option>Select an Asset Type</option>';
$.each(data, function (i, shareType) {
items += "<option value='" + shareType.Value + "'>" + shareType.Text + "</option>";
});
$('#ShareTypesID').html(items);
});
**** Added This ****
getShare();
}

jquery to append a table to div

i have a div id.i have to append a table with values to the div.
<div id="testResult" style="padding-left: 120px; "></div>
am doing follwing steps but it is not working.
$.ajax({
url: '/getReports',
cache: false
}).done(function (html) {
if (html != "") {
$('#testResult').show();
var htm = "";
var string1 = '<table border="1"><tr><td>No</td><td>Testcase</td> <td>OS</td> <td>Browser</td> <td>Result</td></tr></table>';
$.each(html, function (i, data) {
string1 + = '<tr><td rowspan="3">1</td><td rowspan="3">' + data.status.test + '</td><td rowspan="3"><!--OS--></td><td>' + data.status.bwser + '</td> <td> ' + data.status.report + ' </td></tr>';
});
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
}).fail(function () {
$("#testResult").html("Failed to run the test");
$('#edit ').removeAttr("disabled");
});
$("#testResult").html("<br/><br/>") and $("#testResult").html("<p>" + htm + "</p>") will overwrite contents of your "testResult" DIV. So, replace this
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
with
$('#testResult ').append(string1);
$("#testResult").append("<br/><br/>");
$("#testResult").append("<p>" + htm + "</p>");
}
.append(): Will add or append extra strings to the existing contents of the DIV
where as
.html(): Will removes or overwrite the existing contents of the DIV with newer one.
This is the main difference between .append() and .html().
edit this part
$("#testResult").append("<br/><br/>");
Remove this part-->
$("#testResult").html("<p>" + htm + "</p>");
htm is empty string, as you never concatenate any string to it

Use $.each and if with $.getJSON

Me and $.each aren't good friends, I can't seem to figure out how I should use this statement to print all my data in my JSON file. Another problem is the if statement, I tried it in many ways, but whatever I do, no data is being printed.
My JSON file
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
My $.getJSON script
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var el = document.getElementById("kome");
el.innerHTML = "<td><div class='dsc'>" + data.expo + "<br><em>" + data.datum + "</em></div></td>";
});
}
</script>
So how would I integrate the $.each statement and seperate from that, the if statement?
Try this
$.getJSON("home.json", function (data) {
var html = '',
el = document.getElementById("kome");
$.each(data, function (key, val) {
html += "<td><div class='dsc'>" + val.expo + "<br><em>" + val.datum + "</em></div></td>";
});
el.innerHTML = html;
});
Something like this?
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var html = '';
$.each(data, function(i, record) {
html += '' +
'<td>' +
'<a href="' + record.link + '" data-ajax="false">' +
'<img src="' + record.img + '">' +
'<div class="dsc">' +
record.expo + '<br>' +
'<em>' + record.datum + '</em>' +
'</div>' +
'</a>' +
'</td>';
});
$('#kome').html(html);
});
}
</script>
Note: I haven't tested this, so there may be a few syntax errors (mostly concerned about the quotes in the string concatenation).
I will note that you don't need jQuery's $.each for this; you can use a basic for-loop:
for (var i = 0; i < data.length; i++) {
var record = data[i];
... stuff...
}
jQuery's .each() is really useful when iterating over elements in the DOM, though. For example, if you wanted to iterate over the elements with class dsc, you could do:
$('.dsc').each(function(i, dsc) {
// Do stuff to the $(dsc) element.
});
Also, you might as well use jQuery's selectors (the $('#kome')) if you're going to use jQuery.
jQuery's API usually has solid examples for stuff; this is one such case.
$.each can iterate arrays [] or objects {}, your json contains both, so first you need to tackle array, that gives you an object on each iteration. Then you can access its properties.
jQuery each documentation
Second thing: to append to innerHTML use "+=" not "=" or you will reset html on each iteration.
var el = document.getElementById("kome");
$.getJSON('ajax/test.json', function(data) {
$.each(data, function(n, linkData) {
el.innerHTML += '' + linkData.expo + '';
});
}

Categories

Resources