I have a javascript function, for example:
function SuperTD(id,str,tooltip) {
return '<td id="' +id+ '" title="' +tooltip+ '">' +str+ '</td>';
}
The SuperTD called and concatenated with many elements, and I don't want to change how it works (into generating element without using html string).
And I need to trigger a function when that elements are rendered, for example:
function SuperTD(id,str,tooltip) {
var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"';
return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>';
}
where executeFixedFunction is:
function executeFixedFunction(id) {
$('#' + id).uploadFile({
url:"/file/upload"
});
}
what the correct event to do this? I need to initialize a file-upload element everywhere SuperTD called
The users still using Firefox 3.5.
EDIT more context:
GridBuilder.render = function() {
// return from cache
var html = '';
// calls html += SuperTD( ... )
return html;
}
GridBuilder.renderTo = function(id) {
$('#'+id).html(this.render());
// I guess this is where I should initialize the file upload, but still, is there another way?
}
If you are already using jquery i would consider doing it this way:
function superTD (id, str, tooltip) {
return $('<td/>', {
id: id,
title: tooltip,
text: str
}).uploadFile({
url: '/your-url'
})
}
Then you can call appendTo method on superTD to insert it into table row
You can use a setTimeout function to delay the callback function.
function SuperTD(id,str,tooltip) {
var onwhat = 'onwhat="executeFixedFunction(' + "'" +id+ "'" + ')"';
setTimeout(function(){ executeFixedFunction(id) }, 1000);
return '<td><div id="' +id+ '" title="' +tooltip+ '" ' +onwhat+ '>' +str+ '</div></td>';
}
Everything put together with slightly modified Jakubs suggestion. See on Plunkr.
function superTD(id, str, tooltip, callback) {
var td = $('<td/>', {
id: id,
title: tooltip,
text: str
});
var up = $('<span/>'); // <-- this elm will be replaced
td.append(up);
$('#container').append(td);
callback(up, str);
}
function onCreated(elm, fname) {
elm.uploadFile({
url: '/url',
fname: fname
});
}
$(document).ready(function() {
superTD(1, 'foo', 'bar', onCreated);
superTD(2, 'bar', 'foo', onCreated);
});
Related
This is my render code function which is working
{
"data": "assignedTo",
"render": function (data) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + data + "'>" + data + "</a>";
return btnDetail;
}
},
However I want something like
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + data + "'>" + data + "</a>";
where user can see assignedTo but when they click it should got to the ticketId. In short i want both ticketId and assignedTo value in single colum. Please guide me.
You need to make use of row parameter from render function. It contains all values available for current row.
row The full data source for the row (not based on columns.data)
Read more about column rendering here.
{
data: 'assignedTo',
render: function (data, type, row) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + row.TicketId + "'>" + data + "</a>";
return btnDetail;
}
}
or you can ignore data completely if you want to use render function.
{
data: null,
render: function (data, type, row) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + row.TicketId + "'>" + row.assignedTo + "</a>";
return btnDetail;
}
}
All other values returned from server will be available through row parameter.
The idea for this page is to load the 'skills' from my java application and dynamically create a Delete button that allows me to delete those 'skills' from the application.
Error received when attempting to click the button to delete a skill.
manageTech:1 Uncaught ReferenceError: deleteMe is not defined at
HTMLButtonElement.onclick (manageTech:1)
js file:
$( document ).ready( () => {
var url = window.location;
// GET REQUEST
$("#btnGetFiles").click( (event) => {
event.preventDefault();
ajaxGet();
});
function deleteMe(id) {
window.alert("Button clicked, id " + id + ", text");
$.ajax({
url: '/api/technologyList' + '/' + id,
type: 'DELETE',
success: function() {
ajaxGet();
}
})
}
// DO GET
function ajaxGet() {
$.ajax({
type: 'GET',
url: '/api/technologyList',
success: function (skills) {
$.each(skills, function (i, skill) {
$('#listFiles').append('<tr>' + '<td>' + '<button ' +
'type="submit" ' +
'data-id="' + skill.id + '" ' +
'onclick="deleteMe('+skill.id+')"' +
'name="deletebtn">' +
'Delete' +
'</button>' + '</td>' +
'<td>' + skill.id + '</td>' +
'<td>' + skill.logo + '</td>' +
'<td>' + skill.techName + '</td></tr>')
})
}
});
}
});
Your deleteMe is not on the top level - it's inside your $( document ).ready( () => {, so it's not a global variable, so the inline handler onclick="deleteMe('+skill.id+')" fails. (Inline handlers can only reference global variables on the top level.)
Although you could fix it by moving deleteMe outside, inline handlers are bad practice; consider attaching an event listener properly using Javascript instead. Remove the inline handler, and use event delegation:
$('#listFiles').on('click', 'button[name="deletebtn"]', function() {
deleteMe(this.dataset.id);
});
I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}
I do not understand how to do the right thing.
With this query I get a JSON with the file names:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
With this query I get a JSON with the tag names:
$.getJSON("http://api.server.com/list/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<label class='radio'><input type='radio' name='list' id='" + result.List + "' value='" + result.List + "' checked>" + result.List + "</label>");
});
$('.my_list').html(results.join(""));
}
);
In the end, I need to display a list of files. Next to each file should to show a form with a file name and a list of tags:
$(document).on('click', '.share_file_form', function() {
$('.share_file_form').validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
All of this works.
The question is how to make sure that each form will work separately?
Now only works the first form. If you press the button on the other forms will still work the first form.
Your mistake is in the way you identify the form on which the user clicked. The following line is the problem:
$('.share_file_form').validate({
Independent of what you clicked on, you always will get the first form with this selector.
Here is what you need instead:
$(document).on('click', '.share_file_form', function(event) {
$(event.target).validate({
submitHandler: function(form) {
hmm. I 'think' I know what you want..
how about wrapping the second call in a method, or perhaps both, ala.
function fireJSON(){
var func1 = function(){
//your first json code
func2(); // call your second json code
}
var func2 = function(){
// second json code
}
return {
func1: func1
}
}
fireJSON().func1();
I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.