How to call onchage function in another function - javascript

How can I call onchage function in another function?
My first function:
$('.input-number').change(function() {
// my code here
}
and my second function:
$(function(){
$(document).on('change', '.destination', function() {
// my code here
$.ajax({
url: 'myurl',
data: mydata,
type: "post",
success: function(data){
// my code here
// here i must call $('.input-number').change(function()) to refresh my first code
}
});

You need to trigger the event programmatically using trigger() method.
$('.input-number').trigger('change');
// or use shorthandler
$('.input-number').change();

Related

Binding an each statement

If I wanted to bind each statement to the #container div how would I go about this?
Here is an example of the each statement im trying to code:
$.each($(".product-comment"), function (key, value) {
var showmoreHtml = $(this).html();
var showlessHtml = showmoreHtml.substr(0, 400);
if (showmoreHtml.length > 400) {
$(this).html(showlessHtml).append("<a href='' class='product-comment-more'> (...Show More)</a>");
}
$(this).on("click", ".product-comment-more", function (event) {
event.preventDefault();
$(this).parent(".product-comment").html(showmoreHtml).append("<a href='' class='product-comment-less'> (Show less)</a>");
});
$.ajax({
method: 'POST',
url: urlCreateReview,
data: form_data,
cache: false,
processData: false,
contentType: false,
success: function(data) {
$(".tab-comment-holder").load(" .tab-comment-holder");
},
You can call the jquery function on your selector, call .each() and pass a function:
$("#container div").each(function() {
//do something
console.log($(this));
});
EDIT:
Apparently the div is "reloaded" in the callback of an AJAX. The solution is to make sure its items are properly initialized inside the callback. There is an .each() for this purpose, but it uses commands such as
$(this).on("click", ".product-comment-more", function (event) {
//...
}
which creates a click handler for every tag having the class of product-comment-more each time, this means that if there are n such tags and a user happens to click on one of those, the click handler will be executed n times. It's better to create a single handler for each of them. showmoreHtml is not well defined.

Why function is executed 1 + n times when it should be executed once on click?

I'm adding eventListener like this:
var runSingleTest = document.getElementById('runSingleTest');
runSingleTest.addEventListener('click', sendSingeleTestCase);
When user click that button in my form following code is executed 1 + n times, where n is number of click on that button before.
function sendSingeleTestCase(){
var frm = $('#scriptCodeForm');
var btn = $('#runSingleTest');
saveScriptToLocalStorage();
frm.submit(function (ev){
$.ajax({
type: frm.attr('method'),
url: btn.attr('formaction'),
data: frm.serialize(),
success: function (data) {
console.log("Test would run once.");
}
});
ev.preventDefault();
});
}
It doesn't behaves as expected (executed many times when it should be only executed once).
Could you help me to understand possible reasons why it's not working as supposed?
Thanks!
You are connecting the submit handler inside a click handler. Separate those so that you only register the submit handler once.
e.g. something like:
function sendSingeleTestCase(){
saveScriptToLocalStorage();
}
var frm = $('#scriptCodeForm');
var btn = $('#runSingleTest');
frm.submit(function (ev){
$.ajax({
type: frm.attr('method'),
url: btn.attr('formaction'),
data: frm.serialize(),
success: function (data) {
console.log("Test would run once.");
}
});
ev.preventDefault();
});
Also note: As you are using jQuery, please convert your click handler to just this:
$('#runSingleTest').click(sendSingeleTestCase);
or place the handler code inside an anoymous function:
$('#runSingleTest').click(function(){
saveScriptToLocalStorage();
// Do other stuff
});

jQuery: using $(this) inside of $.ajax success function

I'm making an $.ajax call, and the following code does not work as intended. The alert results in 'undefined'
$(document).ready( function {
$(".elem").on("click", function(e) {
e.preventDefault();
$.ajax( {
url: 'index.php',
data: {
'action': 'something'
},
success: function() {
alert($(this).data("foobar"));
}
});
});
)};
However, I was able to get it working by adding an alias to $(this) before entering the ajax function.
$(document).ready( function {
$(".elem").on("click", function(e) {
var old_this = $(this);
e.preventDefault();
$.ajax( {
url: 'index.php',
data: {
'action': 'something'
},
success: function() {
alert(old_this.data("foobar"));
}
});
});
)};
I can't assign unique IDs to the element being clicked, so accessing it via $("#id") isn't an option.
Is there a more standardized approach to accessing the $(this) that existed before entering the success function or does this way work just fine?
The way that you have it is just fine. By default this in jQuery ajax callbacks is the ajax settings object (you can set via $.ajaxSettings). $.ajax also has a context property that you can set:
$.ajax({
url: url,
data: data,
context: this,
success: success
});
Then you could use $(this) as expected, but personally I find the reassignment of this easier to understand. You may want to pick a better variable name than old_this, though.

Can't access object made by ajax call

I have this ajax request:
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
});
as you can see it makes new row in #table. But this new objects made by ajax are not accessible from next functions. Result from ajax is not a regullar part of DOM, or what is the reason for this strange behavior?
$('#uid').on('click', function () {
alert('ok');
});
Use event delegation:
$(document).on('click','#uid', function () {
alert('ok');
});
Note that ajax calls are asynchronous. So whatever you do with the data you need to do it in a callback within the success function (that is the callback which is called when the ajax call returns successfully).
Jquery on doesn't work like that. Use have to give a parent which not loaded by ajax, and the specify ajax load element like this
$('#table').on('click','#uid' ,function () {
// what ever code you like
});
Is simple and complex at the same time. Simple to solve but complex if you are getting started with javascript...
Your event handler - onclick is being fired and bound to an object that doesnt yet exist.
So when you append the object to the #table, you need to set up your click handler as the object now exists.
So in your success part of the ajax return add the click handler event there.
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
Or how about you make it dynamic and create a function to do it for you.
function bindClick(id) {
$('#' + id).click(function() {
//Do stuff here
console.log('I made it here' + id);
});
}
Then:
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
bindClick(uid);
});
}
This is a super contrived example but you get the idea you just need to make the rest of it dynamic as well. for example some name and counter generated id number: id1, id2, id3...
Try it like this, add this $('#uid').on('click', function () { into the success
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
});

jQuery methods in $.ajax success handler don't work

I have a function:
$(".delete").click(function() {
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$(this).parent().parent().remove();
alert("hi");
}
});
});​
I have a problem when I delete the parent object. It just does not disappear. I tried to hide - did not help.
Alert is called normal.
How to solve?
Sorry for bad English.
You're inside another function with another this value by default. Pass the this value from the outer function with the $.ajax function as follows:
$.ajax({
context: this,
...
Because the this in the ajax success callback function is different from the click callback function. You could cache it to a local variable or use the $.ajax()'s context option.
$(".delete").click(function () {
var $this = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $this.attr("title"),
success: function () {
$this.parent().parent().remove();
alert("hi");
}
});
});
Have you tried setting the context: this, parameter in the ajax function.
When the success handler fires, the value of this won't be the same as it was before hand.
See here fore more: http://api.jquery.com/jQuery.ajax/
Try this:
$(".delete").click(function() {
$object = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$object.parent().parent().remove();
alert("hi");
}
});
});​

Categories