add function onclick in json parse - javascript

Im trying to load article from json (its works) and add it link to fucntion, but when I add the a href tag with onclick function (for example - alert), the function doesn't work.
what am I missing?
$.getJSON(categoryAddr,function(data){
json=data;
jQuery(function ($) {
$.each(json, function (i, value) {
var list ="<a href='#' onclick='alert('hey!');'>"
+"<h1>" + value.title + "</h1>"
+ "<img src='" + value.image + "' alt=''/>"
+"<h2>" + value.excerpt + "</h2></a>";
$('.hold').append(list);
});
});
});

you need to escapq quotes inside the alert
change this line
var list ="<a href='#' onclick='alert('hey!');'>"
to
var list ="<a href='#' onclick='alert(\'hey!\');'>"

Use escaped double quotes around your JS
var list ="<a href='#' onclick=\"alert('hey!');\">"

Define onclick event outside instead of defining it inline as shown below
jQuery(function ($) {
var json={title:'title1'};
$.each(json, function (i, value) {
var list ="<a href='#' onclick=\"alert('hey!');\">"
+"<h1>" + value + "</h1>" ;
$('.hold').append(list);
});
});
Fiidle : https://jsfiddle.net/9qes9u8u/
Updated Fiddle based upon #rzr answer
https://jsfiddle.net/t8o56g28/

I would go for delegated events:
var list ="<a href='#' class='link'>"
Now you can use this script, and you don't need to have a nested doc ready block:
$.getJSON(categoryAddr,function(data){
json=data;
$.each(json, function (i, value) {
var list ="<a href='#' data-id='" + value.id +"' class='link'>"
+"<h1>" + value.title + "</h1>"
+ "<img src='" + value.image + "' alt=''/>"
+"<h2>" + value.excerpt + "</h2></a>";
$('.hold').append(list);
});
});
This is delegated event on newly created anchor:
$('.hold').on('click', '.link', function(){
alert($(this).data("id"));
});

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

ADD #url.action with parameter on Table cell in AJAX

I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:
$.ajax({
url: "GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (obj) {
debugger;
$tbl.empty();
$tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
for (var i = 0; i < obj.length; i++) {
$tbl.append(' <tr><td> ' + obj[i].senderId + '</td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
}
}
});
Now instead of <a href="#"> I want to add Action Method #URL.Action on that <td>. Here's my Action Method:
<a href=#Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
But it shows error, I can't use javascript variable obj[i].senderId with c# code #Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?
David is right, but a simplified way for easy understanding.
var href = #Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
Both will work fine.
Update: As per Comment.
Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.
$tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');
And add the below script.
$(document).on('click', '.Test', function () {
$(this).attr('href',$(this).attr('data-href'));
});
You can't mix server-side code and client-side code like that.
One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code. Something like this:
var singleSentShowURL = '#Url.Action("SingleSentShow","Home")';
This would result in something like this client-side:
var singleSentShowURL = '/Home/SingleSentShow';
Then in your loop you could use that variable to manually build the URL. Something like this:
$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');
You might split it into multiple lines for readability:
var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');

JQuery .append list items not triggering a script when clicked on

I am working on a page that loads data from an XML file that populates an HTML unordered list. An unordered list is used to make the gallery from the tutorial on this page. Unfortunately, the created thumbnails do not trigger the javascript which creates the expanding preview.
The javascript should be activated when the user clicks on an anchor in the unordered list.
Any suggestions as to how to resolve this issue would be great.
Code
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$('#load').fadeOut();
$(xml).find("painting").each(function () {
$("ul#og-grid").append('<li> <a href="http://google.com/" data-largesrc="images/' + $(this).find("image").text() + '" data-title="' + $(this).find("title").text() + '" ' + '<>' + '<img src="images/thumbs/' + $(this).find("image").text() + '" alt="img01"/> </a> <li> ');
$(".painting").fadeIn(1000);
});
}
</script>
You need to attach the click event. You can do this whilst populating your li or after. I would do the following
$(xml).find("painting").each(function () {
$('<li> <a href="http://google.com/" data-largesrc="images/' + $(this).find("image").text() + '" data-title="' + $(this).find("title").text() + '" ' + '<>' + '<img src="images/thumbs/' + $(this).find("image").text() + '" alt="img01"/> </a> <li> ')
.click(yourClickFunction)
.appendTo('ul#og-grid');
$(".painting").fadeIn(1000);
});
Don't forget to change yourClickFunction.
Hope that helps
use this line for click event
$(document).on('click', 'element-selector', function () {
// Do Stuff Here
});
You can use following JS code for this
$(document).on('click', 'ul#og-grid li', function () {
// Do Stuff Here
});

How to append data for each div separately

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

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

Categories

Resources