Im using Jquery to trigger AJAX to retrieve data from database on a realtime basis as the user inputs data into a form containing 5 input fields.
I currently have
$("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load change paste", function(){
});
This works great when someone changes a field but it doesnt trigger on load of the page ... the fields are populated from the last known data stored in a session variable when the page is reloaded, and I need the AJAX function to call on this reload too !!
I thought the "load" in the .on would have done this but apparently not
TIA
Change your call like so:
$("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("keyup paste",
function() {
// Your code here
}
).trigger('keyup');
change only triggers on blur, so remove it.
keyup triggers with every keypress.
load doesn't apply to this element.
Chaining trigger('keyup') will cause it to trigger your function immediately.
Also, consider adding a universal class to all of these elements, so you don't have to address them individually by id:
$(".action-ajax-call").on("keyup paste",
function() {
// Your code here
}
).trigger('keyup');
Related
How do you selectize.addItem("value") without triggering item_add?
I have a tags field that’s dependent on another selection. I need to automatically fill in tags whenever that other selection is changed, and then I need to have a listener run code whenever the user adds or removes a tag. I can’t figure out how to add the tags programmatically without triggering the item_add event, but I don’t want it triggering before the user’s even touched the tags.
(There is addItem(…, silent), but unless I’m mistaken, that only stops it from triggering the change event.)
Sample code:
$('#input-tags').selectize({
onItemAdd: function() {
alert("This should only appear by user action");
}
});
$tags = $('#input-tags')[0].selectize;
$tags.addItem("awesome");
$tags.addItem("neat");
JSFiddle
One solution (and the only one I know of) is to remove the event listeners before the addItems and add them back afterwards. That hardly seems ideal, though, especially if it needs to be done more than once.
You can convert your code to register the add callback after adding all initial values:
$('#input-tags').selectize();
$tags = $('#input-tags')[0].selectize;
$tags.addItem("awesome");
$tags.addItem("neat");
// Register the listener once you have initialized the selectize component.
$tags.on('item_add', function() {
alert("This should only appear by user action");
});
I'm trying to track the different form options for this page: http://www.wibitsports.com/formular . Basically I just want to trigger an event for each specific option (out of the 3).
I'm comfortable with setting up the event tracking, the problem is I can't seem to find the HTML to put it on. I think the form's using AJAX - the URL stays the same when I submit.
Where would I find the form code? Ideally I'd like to add event tracking to each form variation's submit button.
If you need any more info I'll do my best to supply it. Clearly in over my head!
Thanks!
Something like this:
$( document ).ready(function() {
$("input[type=radio]").live("click" , function() {
_gaq.push(['_trackEvent', 'Wibit Form', 'Radio button clicked', $(this).attr("id")]);
});
});
Meaning: As soon as the document is read attach an event to all radio buttons. Since apparently more options are loaded via ajax use a "live" event (on() ) in more recent jQuery versions) so this event handler will apply to newly created radios as well. Track this as an event (change parameters at your gusto) that stores the id of the clicked radio as label.
Obviously I haven't really tested this with your site, but even if there's an error somewhere in the code it should be enough to get you going.
I am trying to call google analytics event tracking method before submitting a form on this page
This is the code that I have now:
$(function() {
$('#findbooking input').each(function(){
$(this).blur(function() {
if (!$(this).val()) {
_gaq.push(['_trackEvent', 'Rebooking', 'completed', $(this).parent().parent().text()]);
dcsMultiTrack('WT.ac', 'See_and_Change_my_booking_completed');
} else {
_gaq.push(['_trackEvent', 'Rebooking', 'skipped', $(this).parent().parent().text()]);
}
});
});
});
The problem is that the dcsMultiTrack request is fired twice when the user blur from each input field. It is supposed to only send the request once.
Note: We don't have access/modify the source code and the code will be placed on the same page as a workaround. Any help is highly appropriated
You could use submit handler to track the form submission event. The callback is invoked prior to the actual form submission, so you can place your tracking logic there. This approach guarantees that the tracking events are fired only once, not every time a user moves focus from one form field to another.
If I undestood your note correctly, the function you gave is an external script you don't have access to, and you are going to override it placing script directly on the page. In this case you need to remove the handlers previously attached to blur events. $('#findbooking input').unbind('blur'); will do the trick.
Most of the stuff I see on this site refers to adding information to a div from php. I just want to take a user's input, add it to a table dynamically and have it displayed in the div as the click the submit button.
I'm not doing anything where the data gets posted to a database, no php, etc, at this point.
I have the JQuery to run the dynamic add to the database as well. It works, but I have to use a breakpoint in the javascript to step through and see the entered data added to the row....issue is when that function is done, the page refreshes, and all data is gone.
I need a way to add the data to the table in the div without the page refreshing and clearing all of the other data each time.
Imagine parent information in one div, and child information being added in another div. As I add each child piece, I don't want the parent information to be removed, and in fact want it to remain as "editable" information.
------------------------------------------ Edit ----------------------------------------------
Below is the code I'm now using based on suggestions, but I obviously don't understand completely, because it hits the event handler for the click, but then doesn't get inside the function, just jumps back out, and never hits my other breakpoints inside there.
---------------------------------------Final Edit ----------------------------------------------
I finally pulled my head out of my backside and paid attention to what Charlie was telling me, and got this...and it works when I call the function from the onClick event. I couldn't get the event to bind to the button click, but that may be because I was using the tag instead of the setup.
function(addNoteRow){
event.prevent.Default();
var noteTxt = $('#noteEntry').val();
var noteEntBy = 'BGM'
noteEntDate = (Date());
if (!document.getElementsByTagName) return;
tabBody=document.getElementsByTagName("TBODY").item(0);
row=document.createElement("TR");
cell1=document.createElement("TD");
cell2=document.createElement("TD");
cell3=document.createElement("TD");
textnode1=document.createTextNode(noteEntDate);
textnode2=document.createTextNode(noteEntBy);
textnode3=document.createTextNode(noteTxt);
cell1.appendChild(textnode1);
cell2.appendChild(textnode2);
cell3.appendChild(textnode3);
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
tabBody.appendChild(row);
}
You mentioned you're using jQuery, so I will in my example to make this easier.
$('#submit_button').click( // Bind an event handler to the submit button
function(event){
event.preventDefualt(); //This is necessary if you are using a an submit button input element as normal behavior is to submit the form without ajax causing the page location to change. Event is automatically passed in, and we can call preventDefault() on this object to stop the browser from navigating away from our page.
$.ajax({
url:'http://youserver.com/script_that_will_respond.php', //Give the ajax call a target url
data: $('#user_input').val(), //Supply some data to send with the request,
success: function(data){ //Supply an anonymous function to execute on success. The parameter will be the response text.
$('#your_result_div').html(data); //On success of the ajax call, put the response text into an html element on your page
}
});
}
);
jQuery's ajax method has a lot of settings. This is a pretty bare-bones example.
You can read more about the various options here: http://api.jquery.com/jQuery.ajax/
Edit: I may have misunderstood. If you do not need to reach a server, and want to do this all locally, it is simpler.
$('#submit_button').click( // Bind an event handler to the submit button
function(event){
event.preventDefault();
/*
We have to call this method on the event object bacause deafult behavior
of a subnmit button is to submit the form, causing the browser to go to a new page.
*/
var text = $('#some_input_element').val(); //Store the value of a text input in the variable text
$('#your_div').html(text); //put the contents of the variable text into the "your_div" elemnt.
}
);
try AJAX for partially refreshing portions of page like div etc.
http://api.jquery.com/jQuery.ajax/
Tried to bind submit event (or click or whatever) to an element within a jQuery mobile page. What I wanted to do is get the value from an input within an form element within a jQuery page and store it in cookies/localStorage. Every time I come back to this page I want to restore the input field.
Currently I ended up in using this script:
$('.pageClassSelector').live('pageinit', function (e) {
$('.classSelector').submit(function () {
var q = $('.inputClassSelector').val();
// store to localStorage ...
});
// load from localStorage ...
$('.q').val(lastSearchString);
});
This approach is documented there http://jquerymobile.com/test/docs/api/events.html
Since it seems possible that identical pages are hold in the DOM, ID selectors are not quite useful. My problem now is that everytime I navigate to this page the submit event is bound again and thus results in storing DIFFERENT (!) values. The submit event seems to be fired multiple times and much more interesting with the value before last.
Am I doing anything completly wrong? Any hints how to do scripting in jquery mobile properly?
TRY1:
I placed now the submit event binding within the pagebeforeshow event like so:
$('#PageId').on('pagebeforeshow', function (e) {
$('.classSelector').on('submit', function () {
var q = $('.q').val();
alert('stored: ' + q);
}
$('.q').val(lastSearchString);
}
But the value going to be stored is still the value before last, when I was navigating the page before. The first time it works as it should.
TRY2:
This is what I have now and it looks like it does that what I want. I select now the current page and select only the form which is a child of this page.
Is this good practice?
$('div:jqmData(id="PageId")').on('pagebeforeshow', function (e) {
$(this).find('#form').on('submit', function () {
var q = $(this).find('#input').val();
localStorage.setItem("key", q);
return true;
});
lastSearchString = localStorage.getItem("key");
$(this).find('#input').val(lastSearchString);
});
Your requirement to load from local storage and store on the page needs to be done by binding to the pagebeforeshow event (look at the section "Page transition events") and not the pageinit event like you are currently doing.
$('.pageClassSelector').on('pagebeforeshow', function (e) {
// load from localStorage ...
$('.q').val(lastSearchString);
});
Furthermore generally each page element (where you have data-role='page') should have a unique ID so you can use that instead of the CSS selector.
Multiple events firing when navigating pages sounds like multiple bindings to me, which is a known problem with jQuery Mobile. Bindings are not unbound when navigating pages, because everything is loaded through AJAX. See for example this StackOverflow Question: Jquery mobile .click firing multiple times on new page visit or my solution.
$('.classSelector').on('submit', function(){})
Try to use the constraction to bind your event to element.
Look likes some data was loaded through ajax request