jQuery load function not working on binding - javascript

I bind "load" and "change" in jQuery code.
My goal is: disable some field based on logic when page load.
jQuery( document ).ready(function() {
//Question 34.1
jQuery('select#fever').bind('load change', function () {
var drug_reaction = jQuery(this).val();
if(drug_reaction== 1){
jQuery('input#fever_days').attr('disabled',false);
jQuery('select#character_of_fever').attr('disabled',false);
jQuery('select#evening_raise_of_temparature').attr('disabled',false);
jQuery('select#night_sweats').attr('disabled',false);
}else{
jQuery('input#fever_days').val("");
jQuery('input#fever_days').attr('disabled',true);
jQuery('select#character_of_fever').val("");
jQuery('select#character_of_fever').attr('disabled',true);
jQuery('select#evening_raise_of_temparature').val("");
jQuery('select#evening_raise_of_temparature').attr('disabled',true);
jQuery('select#night_sweats').val("");
jQuery('select#night_sweats').attr('disabled',true);
}
});
});
When I change fever dropdown , its working. But when page load, I fetch data from Database and this code not working:
var drug_reaction = jQuery(this).val();
if(drug_reaction== 1){
jQuery('input#fever_days').attr('disabled',false);
jQuery('select#character_of_fever').attr('disabled',false);
jQuery('select#evening_raise_of_temparature').attr('disabled',false);
jQuery('select#night_sweats').attr('disabled',false);
}else{
jQuery('input#fever_days').val("");
jQuery('input#fever_days').attr('disabled',true);
jQuery('select#character_of_fever').val("");
jQuery('select#character_of_fever').attr('disabled',true);
jQuery('select#evening_raise_of_temparature').val("");
jQuery('select#evening_raise_of_temparature').attr('disabled',true);
jQuery('select#night_sweats').val("");
jQuery('select#night_sweats').attr('disabled',true);
}

load events fire on elements which load data from a URL (e.g. the whole page, img elements and iframe elements).
A select element doesn't load external data, and nor do any of its descendants. There is no load event.
Even if there was, it would have already loaded by the time the ready event fires.
Trigger the change event as part of your ready event handler instead.
jQuery('select#fever')
.bind('change', function () { ... })
.trigger("change");

Related

Jquery code in table header partial randomly does not work when other custom js is on page

So I have a partial view that loads the table header. Inside the header there is the title and one of 3 dynamically shown buttons that when clicked open up a small div containing additional buttons. this jquery code works perfectly fine on pages without custom javascript/jquery inside of them. They also work 4 out of 5 times correctly on the pages with the custom code inisde of them.
*** updated with latest jquery**
$(document).ready(function() {
// Use event delegation to handle clicks on the additional buttons
$(document).on("click", "##additionalButtonID, ##additionalButtonID2, ##additionalButtonID3", function(e) {
e.stopPropagation(); // prevent the event from propagating up to the document element
const div = $("div#div-#Model.UniqueTableIdentifier");
div.css("left", e.clientX -150);
div.css("top", e.clientY);
div.fadeIn(200);
});
// Use event delegation to handle clicks on the buttons inside the div
$(document).on("click", "div#div-#Model.UniqueTableIdentifier button", function(e) {
e.stopPropagation(); // prevent the event from propagating up to the document element
const div = $("div#div-#Model.UniqueTableIdentifier");
div.fadeOut(200);
});
// Use event delegation to handle clicks on the li element
$(document).on("click", ".list-tbl-items", function(e) {
if ((e.target).querySelector('button') != null) {
(e.target).querySelector('button').click();
e.stopPropagation();
}
});
// Use event delegation to handle clicks on the document, outside of the div
$(document).on("click", function(e) {
if (!$(e.target).closest("div#div-#Model.UniqueTableIdentifier").length) {
const div = $("div#div-#Model.UniqueTableIdentifier");
div.fadeOut(200);
}
});
});
You see i even have the eventdelegation to go do onthe document click which i thought would just make it the header of the table at worst but still doing these issues. and worst is i can refresh the page multiple times before it happens again.
Probably jQuery script is still not loaded when you starts use it.
You should attach all events after page is loaded.
Using JQuery:
$( document ).ready( function(){
// here your code...
})
or using pure JavaScript
window.addEventListener ('load',()=>{
// here your code...
} );

EventListener not working with anchor tel:XXXXXXXXX

I have a tag with href="tel:XXXXXXXXX", and I need catch the click event.
I have tested the following code on chrome: $(document).on('click',console.log). If i click on this tag browser it calls the application, but does not trigger a click event.
$("a[href^='tel']").on('click', console.log);
This is working, but I my have a problem with content load by ajax. My code has loaded a page and after some time application added content by ajax. When i use $(document).on('click', ("a[href^='tel']", console.log), there is a problem.
$("a[href^='tel']").on("click", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
})
//or if you want to delegate your function
$(document).on('click', "a[href^='tel']", function(e){
e.preventDefault(); e.stopPropagation();
console.log(this);
alert(this.getAttribute("href"));
});
This will bind an event listener to all click on a tags with a href attribute and prevent the click itself. After click, you'll be able to use your console to see which element was click and what href was used.
Ok, i found resolve.
I use earlier event "mousedown" and change attr "href" to "only number" for disable action click.
Code:
const click2dial_Event = function(e) {
e.preventDefault();
let a = $(this), number;
if (a.attr('href') !== '#') {
number = a.attr('href');
number = number.substr(4);
a.attr('href', '#');
a.attr('data-dial', number)
a.addClass('click-to-dial');
} else {
number = a.attr('data-dial');
}
//...
};
$(document).on('mousedown', "a[href^='tel']", click2dial_Event);
$(document).on('mousedown', '.click-to-dial', click2dial_Event);
This would get the phone number from the a tag starting with a value of tel upon clicking it.
$("a[href^='tel']").on("click", function(e) {
var hrefText = this.getAttribute("href");
var str = hrefText;
var res = str.split(":");
alert(res[1]);
});
On Initial Load
I would first recommend that you wait for the initial DOM to be ready before binding any events to elements.
// DOM ready shorthand
$(function() {
$("a[href^='tel']").on('click', function(e) {
// Do work here
});
});
AJAX Content
If you are adding additional elements after the initial load you will have to bind events to those new elements as well.
You could also do something like adding a data attribute to the elements that you've bound click events to and only add to ones that don't yet have that data attribute - but that's additional unnecessary work.
Full Example Code
// DOM Ready Shorthand
$(function() {
// Click Handler
function clickEvent(e) {
// Do work here
}
// Bind click event to initial tels
$("a[href^='tel']").on('click', clickEvent);
// Arbitrary AJAX request for demonstration (wherever yours may be)
$.ajax('/newContent')
.done(function(html) {
// Adding our response HTML to the page within #someElement
$('#someElement').append(html);
// Bind click event to the new tel elements scoped to the returned html
$("a[href^='tel']", html).on('click', clickEvent);
});
});

Ajax Load Event Incrementing By One

I have a simple textarea where users can input text which is then passed through via AJAX to a URL once they hit the return key. My issue is that on the first press of the return key the text data is sent once, on the second it's sent twice, and so on incrementing my one each time.
After some reading up I realise that if I was using a form submit I'd have to unbind it to prevent this happening. I've tried adding a value flag to prevent the multiple events, but have only got so far as to get it to trigger once only.
My code is as follows. Any guidance on how to prevent the incrementing events would be appreciated - as you can probably tell my confidence/knowledge in Javascript isn't the best. Thank you!
$(function() {
$("#myTextarea").keypress(function(e) {
// If the user hits the return key
if(e.which == 13) {
e.preventDefault();
$.ajax({
success: function(){
var modal = $('#myModal'), modalBody = $('#myModal .modal-body');
modal
// Load the webpage result within the modal Body
.on('show.bs.modal', function () {
modalBody.load('http://www.things.co.uk/things' + document.getElementById('myTextArea').value)
})
.modal();
// Hide the modal after five seconds
myModalTimeout = setTimeout(function() {
$('#myModal').modal('hide');
}, 5000);
}
});
}
});
});
Edit: I solved this by using one() for my modal event via http://www.andismith.com/blog/2011/11/on-and-off/. Thank you everyone.
You must attach the event handler only once. I suppose you're getting the JS in your AJAX response, and executing it again and again on each AJAX load. Removing and re-attaching the handlers is a hacky solution.
To avoid to attach the event handlers more than once, simply put your script in a part of the page which is not reloaded by AJAX, so the event is attached only once.
You can even attach an event handler to an element that is reloaded by ajax using delegated events: Understanding Event Delegation
With this technique, you attach the event handler to a container parent element which is not reloaded by ajax, and handle the events of the reloaded children specified by a filter.
$( "#container" ).on("<event>", "<children filter>", function( event ) {
// code to handle the event
});
Note that in this sample #container is the element which isn't reloaded by ajax. And <children filter> is a jquery selector that chooses the children whose event mus be handled. (<event> is obviously the event name, like click or keyPress).
Explanation: when the event is trigger in the child element, it pops up to the container. The container catches it, and checks that the children passes the filter. If so, the vent is handled.
If there are no more event handlers on myTextarea div code below should suffice.
If there are multiple event handlers attached to keypress event you will have to use named function and remove it using $.unbind() more on how to do this.
$(function() {
$("#myTextarea").off();
$("#myTextarea").keypress(function(e) {
// If the user hits the return key
if(e.which == 13) {
e.preventDefault();
$.ajax({
success: function(){
var modal = $('#myModal'), modalBody = $('#myModal .modal-body');
modal
// Load the webpage result within the modal Body
.on('show.bs.modal', function () {
modalBody.load('http://www.things.co.uk/things' + document.getElementById('myTextArea').value)
})
.modal();
// Hide the modal after five seconds
myModalTimeout = setTimeout(function() {
$('#myModal').modal('hide');
}, 5000);
}
});
}
});
});

jquery .bind prevent running on page load

I have a jquery function that binds a select field on a form to multiple actions. It binds to both change and keyup, so that mouse and keyboard clicks are both captured.
$(document).ready(function(){
$('#user_id').bind('change keyup',function () {
calculateAmounts();
}).change();
});
This works perfectly.
However, in addition to running on the change and keyup functions, the calculateAmounts() function is also called when first loading the page. I'd like to prevent this code from running when the page is first loaded.
You're triggering a change event when you call .change() on the $('#user_id') element, which will call your change/keyup event handler. If you remove the .change() call, then that event won't be triggered when the page loads:
$(document).ready(function(){
$('#user_id').bind('change keyup',function () {
calculateAmounts();
});
});
try this (taking in consederation that #user_id is input field)
$(document).ready(function(){
var yourVAL = $("#user_id").val();
$('#user_id').bind('change keyup',function () {
if($("#user_id").val() != yourVAL){
calculateAmounts();
}
}).change();
});

change event doesn't fire on ajax loaded forms

I have an HTML document, with the jquery code
$(function(){
[...]
$("#newNotice").click(function(){
$("#properties").load("testDiagramm.html #NoticeForm");
return false;
});
function showFormValues(){
var s = $("form").serialize();
[... Do things ...]
}
$("input, textarea").change(showFormValues);
});
At the beginning there is no form in the HTML document. But i load diffrent forms into the document. One of those request you can see here
$("#properties").load("testDiagramm.html #NoticeForm");
The problem is. that the codeline
$("input, textarea").change(showFormValues);
only fire, when the form was loaded at the beginning. What must I do, if i want to execute the function showFormValues(), when I changed something in the formular, which i load later?
Thanks a lot for your answers.
Lara
Your form loses its binding to the DOM after it is reloaded via ajax, so event handlers previously bound to the elements that get injected into the page are lost.
I would normally suggest using event delegation with live, but it does not support the change event, so a safe bet would be to rebind using a callback as a second parameter to your $.load function:
$(function(){
[...]
$("#newNotice").click(function(){
$("#properties").load("testDiagramm.html #NoticeForm", function() {
$("input, textarea").change(showFormValues);
});
return false;
});
function showFormValues(){
var s = $("form").serialize();
[... Do things ...]
}
$("input, textarea").change(showFormValues);
});

Categories