jQuery .blur on input AND div classes - javascript

I have a form with multiple input fields. I'm using a blur function to trigger an AJAX request when ever an input field is clicked out of like so:
$(".innerItems input").blur(function() {
$.ajax({
// etc
});
});
However, I've also built a custom "select menu" using DIVs and jQuery like so:
http://jsfiddle.net/tctc91/gWS2L/
How can I simulate a "blur" so that when the value changes in my custom select menu, the AJAX request is triggered like it normally would if it were an input?

You can trigger events on elements programatically by using trigger():
$(".innerItems input").trigger("blur");
So in your code, it would be:
$(".currentMenu li").click(function(e){
e.preventDefault();
$(this).closest(".currentMenu").prev().html($(this).text());
$(this).closest(".currentMenu").prev().append('<span class="dd-arrow"></span>');
$(".innerItems input").trigger("blur");
});

You already have a listener on the click event just add the ajax to the bottom of that ?
$(".currentMenu li").click(function(e){
e.preventDefault();
$(this).closest(".currentMenu").prev().html($(this).text());
$(this).closest(".currentMenu").prev().append('<span class="dd-arrow"></span>');
// ajax here
doAjaxStuff();
});​
$(".innerItems input").blur(doAjaxStuff);
function doAjaxStuff() {
$.ajax({
// etc
});
}

You can create a custom event say customMenuChanged and trigger it whenever you change the value.
$(".currentMenu li").click(function(e){
e.preventDefault();
var $prev = $(this).closest(".currentMenu").prev();
//Check if the value actually changed or same item is selected
if($prev.text() != $(this).text()){
$(document).trigger('customMenuChanged', $(this).text());
}
$prev.html($(this).text() + '<span class="dd-arrow"></span>');
});
$(document).bind('customMenuChanged', function(e, data){
alert("Menu changed " + data);
//Code here to make ajax request
});
You can bind event to any element you want and trigger it.
Working demo - http://jsfiddle.net/gWS2L/6/

Related

why does checkbox stops working when ever i use addEventListener

when ever i use addEventListener my check box stops working i tried removing every code but when i add this code my checkbox stops working
this is my event listener
document.addEventListener('click', function(e) {
e.preventDefault();
});
my document has innerhtml before it and i wanted to get the selected items id
this is the innerhtml
document.innerHTML += "<div class='product-container'><div class='course'><div class='course-preview'><img class='product-image' src="+productimageUrl+"></div><div class='course-info'><div class='progress-container'><h6>OnSale: "+ productsale +"</h6><h6>Featured: "+productfeatured +"</h6><h6>soldOut: "+ productsoldout +"</h6></div><h2>"+ productname +" "+ productprice +" </h2><h4>"+productcategory+", "+productsubcategory+"</h6><h4>"+ productamount +"</h4><h6>PRODUCT ID:</h6><h5>"+ productid +"</h5><button id='editbutton' class='btn'>Edit Product</button></div></div></div>"
whenever i use this code this code it stops working in case you want document this is my document
const document = document.getElementById("main-page");
e.preventDefault(); prevents any action that would've taken place when clicking.
If you want to preventDefault() only when you're not clicking on a checkbox, test if the target object is or not an input.
document.addEventListener('click', function(e) {
if(e.target.tagName != "INPUT") {
e.preventDefault();
}
});

jquery selector for future element if visible

One of my ajax popup is loading too late.so my condition of jquery to check visibility is not working.
$(document).ready(function() {
if($('#emailCart').is(':visible')){
alert('yes');
let shouldFire = true;
$("input, select").click(function(){
if(shouldFire) {
alert('sent');
sendGAEvent('Email', 'click','Email Cart');
shouldFire = false;
}
});
};
});
seems "is(':visible')" only checks for dom loaded elements.How can i apply this conditions to future elements also.
Email cart image
When clicking on this Email cart button many textboxes appear on clicking any one of those my code should work. I am using a tool tempormonkey by which i inject my code to websites.But my code is not working when i inject using tempormonkey but instead works with console.
Do it the other way around: check the visibility in the handler function.
$(document).ready(function() {
$("input, select").click(function() {
if ($('#emailCart').is(':visible')) {
alert('sent');
sendGAEvent('Email', 'click', 'Email Cart');
}
});
});
If the input and select elements are loaded dynamically, use event delegation as described in Event binding on dynamically created elements?. But that doesn't change the logic of how to check for visibility of the cart.
Its not possible to write such code which will execute in future but we can monitor that on click of document because you are saying that on click of Email Cart button you want to execute it.
I hope it will resolve your issue, try it:-
$(document).on('click', function (e) {
if (!$('#emailCart').is(':visible')) return;
alert('yes');
let shouldFire = true;
$("input, select").click(() => {
if (!shouldFire) return;
alert('sent');
sendGAEvent('Email', 'click', 'Email Cart');
shouldFire = false;
});
});

jQuery doesn't recognize a class change

Ok, I have a edit button, when I press on it, it changes to "done" button.
It's all done by jQuery.
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.attr('class', 'icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});
When I press on a "edit" (".icon-pencil") button, its classes change to .icon-ok-sign (I can see in chrome console),
but when I click on it, no alert shown.
When I create a <span class="icon-ok-sign">press</span> and press on it, a alert displays.
How to solve it?
Try using $( document ).on( "click", ".icon-ok-sign", function() {...
Thats because you can not register click-events for future elements, you have to do it like this:
$(document).on('click', '.icon-ok-sign', function() {
alert('hey');
});
This method provides a means to attach delegated event handlers to the
document element of a page, which simplifies the use of event handlers
when content is dynamically added to a page.
Use following script:
$(document).on('click','.icon-ok-sign',function(){
alert("hey");
});
Try this:
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.removeAttr('class').addClass('icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});

Do not fire one event if already fired another

I have a code like this:
$('#foo').on('click', function(e) {
//do something
});
$('form input').on('change', function(e) {
//do some other things
));
First and second events do actually the same things with the same input field, but in different way. The problem is, that when I click the #foo element - form change element fires as well. I need form change to fire always when the content of input is changing, but not when #foo element is clicked.
That's the question )). How to do this?
Here is the code on jsfiddle: http://jsfiddle.net/QhXyj/1/
What happens is that onChange fires when the focus leaves the #input. In your case, this coincides with clicking on the button. Try pressing Tab, THEN clicking on the button.
To handle this particular case, one solution is to delay the call to the change event enough check if the button got clicked in the meantime. In practice 100 milisecond worked. Here's the code:
$().ready(function() {
var stopTheChangeBecauseTheButtonWasClicked = false;
$('#button').on('click', function(e) {
stopTheChangeBecauseTheButtonWasClicked = true;
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
var self = this;
setTimeout(function doTheChange() {
if (!stopTheChangeBecauseTheButtonWasClicked) {
$(self).val($(self).val() + ' - changed!');
} else {
stopTheChangeBecauseTheButtonWasClicked = false;
}
}, 100);
});
});
And the fiddle - http://jsfiddle.net/dandv/QhXyj/11/
It's only natural that a change event on a blurred element fires before the clicked element is focused. If you don't want to use a timeout ("do something X ms after the input was changed unless in between a button was clicked", as proposed by Dan) - and timeouts are ugly - you only could go doing those actions twice. After the input is changed, save its state and do something. If then - somewhen later - the button is clicked, retrieve the saved state and do the something similar. I guess this is what you actually wanted for your UI behaviour, not all users are that fast. If one leaves the input (e.g. by pressing Tab), and then later activates the button "independently", do you really want to execute both actions?
var inputval = null, changedval = null;
$('form input').on('change', function(e) {
inputval = this.value;
// do some things with it and save them to
changedval = …
// you might use the value property of the input itself
));
$('#foo').on('click', function(e) {
// do something with inputval
});
$('form …').on('any other action') {
// you might want to invalidate the cache:
inputval = changedval;
// so that from now on a click operates with the new value
});
$(function() {
$('#button').on('click', function() {
//use text() not html() here
$('#wtf').text("I don't need to change #input in this case");
});
//fire on blur, that is when user types and presses tab
$('#input').on('blur', function() {
alert("clicked"); //this doesn't fire when you click button
$(this).val($(this).val()+' - changed!');
});
});​
Here's the Fiddle
$('form input').on('change', function(e) {
// don't do the thing if the input is #foo
if ( $(this).attrib('id') == 'foo' ) return;
//do some other things
));
UPDATE
How about this:
$().ready(function() {
$('#button').on('click', function(e) {
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
// determine id #input is in focus
if ( ! $(this).is(":focus") ) return;
$(this).val($(this).val()+' - changed!');
});
});

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

Categories

Resources