Jquery event is not always triggered - javascript

I have a Jquery event which does not trigger every time:
http://jsfiddle.net/LphjL/
My code:
thisWebsite = websiteInitialization ();
function websiteInitialization () {
companyName = "name";
var thisWebsite = new websiteConstructor(companyName);
return thisWebsite;
}
function websiteConstructor(companyName) {
this.companyName=companyName;
}
function ajaxUpdateDB(websiteElement, value) {
return $.post('/echo/html/',{html: "<p>Text echoed back to request</p>",delay: 3}
,function(a){}
,"json"
);
}
function updateDatabase(websiteElement, value) {
var promise = ajaxUpdateDB(websiteElement, value);
promise.complete(function () {
thisWebsite[websiteElement] = value;
});
}
$(document).ready(function() {
$(".websiteElement").change(function() {
updateDatabase( $(this).attr('id'), $(this).val() );
});
$("#infos").click(function() {
htmlCode = "<input class='websiteElement' id='companyName' type='text' value='"+thisWebsite.companyName+"'>";
$("#panel-content").html(htmlCode);
});
$("#homepage").click(function() {
htmlCode = "homepage";
$("#panel-content").html(htmlCode);
});
});
​
As you can see in the jsfiddle, the first time the input field is updated the Ajax is triggered, but:
if you click on 'Homepage', then click back on 'Generic infos' and update the input field again this time the Ajax is NOT triggered: $(".websiteElement").change event is not called the second time.

You need to bind the event using event delegation, or rebind the event after you replace the element. Below is the event delegation option:
$("#panel-content").on("change",".websiteElement",function() {
updateDatabase( $(this).attr('id'), $(this).val() );
});
If the event is bound directly on the element, the event will be lost when the element is replaced/removed.

Related

Get selectize.js original element

I'm using selectize.js something like this:
$( 'select' ).selectize( {
onChange: function( value ) {
// how to get original element here?
}
} );
There's several select elements on the page.
I want to get select on which the event occurred inside of onChange.
How can I do it?
you can use $(this)[0] inside the onChange. Once this is the selectize object by itself
$( 'select' ).selectize( {
onChange: function( value ) {
var obj = $(this)[0];
alert(obj.$input["0"].id);
}
} );
Here's a Fiddle
you can get all user events from onInitialize :
$('select').selectize({
onInitialize: function (selectize) {
selectize.on('change', function (value) {
var elem = this.$input[0];
console.log('on "change" event fired > ' + elem.id);
});
selectize.on('focus', function () {
console.log('on "focus" event fired');
});
selectize.on('dropdown_open', function () {
console.log('on "dropdown_open" event fired');
});
}
}

jQuery trigger change event function

I have a change function in javascript who permit me to do an action when the user click on a chekbox who's name is "nameCheckbox" so i have this script.
$("input[name='nameCheckbox']").each(function()
{
var object = creatObject($(this).val());
$(this).change(function()
{
if($(this).is(':checked'))
{
var object = creatObject($(this).val());
}
else
{
object.remove();
}
});
});
But i want to have another checkbox who permit to check or uncheck all the checkbox who's name is "nameCheckbox" and pass by the function change of all the element. So i have this code.
$("[name='allCheck']").change(function()
{
var selectAll = false;
if($(this).is(":checked"))
{
selectAll = true;
}
$("input[name='nameCheckbox']").each(function()
{
if(selectAll)
{
$(this).prop('checked',true);
}
else
{
$(this).prop('checked',false);
}
//And here i want to do something like $(this).change();
});
});
Thank you
$(this).change() should work, according to change()
Description: Bind an event handler to the "change" JavaScript event,
or trigger that event on an element.
This is effectively the same as using trigger()
$(this).trigger('change');

how to get the user input from prompt

I have this code (in jQuery Impormptu):
var statesdemo = {
state0: {
title: 'Name',
html:'<label>name <input type="text" name="name" value=""></label><br />',
buttons: { Next: 1 },
submit:function(e,v,m,f){
console.log(f);
e.preventDefault();
$.prompt.goToState('state1');
}
},
state1: {
title: 'choice',
html:'<label>choice: <select name="travel" multiple>'+
'<option value="1" selected>1</option>'+
'<option value="2">2</option>'+
'</select></label>',
buttons: { Back: -1, Done: 1 },
focus: 1,
submit:function(e,v,m,f){
console.log(f);
e.preventDefault();
if(v==1) {$.prompt.close();}
if(v==-1) $.prompt.goToState('state0');
}
}
};
and with simple jquery I have this snippet:
$('#id').bind("dblclick", function() {
console.log('target id: ' + event.target.id);
f = $.prompt(statesdemo);
});
how can I get the user input when the prompt is finished?
the $.prompt does not return anything.
Also, the problem is that the $.prompt is a non blocking function. so the programs continues without waiting the user input.
try something like this
$('#my_a').click(function() {
f = $.prompt(statesdemo);
if(f.name!==undefined){
console.log(f.name);
}
if(f.travel!==undefined){
console.log(f.travel);
}
});
I've created a demo with an extra button that logs user input.
You can achieve this by creating an object to contain user input within Impromptu objects.
var userInput = {};
Next, create a function that takes a form input change event, and assigns the input's current value to a property in the object we just created with the same name as the input.
function registerUserInput( changeEvent ){
var input = changeEvent.target;
userInput[ input.name ] = $( input ).val();
};
Then we create an event listener on the body for all change events that occur within an Impromptu wrapper (.jquibox)
$( 'body' ).on( 'change', '.jqibox *', registerUserInput );
From this point onwards if ever an input within an Impromptu changes, its value will be recorded in the userInput object. So, to get the name input in your example:
userInput.name

jquery: Callback not received on clicking of button

I need to send a request on click of button but callback is not received on firing of click event of the button.
Following is code snippet:
$(document).ready(function () {
var counter = 0;
$("#trail").click(function () {
$("#dialog").dialog();
if (counter < 1) {
$("#searchboxdiv").after('<input type="text" id="searchbox">');
$("#searchbox").after('<input type="button" id="searchbutton" value="search">');
counter++;
}
});
$("#searchbutton").click(function () {
var dataToSend = null;
$.ajax({
data: dataToSend,
url: "FormHandler",
success: function (result) {},
beforeSend: function () {
dataToSend = $("#searchbox").val();
}
});
});
$("#searchboxdiv").on('click', "#searchbutton", function(){
var data = null;
});
});
I added the textbox in the dialog box dynamically and on click of button in dialog box, callback is not received
Your options:
Use event delegation. Bind the click to immediate static parent like this :
$("#searchboxdiv").on('click', "#searchbutton", function(){ });
Or, bind it to the document.
$(document).on('click', "#searchbutton", function(){ });
Or, move the existing click after counter++;, ie., inside $("#trail")'s click handler.
For more info, see on()
Use event delegation (for dynamically added #searchbutton)
$('#searchboxdiv').on('click',"#searchbutton",function(){
http://learn.jquery.com/events/event-delegation/

JQuery attach event to method in instance

I have code that looks like this....
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
$(this.input).bind('keyup'....);
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
this.input = the 1st element of type input found within 'id' which is what I will be referencing. This works fine for what I need.
What I want to do then is to bind the keyup event on 'input'. However I want the event to reference the instance method contained in my function - this.KeyUpHandler().
Also I need 'e' to be event that would have been passed into the function had I just done this on the markup for the input (onkeypress="keyuphandler();").
Any ideas how I can bind the event to the a function in the instance of the function I am working within?
function Finder(id) {
this.id = id;
this.input = $("#" + this.id + " :input[type='text']:first")[0];
that=this;
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', this.KeyUpHandler);
}
It is important that you call bind() after defining the function!
this.KeyUpHandler = function (e) { ..the event should trigger this.. }
$(this.input).bind('keyup', function(){
this.KeyUpHandler(event);
//more code can go here
});

Categories