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();
});
Related
Passing one parameter (report.id) to removeUser function works fine, but when I want to pass two parameter (report.id and report.name) I get Uncaught SyntaxError: Invalid or unexpected token.
I tried '(" +report.id +","+ report.name +")'
I tried '(" +report.id report.name +")'
but none works, what I am doing wrong here
$.ajax({
url: "xxx",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, report) {
html += '<tr>';
html += '<td>' + report.id + '</td>';
html += '<td>' + report.name + '</td>';
html += "<td><a onClick='removeUser(" +report.id + report.name +")'" + "'> Remove </a></td>";
html += '</tr>';
});
$('#users').html(html);
},
function removeUser(id, name) {
alert("ID: "+ id + "Name: "+ name)
}
You need commas between the parameters, and you need quotes only around report.name.
It's much easier to write this using a template literal rather than concatenation.
html += `<td><a href="#" onClick='removeUser(${report.id}, "${report.name}")'> Remove </a></td>`;
Also, since you're doing this with an a element, you should set its href so it doesn't try to link to another page after running the onclick function.
Is it possible send an AJAX request when a form is submit, then show a list below the form? If use razor foreach my page will be reloaded. I would use a PartialView to solve that problem.
Can I use AJAX to submit and return the list? If the AJAX request is successful, I could create the code bellow.
for (int i = 0; i < data.lenght; i++) {
$('#MyElement').append('tr' +
'<td>' + data.Id + '</td>' +
'<td>' + data.Name + '</td>' +
+'</tr>');
}
I tried it, but without success. I would like to know if it is possible, or just PartialView.
First of all, change lenght to length. Check if data is properly fetched by using console.log(data) (check your browser console). if the data is printed in the console and you still can't loop and append the data to HTML DOM, then use this :
$.each(data,function(index, dataValue){
$('#myElement').append('<tr>'+'<td>' + dataValue.Id + '</td>' + '<td>' + dataValue.Name + '</td>' + '</tr>'
)
})
I'm trying to run this ajax method for multi select drop down:-
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
},
async: false
When i use the static multi select drop down on the html it works without red box, image shown as below :-
And which is not working is shown in red box:-
These scripts i'm using :-
<link href="~/css/jquery.multiselect.css" rel="stylesheet" />
<script src="~/js/jquery.multiselect.js"></script>
<script src="/js/jquery.min.js"> </script>
The issue as i see is that in case of dynamic my scripts runs before page load and thus this dynamic ajax don't show drop down,but in case of static multi select drop down it works because this drop down is before the page loads and thus the script runs over it how do i run ajax before page call or before these scripts run.
Just call your .selectMultiple event function in your ajax success method after inserting your select tag in DOM
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
$('#langOpt3').selectMultiple(
//your code
);
}
I've set up an Ajax request to the Ebay API using Jquery, which works while I have a search term/keyword hardcoded, but I cannot figure out how to write the code to make my (bootstrap) button trigger the Ajax request using the search form input. I've tried various things to no avail. I'm completely new to this and this is my first time making an Ajax request and using JQuery so hopefully this makes sense.
Jquery:
$(document).ready(function() {
url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=rare soul 45"; //This would get deleted?
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I'm a bit surprised you managed to get an ajax request running but you struggle with registering a click event handler. :) but here we go...
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
// get the input value with:
var searchstring = $('input[type="text"]', this).val();
// your ajax request, using the variable above
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
It looks like you are making that ajax call upon document ready which is not really what you want. You want to make that call upon a button press event. So I would do this.
Put that ajax call into a function that you can call
Give the button an id
On document ready, use jquery to attach an event handler to the element with the id in step 2 above that triggers a call to your function mentioned in step 1 above.
Then, don't forget to extract the value in the field from the event and place it into the called ajax function as a parameter.
Given your current HTML, you can call a click event on your submit button like this...
$('button[type="submit"]).on('click', function(event) {
/*
since the button is of type "submit",
prevent the default behavior. Which,
in this case, is to submit the form.
*/
event.preventDefault();
//Check your browser's console to see what this is
console.dir(event);
//insert AJAX code here
});
This code uses the jQuery .on() method to capture the given event, 'click', on a given element $('button[type="submit"]'). Once this event has been captured, you can access it as event, or name of your choice, within the function.
This event object contains information regarding the event itself. It can be quite daunting at first, but I encourage you to look through a console.dir(event); call. More specifically, e.currentTarget/e.target, and view to get a sense of what is going on. From there you can look into what the difference is between some things that seem the same and get as familiar with it as you'd like.
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
});