Here is my javascript code, the event is onkeyup for many row of table !
function product(id)
{
$('#customers2').find('tr').click( function(){
var clicked = this;
});
var row = $(clicked).find('#tempnow').val();
if (row == "noncheck"){
$(clicked).find('#ett').val("");
$(clicked).find('#ett').prop("disabled", true);
}
else{
$(clicked).find('#ett').prop("disabled", false);
$.ajax({
url:baseurl+"/getinform/",
type: "POST",
dataType: "json",
data: {masp : id},
success:function(data) {
var thue = data['pcs_cl_pd_thue'];
$(clicked).find('#tyu').css("color", "red");
$(clicked).find('#tyu').val(thue);
}
});
}
}
When i use firebug, variable clicked is not defined ?
var clicked; // Define it outside
$('#customers2').find('tr').click( function(){
clicked = this; // Give it a value on click, from inside a function
next() // Now it has a value, call another function that'll do something with it
});
function next(){
$(clicked).find('#ett') // It works!
}
Related
I have two ajax functions that one is recursively working at loop and other is working when click event invoked. I tested both of the functions that are able to work properly. But when i start recursive function button event is not invoked.
Function that works on click event GET Content from ActionResult (MVC)
function UpdateRequests(url, state, id, cell)
{
$.ajax({
type: "GET",
url: url + id,
success: function (result) {
if (result == "OK")
{
cell.fadeOut("normal", function () {
$(this).html(state);
}).fadeIn();
}
else if(result == "DELETE" || result == "CANCEL")
{
cell.parent().fadeOut("normal", function () {
$(this).remove();
});
}
else
{
$(".modal-body").html(result);
$("#myModal").modal();
}
},
error: function () {
alert("Something went wrong");
}
});
}
Recursive function GET partial view from ActionResult (MVC)
function RefreshRequests()
{
if (isListPage())
{
var id = PageId();
var url = "/Home/List/" + id;
}
else
{
var url = "/Home/Index";
}
$.ajax({
type: "GET",
url: url,
success: function (data) {
$(".ajaxRefresh").html(data);
EditPageHeader();
},
complete: function () {
setTimeout(RefreshRequests, 2000);
}
});
}
Click event
$(".tblRequests").on("click", button, function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
Main
$(document).ready(function () {
EditPageHeader();
RefreshRequests();
ButtonEvent(".btnPrepare", "/Home/Prepare/", "PREPARING");
ButtonEvent(".btnApprove", "/Home/Approve/", "APPROVED");
ButtonEvent(".btnCancel", "/Home/Cancel/", "CANCELED");
RefreshRequests();
});
Assumptions:
The Ajax Calls bring you data that end up as HTML elements in the modal body.
These new elements added above need to respond to the click event (the one that doesn't work correctly right now)
If the above 2 are true, than what is happening is you are binding events to existing elements (if any) and new elements (coming from API response) are not bound to the click event.
The statement
$(".tblRequests").on("click", button, function (e) {
...
})
needs to be executed every time new elements are added to the body. A better approach for this would be to define the event handler as an individual method and then bind it to each new element.
var clickHandler = function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
}
// Then for each new record that you add
$(".tblRequests").on("click", button, clickHandler);
It would be helpful if you can try to explain what exactly you are trying to achieve.
Problem is that the $(this) will hold all elements of the selector. And will also now with one as it will be triggered one time and then never again. Also as can be seen from here, delegate events should be at the closest static element that will contain the dynamic elements.
function ButtonEvent(button, url, state)
{
$("body").on("click", button, function (e) {
e.preventDefault();
var button = e.target;
var id = $(button).data("id");
var currentRow = $(button).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
}
$function(){ and $window.onload() - I'm not sure how to handle this? On the $('#ashift').on('click',function(){ I need the ajax call to fire again? should I wrap it in a function and call the function on page load and then again in the click event, or is there a better way - I need the clicked_shift variable to update in the ajax call.
<script id="source" language="javascript" type="text/javascript">
var clicked_shift = "C";
$('#ashift').on('click', function(){
clicked_shift = "A";
});
$(function () {
$.ajax({
url: 'county.php',
data: {action:"tt"},
dataType: 'json',
success: function(data){
alert(clicked_shift);
$.each(data, function(key, val) {
if (val.completed == 1) {
color = "green";
} else {
color = "red";
}
if (val.Shift == clicked_shift){
$('#station'+val.Station+' .snum').append("<span style='color:"+color+"'>" + val.LastName + "</span><br/>");
}
});
}
}); // end ajax
}); // end of function()
</script>
var clicked_shift = "C";
function ajaxCall(){ // function declaration
console.log("clicked_shift",clicked_shift);
}
$(function () {
ajaxCall(); // call function ondomready
$('#ashift').live('click',function(){
clicked_shift = "A"; // change variable value
ajaxCall(); // re-invoke the function
});
}); // end of function()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="ashift">click</div>
$(function(){}); is like $(document).ready(function(){}); a self invoked anonymous function which will be triggered when dom is fully loaded. To re-invoke a function later, you need to declare it or to assign it to a variable.`
I have done an auto complete such that when I click the selected result it appends to a div.
image when picking a vehicle
But when I navigate away from that popup and return to it. When I do a search and click the result I want, it appends two values at a go with the second one as empty like in the next image.
the second image with a blank value
How do I prevent this from happening ?
My code is as shown below:
$(function(){
$(".search1").keyup(function() {
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!=''){
$.ajax({
type: "POST",
url: "assets/ajax/search1.php",
data: dataString,
cache: false,
success: function(html){
$(".resultgeter").html(html).show();
}
});
}return false;
});
$(document).on('click', ".showing" , function() {
var vhlid = $(this).html();
$(".searchid").append('<div class="choice"><div class="pickVehicle">'+vhlid+'</div><div class="select2-search-choice-close"></div></div>');
$(this).html("");
this.html = "";
$(this).remove();
$(".resultgeter").fadeOut();
return false;
});
$('.search1').click(function(){
$(".resultgeter").fadeIn();
return false;
});
});
I don't know the real solution for this, but a trick might work.
Adding an if statement to make sure vhlid is not blank while appending.
$(document).on('click', ".showing" , function() {
var vhlid = $(this).html();
if(vhlid!=" " || vhlid.length>1) {
$(".searchid").append('<div class="choice"><div class="pickVehicle">'+vhlid+'</div><div class="select2-search-choice-close"></div></div>');
}
$(this).html("");
this.html = "";
$(this).remove();
$(".resultgeter").fadeOut();
return false;
});
I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/
I want after click on link show alert box with tow option ok and cancel, if user click on button ok return it function is true and if click on button cancel return it function is false, problem is here that after click on link always return is true. How can fix it?
Example: http://jsfiddle.net/MaGyp/
function myalert() {
var result = true;
var $alertDiv = $('<div class="alert">Do you want to delete this item?<button class="ok">ok</button><button class="cancel">cancel</button></div>');
$('body').append($alertDiv);
$('.ok').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
result = true;
});
$('.cancel').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
result = false;
});
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display', 'block');
return result;
};
$('.iu').click(function () {
alert(myalert());
if (myalert() == true) {
alert('ok')
} else {
alert('no')
}
});
Update:
...
$('.iu').click(myalert)
function callback(result) {
//
if(result){
alert(result);
$('.image_upbg').each(function(){$(this).removeClass().addClass(unique())});
var get_class = '.'+$(this).closest('div').attr('class');
var get_val = $(this).closest('a').find('input').attr('value');
//alert(get_val);
var val = 'val_upimg1=' + get_val;
$(get_class).fadeOut('slow');
$.ajax({
type: "POST",
dataType: 'json',
url: 'delete_upimg',
data: val,
cache: false,
success: function (data) {
$(get_class).fadeOut('slow');
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
}else{
alert('no')
}
}
If you want to keep it structured like this, you could use a callback after the user responds.
http://jsfiddle.net/MaGyp/2/
function myalert() {
...do stuff here
$('.ok').click(function () {
callback(true); // callback when user clicks ok
});
$('.cancel').click(function () {
callback(false); // callback when user clicks cancel
});
}
$('.iu').click(myalert);
function callback(result) {
alert(result);
}
As suggested by Ben you could improve this by making the callback function a parameter to the first function to remove the tight coupling.
myalert() returns before result is set to true or false. To fix it I suggest having myalert() take a callback function as a parameter, and calling it inside the click() handlers within myalert(). The .iu event handler will then need to be split into two functions, one of which is the callback passed into myalert().
you are not waiting for the ok and cancel clicks so would always return true.
Modified the fiddle - http://jsfiddle.net/MaGyp/3/
function myalert() {
var result = true;
//var hide = $('.alert').fadeOut(100);
//var css = $('#appriseOverlay').css('display','none');
var $alertDiv = $('<div class="alert">Do you want to delete this item?<button class="ok">ok</button><button class="cancel">cancel</button></div>');
$('body').append($alertDiv);
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display','block');
return result;
};
$(document).ready(function(){
$('.ok').live('click',function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display','none');
alert('ok');
});
$('.cancel').live('click',function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display','none');
alert('cancel');
});
$('.iu').click(function() {
myalert();
});
})