I'm quite new to webdevelopment and AJAX and I'm facing a little issue there. Basically, I have a form on my webpage. When I submit this form, it makes an AJAX call to my controller, send me the data I want back, and change the html content of the page.
JS code :
$(document).ready(function() {
$("#mydiv table tbody td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$('#myform').submit(function()
{
try {
var host = $("#host").val();
var port = $("#port").val();
var username = $("#username").val();
var password = $("#password").val();
var database = $("#database").val();
$.ajax({
type: "POST",
url: "/management/connectDatabase",
dataType: "JSON",
data: "host="+host+"&port="+port+"&username="+username+"&password="+password+"&database="+database,
cache: false,
success:
function(data){
$('#mydiv').html(show_tables(data));
},
});
return false;
}
catch(e){
console.debug(e);
}
});
});
function show_tables(data)
{
var html = '<div id="mydiv">';
html += '<table class="display" id="example">';
html += '<thead><tr><th>Tables</th></tr></thead><tbody>';
for (var tablesCount = 0; tablesCount < data.tables.length; tablesCount++){
html += '<tr class=gradeA id="trtest">';
html += '<td id="tdtest">' + data.tables[tablesCount] + '</td>';
html += '</tr>';
}
html += '</tbody></table>';
html += '</div>';
return html;
}
When I submit the form, the HTML is generating right, and I can see my content. But, I can't click on any entries of the <table>. Moreover, when I want to see the sourcecode of my page, it doesn't displays me the table, but still my form, even if it has still been validated.
Could someone explain me what I do wrong here ?
Depending on which jQuery version you're using, you need to either bind the click event using jQuery.delegate or jQuery.on in order for things to work with dynamically added DOM elements.
Edit: as pointed out by Geert Jaminon, you have to use the selector parameter of the on function. This works for me.
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
});
$("#mydiv table tbody").on('click', 'td', function() {
alert("You clicked my <td>!" + $(this).html() + "My TR is:" + $(this).parent("tr").html());
});
.live() is replaced by .on() in the newer jQuery versions.
http://jsfiddle.net/ZqYgv/
you need to bind the click event handler after the rendering of the elements, since they weren't in place when you made the binding.
If you insert data dynamically, you need to add the click event after the data has been inserted.
http://codepen.io/thomassnielsen/pen/FEKDg
$.post('ajax/test.html', function(data) {
$('.result').html(data);
// Add .click code here
});
Related
I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!
I'm currently trying to select a specific csv file based on user selection and then display this as a html table in the web page on the click of a button.
The steps that this will need to have are:
to select the options from a drop down which will be used to identify the csv file name
pass the csv file name to a function which displays this as a html table
perform this on the click of a button rather than when the web page loads
Below is the code I have so far, the first part of the code identifies the csv file name.
The second part reads in a hard coded csv file and parses it as a html table which is displayed when the web page opens.
<script>
function button_clicked(){
var obj_opt = document.getElementById("opt");
var opt = obj_opt.value;
if (opt==""){
alert("Please select Option1");
return;
}
var obj_opt_two = document.getElementById("opt_two");
var opt_two = obj_opt_two.value;
if (opt_two==""){
alert("Please select Option2");
return;
}
var urls= "http://mysite/" + opt + "_" + opt_two + ".csv";
alert("The link is: " + urls);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "http://mysite/Option1_Option2.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
<button type="button" onClick="button_clicked()">Load New File</button>
I am unsure how to combine the two javascripts to load the user selected csv as a table via a button, any help on how to do this would be greatly appreciated!
To make this work you need to move the $.ajax logic in to the button click handler, and apply the url value to it.
Also note that using on* event attributes in HTML is very outdated and should be avoided where possible. You should use unobtrusive event handlers instead. As you've already included jQuery in the page, you can use that:
$(function() {
$('#load').click(function() {
var opt = $("#opt").val();
if (!opt) {
alert("Please select Option1");
return;
}
var opt_two = $("#opt_two").val();
if (!opt_two) {
alert("Please select Option2");
return;
}
$.ajax({
type: "GET",
url: `http://mysite/${opt}_${opt_two}.csv`,
success: function(data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
});
function arrayToTable(tableData) {
var html = tableData.map(function(row) {
var rowHtml = '<tr>';
row.forEach(function(cell) {
rowHtml += `<td>${cell}</td>`;
});
return rowHtml + '</tr>';
});
return `<table>${html.join('')}</table>`;
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<button type="button" id="load">Load New File</button>
Finally, note that jQuery 1.7 is rather old now. I'd suggest upgrading to 1.12 if you still need to support older IE browsers, or 3.2.1 if not.
Move the
$.ajax({
type: "GET",
url: "http://mysite/Option1_Option2.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
in the place of
alert("The link is: " + urls);
I am trying to read a table when I click on total button,the button is created on ajax call with table I tried with both id attribute and input type submit selectors but I am not able to read the button,but when I tried to call javascript function on button click the javascript function is called,can anyone explain this and how should I read using jquery selectors
$.ajax({
type:'POST',
url:'/pos/addproduct',
dataType: "json",
data:JSON.stringify(order),
contentType: "application/json; charset=utf-8",
success:
function(data){
i++;
console.log(i);
$.each(data,function(index,value){
var temp = "qty" + data[index].barcodeid.trim();
var qtyitm=$("#"+temp);
if(qtyitm.length != 0){
qtyitm.html(data[index].qty);
//("#price"+(data[index].barcodeid.trim())).html(data[index].price);
temp = "price" + data[index].barcodeid.trim();
qtyitm = $("#"+temp);
qtyitm.html(data[index].price);
}
else{
var row=$("<tr><td>"+data[index].oid+"</td>"+"<td>"+data[index].pname.trim()+
"</td>"+
"<td id=\"qty"+data[index].barcodeid.trim()+"\">"+data[index].qty+"</td>"+
"<td id=\"price"+data[index].barcodeid.trim()+"\">"+data[index].price+"</td>"+
"<td>"
+data[index].barcodeid.trim()+"</td></tr>"
);
$("#firstrow").after(row).removeClass("hidden");
}
})
if(i==1){
var row1=$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
$("#order tbody").append(row1);
}
}
})
});
$('input[id="calculateTotal"]').click(function(event){
alert("hello");
})
Since the submit button #calculateTotal was added dynamically via js code in :
$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
You should use event delegation on() to attach click event to it, like :
$('body').on('click', 'input[id="calculateTotal"]', function(event){
alert("hello");
})
Hope this helps.
Browser parses your javascript code when your page is loaded and attaches event listeners to DOM elements in your initial loading (in that case your button does not exits as you simply attach it to existing DOM tree [hence no event bound] )
Solution is use $('document').on('event','selector','callback') so with you code :
var row1=$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
$("#order tbody").append(row1);
and in Js:
$('document').on('click','#calculateTotal',function(){
//do your stuff here
});
Hope it helps...:D
I'm trying to submit a rails form using jQuery (Which I know little about) and have had success in setting up a form to submit on clicking the submit button and run a callback(I believe this is the correct terminology?), but I would also like to make it work when just hitting enter.
As it stands, hitting enter will submit data to the database but will not run the commands to append the div or clear the text field. How could I make this happen so it works the same for the enter key as it does the submit button? I've tried to wrap the code inside a function that will run when enter is hit but having no luck!
function runScript(e) {
if (e.keyCode == 13) {
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
}
I tried that with no luck.
My current, button-working, JS file:
var scrollToBottom = function(anim){
var myDiv = $(".wrap");
myDiv.animate({ scrollTop: myDiv[0].scrollHeight - myDiv.height() }, anim);
};
$(document).ready(function(){
scrollToBottom(0)
//JS to POST form
$('.submit').click(function() {
var valuesToSubmit = $('.msgform').serialize();
$.ajax({
type: 'POST',
url: window.location.href + '/messages', //sumbits it to the given url of the form
data: valuesToSubmit,// { chat_id, <%= #chat.id %> },
dataType: "JSON", // you want a difference between normal and ajax-calls
})
.done(refresherFunc)
.fail(function(){
alert("Error sending message. It would be nice to make this a flash error.");
});
return false; // prevents normal behaviour
})
});
var refresherFunc = function(json) {
// Get debugging goodies.
console.log(json);
// Set variables with JSON object data
msg = json.msg;
foreign = json.foreign_speaker;
msg_translated = json.msg_translated;
//The HTML that we will append to the document.
html = "<div class='msg msg" + foreign + "'>" + msg +
"</div> <div class='msg msg" + foreign + "-translation'>" + msg_translated + "</div>"
// Append new message.
$('.chatmessages').append(html).fadeIn('fast');
scrollToBottom(500)
// Clear form with jquery.
$('#message_msg').val('');
$('#message_foreign_speaker').attr('checked', false);
}
Catch your form submit event with jQuery's submit() function and return false inside it. This function will be called any way you submit the form (clicking on submit button or pressing enter key). Returning false will prevent the browser from completing the form sumbittion which lets you do whatever you want with it.
See example: http://jsfiddle.net/vgk4wu46/
I'm having difficulty making a clickable button in my dynamically generated table that would send data specific to the table cell that was clicked.
My table is generated and modified whenever the user types into the search box with this AJAX call:
$(document).ready(function(){
$("#data").keyup(function () {
$.ajax({
type: "POST",
dataType: "JSON",
data: "data=" + $("#data").val(),
url: "search1.php",
success: function(msg){
var output = "";
for(var i = 0; i < msg.length; i++) {
output += '<tr onmouseover=this.style.backgroundColor="#ffff66"; onmouseout=this.style.backgroundColor="#F0F0F0";>';
output += '<td>';
if (msg[i].website != ''){ output += '' + msg[i].name + '</td>';}
else output += msg[i].name + '</td>';
output += '<td class="description">' + msg[i].description + '</td>';
output += '<td><input type="button" onclick=' + submit() + ' value=' + msg[i].id + '></td></tr>'; // Here is where I'd like to put in a clickable button
}
$("#content").html(output);
$("#myTable").trigger("update");
}
});
});
});
If I make submit() simply alert("hello") it runs when the page is loaded for every instance of the onclick call to submit(). Could someone please explain to me how to make submit only get called when its button is clicked and not on page load. Thanks in advance.
You have to put the submit() call in a quoted string. Same goes for the msg[i].id. All values in HTML should be quoted.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
You are trying to assign submit() to the button's onclick, but you are actually calling the function when you generate the string output. It needs to be in quotes inside the string, not concatenated in.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
//----------------------------------------^^^^^^^^^^^^
A better strategy would be to leave out the onclick attribute entirely, and use jQuery's .on() to dynamically assign the method. It is often considered a better practice to bind events dynamically rather than hard-code them into HTML attributes.
// No onclick attribute in the string:
output += '<td><input type="button" value="' + msg[i].id + '"></td></tr>';
// And a call to .on() in the $(document).ready()
$('input[value="'+msg[i]+'"]').on('click', function() {
submit();
});