Onclick event only works on double click - javascript

My onclick event only works on double click. I searched the previous similar questions also but none of them worked. Please if anyone can help me with this.
function getDetails(tablename,field)
{
goToFind("0"+tablename);
var prntid=sessionStorage.getItem('prnt_id');
$.ajax({
url: 'addresses/getAddressDetails',
type: "post",
data: {'tablename':tablename,'fld':field,'prntid':prntid},
success: function(data){
var obj = JSON.parse(data);
res=res.split("|");
var str="<center><input type='button' value='Exit' onclick=javascript:window.close();opener.window.focus();></center><br/><table border=1>";
str+="<tr>";
for(var i=0;i<res.length;i++)
{
str+="<th>"+res[i]+"</th>";
}
str+="</tr>";
for(j=0;j<obj.length;j++)
{
str+="<tr>";
for(i=0;i<res.length;i++)
{
str+="<td>"+obj[j][res[i]]+"</td>";
}
str+="</tr>";
}
str+="</table>";
z = window.open('', 'popUp','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes');
z.focus();
z.document.open();
z.document.write(str);
}
});
}
Here I am calling my method from index page
<button class="w3-btn w3-brown" value='skip' onclick="getDetails('addresses','party_id')">Current Party Address</button>

Related

Bind textbox with response from onclick event - jquery

I have a textbox in my view page. when i click on imageIcon,it will take data from db and return in alert successfully. But, when i try to bind this response data to textbox, it is not binded correctly. My code in view page is as following :
#foreach (var dateitem in list)
{
<td id="HoursTxt">
#Html.TextAreaFor(modelitem => dateitem.Hours, new { id = string.Format("txtHours"), style = "width:50%;height:70%;" })
#Html.Hidden("CuDate", dateitem.Date)
<img src="~/Images/comment.png" class="prevtest" />
<div style="border:solid;display:none;">
<input type="text" id="TxtNotess" />
<input type="button" id="BtnComment" value="Save" />
</div>
</td>
}
In my onclick event of imageIcon jquery is following:
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId =parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
success : function(data)
{
alert(data);
$('#TxtNotess').val(data);
alert('success');
},
error:function()
{
alert('Error');
}
});
$(this).next().toggle();
});
the text box with id TxtNotess not bind with response value
Can anyone help me to do this..
Thanks in advance..
First: ID of an element must be unique so use class for the textfield TxtNotess.
<input type="text" class="TxtNotess" />
Then, in the success handler find the textfild with class TxtNotess inside the next sibling of the clicked element
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$(this).next().find('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
I gets resolved by using class name for textbox..

JSON information is looped once

So the problem is that I'm loading JSON files from url into my html and it's working perfectly besides for the fact that it shows the information twice..
Does anyone know why this is the case?
Here's the Jquery/Javascript code that I use to load the JSON into my html.
$.ajax({
url: 'http://datatank4.gent.be//bevolking/totaalaantalinwoners.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
i = 0;
var access;
var url;
$(data).each(function(index, value) {
wijkname = value.wijk;
year = value.year_2010;
i++;
$('#pagewrap2').append(
'<div class="dataond col col-xxs-12 col-md-3"> <h2> ' + wijkname + '</h2><p>' + year + '<div id="maps">' + "<iframe width='100%' height='100%' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&q="+ encodeURIComponent( wijkname + ' ' + 'Gent' ) +"&output=embed'></iframe>" + '</div>' + '</p></div>'
);
});
}
});
First check the response of this ajax call.
If the response look fine maybe you're making the ajax call twice.
For example when you add an event listener twice. (add off() function before click() if you're using jquery)
I've found the problem. Really stupid but I linked my file twice in my index.html...
Thanks everyone for your replies.
<script type="text/javascript">
$(document).ready(function() {
var categoriesId = [];
$.getJSON("http://datatank4.gent.be//bevolking/totaalaantalinwoners.json", function(data) {
$.each(data, function(index, item) {
categoriesId.push(item.wijk);
}
);
for (i = 0; i < categoriesId.length; i++) {
alert(categoriesId[i]);
var newInProductPriceDiv = document.createElement('div');
newInProductPriceDiv.setAttribute('id', "recentlyViewedProductPriceDiv" + i);
newInProductPriceDiv.setAttribute('class', "subcategoryListPriceDiv");
newInProductPriceDiv.innerHTML = newInProductPriceDiv.innerHTML + categoriesId[i];
document.getElementById('pagewrap2' + i).appendChild(newInProductPriceDiv);
}
}
);
}
);
</script>
if you have any confusion then tell me ok . and if you not get your exactly output then also tell me.

Button onclick event not firing on first click

I've checked around and read a couple articles on this issue and tried a few things but nothing seems to be working. The issue is when the button is clicked the first time nothing happens. The second time its clicked then the event and ajax request is fired off. In addition to having to click the button twice the ajax data is requested and displayed twice. Ive seen a few articles that said check the buttons visibility and if it is checking to turn off/on another elements visibility in this case its not. Additionally I have the onclick of the button calling a method to fire the ajax. Whats strange is when i removed the code from the method and place it in the DOM ready the event fires the first time but my ajax data never returns
Button HTML :
<input id="btnSearch" onclick="GetInfo();" type="button" value="Find ID" class="button-ffe" />
Here is the click code :
function GetInfo() {
var term = $('#txtUtente').val();
$('#btnSearch').click(function () {
var winW = window.innerWidth;
var winH = window.innerWidth;
var dialogoverlay = document.getElementById('dialogoverlay');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH + "px";
$.ajax({
url: 'DAL/WebService1.asmx/GetPTSID',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: term }),
dataType: 'json',
success: function (data) {
document.getElementById('dialogoverlay').style.display = 'none';
$('#infoFoundID').html(data.d[0]);
$('#foundInfoMessage, #userInformation').show();
$('#registerProductInfo').hide();
var partTable = $('#partTable tbody');
$(data.d).each(function (index, id) {
partTable.append('<tr> <td>' + id + '</td><td>' + '<input onclick="GetPartNumber();" id="Button1" type="button" value="Copy Number" />' + '</td></tr>');
});
},
error: function (err) {
console.log(err);
}
});
});
} //end getinfo
You are attaching the event in the first click, so the code runs like you write.
You can remove the first function definition :
var term = $('#txtUtente').val();
$('#btnSearch').click(function () {
var winW = window.innerWidth;
var winH = window.innerWidth;
var dialogoverlay = document.getElementById('dialogoverlay');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH + "px";
$.ajax({
url: 'DAL/WebService1.asmx/GetPTSID',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: term }),
dataType: 'json',
success: function (data) {
document.getElementById('dialogoverlay').style.display = 'none';
$('#infoFoundID').html(data.d[0]);
$('#foundInfoMessage, #userInformation').show();
$('#registerProductInfo').hide();
var partTable = $('#partTable tbody');
$(data.d).each(function (index, id) {
partTable.append('<tr> <td>' + id + '</td><td>' + '<input onclick="GetPartNumber();" id="Button1" type="button" value="Copy Number" />' + '</td></tr>');
});
},
error: function (err) {
console.log(err);
}
});
});
Your jQuery click function is in your GetInfo() function. Change your JS to:
var getInfo = {
init: function() {
$(document).ready( function() {
getInfo.click();
});
},
click: function() {
var term = $('#txtUtente').val();
$('#btnSearch').click(function () {
var winW = window.innerWidth;
var winH = window.innerWidth;
var dialogoverlay = document.getElementById('dialogoverlay');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH + "px";
$.ajax({
url: 'DAL/WebService1.asmx/GetPTSID',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: term }),
dataType: 'json',
success: function (data) {
document.getElementById('dialogoverlay').style.display = 'none';
$('#infoFoundID').html(data.d[0]);
$('#foundInfoMessage, #userInformation').show();
$('#registerProductInfo').hide();
var partTable = $('#partTable tbody');
$(data.d).each(function (index, id) {
partTable.append('<tr> <td>' + id + '</td><td>' + '<input onclick="GetPartNumber();" id="Button1" type="button" value="Copy Number" />' + '</td></tr>');
});
},
error: function (err) {
console.log(err);
}
});
});
}
};
getInfo.init();
Now you can change your html to:
<input id="btnSearch" type="button" value="Find ID" class="button-ffe" />
That should work.
So, the first click will run GetInfo() - which, adds a jQuery click listener (but doesn't run it)
then the second click runs the function defined in the click listener - and GetInfo - which adds ANOTHER instance of the jQuery stuff
then the third click runs the function defined in the click listener, twice - and GetInfo - which adds ANOTHER instance of the jQuery stuff
use focusableInTouchMode=false in xml it works for me

how to count total number of ajax response data sets inside for loop?

i am calling an ajax and output api response in textbox. I want count total number of data sets received(counteri) and display it each time i click a button. For example if i click the button first time i want to an alert display counteri=20 and next time i click button it display counteri=40 and... counteri=60.
Currently my code keeps showing 20 each time and not adding the values. could any one tell me how to fix this.Thanks
<script>
var maxnumId = null;
var counteri= null;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......"),
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
$(".galaxy").append("<div class='galaxy-placeholder'><a target='_blank' href='" + data.data[i].link +"'><img class='galaxy-image' src='" + ok.images.standard_resolution.url +"' /></a></div>");
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
//alert('www!'+i);
counteri=i;
}
}
});
counteri=counteri+counteri;
alert('counteri is now: ' + counteri);
}
</script>
<body>
<br>
<center>
<div id="myDiv"></div>
<div class="galaxy"></div>
<button id="mango" onclick="callApi()">Load More</button>
</html>
EDIT:
Adding this in start of success added up total number of records from ajax response
var num_records = Object.keys(data.data).length;
num_records2=num_records2+num_records;
alert('number of records:'+ num_records2);
and
var num_records2 =null; // outside function
Ajax are async calls.
Move the alert to just after the for. Not outside the success callback.
Looks like the problem is that you are setting counteri to the value of i instead of adding the value of i. Try this instead:
counteri += i;
Ajax calls are asynchronous. You should increment your counter on success, not outside of the ajax call. Something like this:
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Considering that your ajax request is executed with success, to get what you want you need to declare the i variable before for ( ....) loop as is the follow script:
var counteri = 0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Please ses here demo
EDIT
Also i have rechecked if the variable i is not declared before for(...) loop and works OK. So, the only fix is to remove counter=i from for(...) loop and to change the counteri=counteri+counteri; to counteri+=i;
Take in consideration that the ajax requests produce a number of different events that you can subscribe to. Depending of your needs you can combine this events to accomplish the desired behavior. The complete list of ajax events is explained here
EDIT2
After reading your comments, i see that you need the last value of i globally,
you need to add a second global variable too keep the sum of last i during all ajax requests.
To do this, id have added a minor change to answer:
var counteri = 0,
totali =0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri = i;
totali = totali + i;
alert('totali is now: ' + totali );
}
});
}
JSFiddle demo
EDIT 3
After your last comment, you need to add in the API response the number of returned rows. For this, you need to change for (i = 0; i < 100; i++) { to something like this:
var num_records = data.num_rows;
for (i = 0; i < num_records ; i++) {
or, without adding the number of rows in response
var num_records = Object.keys(data.data).length;
for (i = 0; i < num_records ; i++) {

jQuery dropdown not firing the delete button

In my small practice project, I have a dropdown with a delete button:
function getMessages() {
$.ajax({
type: "POST",
url: "/Message/GetMessageMethod",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(data) {
var jsonData = $.parseJSON(data);
var newHtml = "<table style='width: 100%;'class='table-hover'><tr><th>Message</th><th>Date Posted</th><th>Posted by</th></tr>";
for (var i = 0; i < jsonData.length; i++) {
newHtml += "<tr><td>" + jsonData[i].message + "</td><td>" + jsonData[i].date + " - " + jsonData[i].time + "</td><td>" + jsonData[i].name + "</td><td><div class='btn-group'>"+
"<a class='btn dropdown-toggle' data-toggle='dropdown' href='#'> Actions " +
"<span class='caret'></span></a>" +
"<ul class='dropdown-menu' role='menu'>" +
"<li role='presentation'><input type='button' role='menuitem' value='Delete' class='btn btn-danger delMsg'/></li>" +
"</ul></div></td></tr>";
}
newHtml += "<table>";
$('#txfMessage').html(newHtml);
}
});
};
But my delete button is not firing when I click on it... I have a break point in firebug, but its not reaching it...
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
What could be I doing wrong, I've been busy with this since yesterday but couldn't find anything... Help please!
Thank you in advance!
You need to use jQuery event delegation, because you are attempting to attach an event to an element which does not yet exist in the DOM.
Change:
$('.delMsg').on('click', function () {
to:
$(document).on('click', '.delMsg', function () {
Check out this link for more information.
Since the delete button is created AFTER the AJAX call, your "on" method does not attach the event to it. You may use the live method. It will account for elements created after the method is attached.
EDIT: By the way, this depends on the JQuery version. live still works. If you have to use on, use it correctly, like pointed out by Pierre Granger and Jamie Dunstan.
You have to do something like:
$('#txfMessage').html(newHtml);
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
i.e. bind each time you append new html elements, or use event delegation as in the other answers.

Categories