I have a list of items and I want to do something whenever one of the items is selected, but the problem is that the check-box's change function is not working with me.
I have checked the code inside the function and it's working fine outside the change event. i'm not sure of the reason why it's not working but what could it be other than the function its self ?
Here the change function:
$("input[name='checkCoResult']").change(function () {
if (this.checked) {
$("#searchResultSecond").attr("style", "opacity: 0.6");
$("#searchResultSecond *").attr("disabled", "disabled").off('click');
}
});
and this is the code that generate my list:
$.ajax({
url: "CCDMSWebService.asmx/getCoSearchResult",
data: JSON.stringify(objectData),
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Result = response.d;
contantDiv.text("");
$.each(Result, function (index, val) {
contantDiv.append('<div class="panel-bod"><label style="margin:2px; border-radius: 10px;border: 1px solid #cc0000;padding: 5px;"><input type="checkbox" value="' + val.companyID + '" name="checkCoResult" class="nnn"> '
+'<img src="images/' + val.companyID + '.png" alt="company logo" width="30%" height="30%">' + val.companyName + ' provides all your needs</label></div>');
})
},
failure: function (msg) {
alert(msg);
}
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). In your case it seems you already have a div named contantDiv present in your page, so modify your code like
contantDiv.on("change","input[name='checkCoResult']",function(){ ...
Check out http://api.jquery.com/on/#direct-and-delegated-events for more details.
if your content is dynamic then try
$(document).on("change","input[name='checkCoResult']",function(){
// your code
});
Related
I have a column in my jQuery datatable that renders a green checkmark link if data == true or a red X if data == false:
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '#Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '';
}
return '';
}
},
The problem is that when I click one of the links (either green checkmark or red X), it navigates to another page. I know that this is because I am using href and Url.Action.
When a user clicks one of the links, I want to call the /Payment/Set method to update the data (green checkmark to red X and vice versa) and then I want to redraw my datatable (i.e. dataTable.draw()) without navigating from the current page (i.e. Index view). /Payment/Set method updates the data without returning anything (i.e. void).
Update: I tried the following and it almost works, meaning that when I click one of the links, the data is updated and the datatable is refreshed, except it still tries to navigate to another page.
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '#Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '';
}
return '';
}
},
<script>
function onclickFunction() {
$.ajax({
type: "GET",
url: $(this).attr("href"),
success: function () {
paymentDataTable.ajax.reload();
}
});
}
</script>
If you use an anchor <a> it is obvious that the browser will navigate to another page. That's the actual purpose of the anchor tag.
You should use an AJAX function to call when your button is pressed and at the callback call the reload of the table.
This can be a way:
{
data: "HasPayment",
render: function (data, type, row) {
if (data) {
return '<button class="fas fa-solid fa-check" style="color: green" onclick="setPayment(row.Id, row.Year, row.Month, data)"></button>';
}
return '<button class="fas fa-solid fa-times" style="color: red" onclick="doSomethingElseMaybe()"></button>';
}
}
Then you should create two more functions, one with the AJAX call and one with the table reload to be called as callback.
function setPayment(id, month, year, data){
var url = `Payment/Set?applicationId=${id}&year=${year}&month=${month}&hasPayment=${data}`;
$.ajax({
type: "POST", //OR GET? it depends on your backend
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
reloadTable();
},
error: () => {
console.error("500 Internal Server Error.");}
});
}
Then in the reloadTable function just call the ajax.reload() method of the DataTable api.
for example
function reloadTable(){
datatable.ajax.reload();
}
Here is the documentation of DataTables reload method.
Here is the documentation of JQuery AJAX.
You may have to adapt the example code to your specific backend purpose.
I want to make a clickable link in my ajax success response. But I could not do this.
<td id="attachment"></td>
function DoAction(id) {
$.ajax({
type: "get",
url: "/view_message",
data: "id=" + id,
dataType: 'json',
success: function(data) {
if (data) {
var text = "No Files There !";
$('#myModal').modal('show');
$('#subject').text(data.subject);
$('#body').text(data.body);
$('#created_at').text(data.created_at);
if (data.attachment) {
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
} else {
$('#attachment').text(text);
}
}
}
});
}
I want to display a clickable link in my .
I always encounter this when using ajax calls so;
Update your code from this.
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
To This.
$(document).find('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
if the code doesn't work add a console.log("working") function to see if your code is really reaching the success function.
I hope it helps.
I need to make list (like ng-repeat in angularjs) and click on any of item in list, call function with passed data of the selected item
I make list with $.ajax call and $.each
$(document).ready(function() {
var inHTML = "";
$.ajax({
url: 'http://some.some',
dataType: "json",
success: function(data){
$("#dynamicTable").append('<tr><th><h5 style="margin-left: 15px; margin-top: 15px;">' + "Events" + '</h5></th></tr>');
$.each(data.videos, function(key, value){
$("#dynamicTable").append('<table><tr><td class="aktivniItem backgroundIdKlupa_izbornik_td" style="color: white">'+ moment(value.time).format('DD-MM-YYYY HH:mm:ss') +'</td><tr></table>').click({param1: value.href}, setSourceToVideoPlayer);
});
function setSourceToVideoPlayer(event){
alert(event.data.param1);
}
}
});
});
and in HTML
<table id="dynamicTable" class="table-hover"></table>
Problem is, with this code, when I click on any of item in list I get alert with passed datafor all items, one-by-one, not only for clicked.
Please try below code. I have given the only idea, it might be possible some syntax error.
$(document).ready(function() {
var inHTML = "";
$.ajax({
url: 'http://some.some',
dataType: "json",
success: function(data){
$("#dynamicTable").append('<tr><th><h5 style="margin-left: 15px; margin-top: 15px;">' + "Events" + '</h5></th></tr>');
$.each(data.videos, function(key, value){
$("#dynamicTable").append('<table><tr><td class="aktivniItem backgroundIdKlupa_izbornik_td" data="' + value.href + '" style="color: white">'+ moment(value.time).format('DD-MM-YYYY HH:mm:ss') +'</td><tr></table>');
});
$(".aktivniItem").click(function (){
alert($(this).attr("data"));
});
}
});
});
Only way I can get this to work, for now, is with event.stopImmediatePropagation();
function setSourceToVideoPlayer(event){
alert(event.data.param1);
event.stopImmediatePropagation();
}
Here is detail about this. If this is not a good way to do this, pls tell me. Thnx
I am aware that this question has been asked before and I had the solution working last week based on the responses in the answers provided, nothing has changed and all of a sudden the jquery has stopped working.
I am using an Ajax call (below) that returns me a string that I assign to a hidden link on a page to force the download of a file from my works LAN.
$(document).ready(function () {
$(".excelLoader").hide();
$('.extract')
.on('click',
function () {
var rh = Number($(this.id).selector);
console.log("clicked: " + rh);
var loader = "load_" + rh;
var excel = "excel_" + rh;
console.log(loader);
$("." + excel).hide();
$("." + loader).show();
var params = {
responseHeaderId: rh
}
$.ajax({
type: "POST",
url: "SubmissionTracker.aspx/ExportFile",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#hiddenLink").attr("href", data.d);
console.log($("#hiddenLink").val());
$("#hiddenLink").click();
$("." + excel).show();
$("." + loader).hide();
},
error: function (data) {
console.log("error :" + data);
console.log(data);
$("." + excel).show();
$("." + loader).hide();
}
});
});
})
the issue that I have now is that the href is not being set, so the click event fires but with nothing to fetch.
The line I believe to be the issue is $("#hiddenLink").attr("href", data.d);
the line it is trying work with in my ASP.Net Webforms page is <a id="hiddenLink" href=""></a>.
I have cleared my Cache, removed any temporary files that may have existed but still cannot reproduce the positive results I had last week.
Any and all help bery much appreciated.
-----------update----------------
issue appears to be on the click event of the link. JQuery that I am usering is version jquery-1.11.3.js which is referenced first, and the js file where this is referenced is in the middle of all the other referenced files.
I have a function for getting records from database on keyup event.
Here is my code:
function displaySearch(key) {
$.ajax({
type:"POST",
url:"searchprofile.php",
data:{
k:key
},
success:function(data){
var details_arr=data.split("+");
$('.searchresult').empty();
for(var i=0;i<details_arr.length-1;i++){
$('.searchresult').append("<div class='profile' id='searchprofile'><img class='profilepic' src='images/profile.jpg'/><div class='doctorname'><div class='pname' onclick='saveName("+details_arr[i]+")'>"+details_arr[i]+"</div></div></div>");
$('.searchresult').show();
$('.searchresult .profile').show();
}
details_arr.length=0;
}
});
}
But i am getting javascript error here saying "Unexpected token ILLEGAL".
How do i give the onclick function with the value of details_arr[i]?
Please help.
As you have jQuery, you really shouldn't inline code. As you see it makes it more difficult to handle quotes inside quoted strings (yes, you're missing quotes around your argument to saveName).
You may do this :
(function(i){
$('.searchresult').append(
"<div class='profile' id='searchprofile'>"
+ "<img class='profilepic' src='images/profile.jpg'/>"
+ "<div class='doctorname'>"
+ "<div id=someId class='pname'>"+details_arr[i] // <- give some Id
+"</div></div></div>"
);
$('#someId').click(function(){saveName(details_arr[i])});
})(i);
$('.searchresult').show();
Note that I used a closure to ensure that i has the needed value in the callback (not the value at end of iteration).
Be careful with the split: on most browsers "+aaa".split('+') makes ["", "aaa"] and as you don't iterate up to the end of the array, this sample string would made you iterate on nothing.
function openNow(x)
{
var pageUrl = '<%=ResolveUrl("~/OnFriends.php")%>'
$.ajax({
type: "POST",
url: pageUrl + '/CreateNew',
data: '{k: "'+ x +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(data)
{
<---Now Do Your Code Hear--->
}
});
}
CreateNew is my web service what i created in .php file
I would use something like that
bare in mind ID must be unique inside a document (HTML Page)
because the content is generated on the fly; it's better to use the JQuery "on"
$(".pname").on("click", function (event) {
saveName($(this).text());
});
event handler to bind the click event
function displaySearch(key){
$.ajax({
type: "POST",
url: "searchprofile.php",
data: {
k: key
},
success: function(data) {
var details_arr = data.split("+");
var searchResults = "";
for (var i = 0; i < details_arr.length - 1; i++) {
searchResults += "<div class='profile'>" +
"<img class='profilepic' src='images/profile.jpg'/>" +
"<div class='doctorname'>" +
"<div class='pname'>" + details_arr[i] +
"</div></div></div>";
}
$('.searchresult').html(searchResults).show();
}
});
}
$(".pname").on("click", function (event) {
saveName($(this).text());
});
use the Jquery html to replace everything inside searchresult outside the loop that way it
will be called once not details_arr.length - 1 times
you should tell the line at which you are getting error
i think you did not specified you web service in ajax call at...
"url:"searchprofile.php"
Finally got the onclick function working. :)
Instead of appending the div everytime, i just editted my php page by adding the html i needed in the data that is returned in ajax.