How can I change the event function after the its already clicked once? then in the second or more times it will behave differently.
I already tried the one event but I still want to have a function on that button if clicked but a different one.
here's my code on one click event
$(document).one('click', '#search', function(e){
e.preventDefault();
e.stopPropagation();
that._getEmployeeProfile();
});
on second or above clicked I want to happen this
$(document).on('click', '#search', function(e){
e.preventDefault();
e.stopPropagation();
$('searchlist').modal('show')
});
Thank you!
You can set a variable which will be updated if the user clicked on the element.
var userAlreadyClicked = false;
$(document).on('click', '#search', function(e){
e.preventDefault();
e.stopPropagation();
if(!userAlreadyClicked ){
that._getEmployeeProfile();
userAlreadyClicked = true;
}else{
$('searchlist').modal('show')
}
});
You can maintain one variable as flag based on which you can execute the specific code block:
let flag = true;
$(document).on('click', '#search', function(e){
e.preventDefault();
e.stopPropagation();
if(flag){ //since the flag is true this code block will be executed only for the first click
that._getEmployeeProfile();
flag = false; //set the flag to false which will execute the else block for the subsequent click.
}
else{
$('searchlist').modal('show');
}
});
you can use a flag in your function and after first call of the function you can increment that number and then apply a check by if statement if the value of the flag variable is greater then one you can write another functionality
e.g
let flag = 0;
$(document).on('click', '#search', function(e){
flag++;
e.preventDefault();
e.stopPropagation();
if(flag > 1){
$('searchlist').modal('show');
} else {
that._getEmployeeProfile();
}
});
You can data attribute in button tag and after first click you can change data attribute of that button.Below is example :
$(document).on('click', '#search', function(e){
var functionName = $(this).data('function');
$this = $(this);
e.preventDefault();
e.stopPropagation();
if (typeof window[(functionName)] === 'function') {
window[(functionName)]();
$this.data('function','nofunction');
}
else{
$('searchlist').modal('show')
}
});
<button name="search" id="search" data-function=""></button>
This sounds like an X/Y problem. Let me guess at a better title.
"How can I show an existing profile if I already got it"
I would
assign the event handler to the submit of the form
store the user in a key/value store
If the user is not in the store, get the user
show the user from store.
If you have multiple or unspecified number of elements whose behavior you want to change after a click, the next solution seems appropriate at least at first glance:
$(document).on('click', '#search', function(e) {
e.preventDefault();
e.stopPropagation();
var t = $(e.target);
if (typeof t.prop('alreadyClicked') === 'undefined') {
t.prop('alreadyClicked', 1);
that._getEmployeeProfile();
} else $('searchlist').modal('show');
});
Related
Can anybody tell why in my given code I am unable to get alert? Why is clicked always false even after my button gets clicked?
$(document).ready(function() {
var clicked = false;
$(document).on('click', '#submit-catalog', function() {
var clicked = true;
});
if(clicked){ // never get executed
alert("button clicked")
//i am executing some function only if that button clicked
}
});
JavaScript does not wait for the click listener to be executed before going into the if-block.
The variable never gets set to any other value before it's checked.
You also have some syntax errors in your code pointed out by #BraveButter's answer.
If you want to alert once the element has been clicked use this code:
$(document).ready(function() {
$(document).on('click', '#submit-catalog', function() {
alert("button clicked");
});
});
Document ready is executed as soon as the the form finishes loading. Your button is not clicked at that point.
You are adding an event handler to the button that will change the value of the clicked variable as soon as the user clicks the button.
All good and well but If you want something to happen on the click of the button (the functionality you mention) you should run this functionality on the click event. Something like that
function doWhatIWant(){
alert("button clicked")
//i am executing some function only if that button clicked
}
and change your event handler like that
$(document).on('click', '#submit-catalog', function() {
clicked = true;
doWhatIWant();
// Or just add your functionality here
});
because you created a new variable with another scope inside of your eventhandler
remove the var before it so you set your variable in the document ready function.
Also your queue will handle the if before you can trigger the onclick event.
$(document).ready(function() {
$(document).on('click', '#submit-catalog', function() {
alert("button clicked")
});
});
Now each time your button fires the onclick event it will show the alert window
If you just want to show the alert window once try this
$(document).ready(function() {
var clicked = false;
$(document).on('click', '#submit-catalog', function() {
if(!clicked) {
clicked = true;
alert("button clicked")
}
});
});
the problem is that your if statement is outside the evaluation of the onClick function, thus, your if is never evaluated.
also you are doing var clicked = true inside the function.
here you have a working example:
$(document).ready(function() {
var clicked = false;
$(document).on('click', '#submit-catalog', function() {
clicked = true;
if (clicked) {
alert("button clicked")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='submit-catalog'> clickme </button>
check that if you change the value of clicked, as soon as you enter to the document, it will trigger an alert. this is because the if is evaluated as soon as you enter.
$(document).ready(function() {
var clicked = true;
$(document).on('click', '#submit-catalog', function() {
//you call this when you click the button.
});
if(clicked){ // never get executed
alert("button clicked")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
just cancel default submit action, set clicked to true and call a function to alert and submit form
$(document).ready(function() {
var clicked=false;
$(document).on('click', '#submit-catalog', function(e) {
e.preventDefault();
clicked=true;
click();
});
function click(){
alert("button clicked")
//submit catalog form
$('#catalog-form').submit();
}
});
I need to know where the click event happens in my document, i Have some divs , and when i press cntrl key and click on them some events will occur, i just need to know how to identify the divs which got clicked, is it possible to generalize them in document.click fn Like what i have tried.
Here is a sample of what i have tried
HTML
<div class="DivOne">Div1</div>
<div class="DivTwo">Div2</div>
<div class="DivThree">Div3</div>
Jquery
$(document).bind("click", function (e) {
if (e.which == '17') {
alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
}
});
You can use e.target along with .is() function to achieve what you want.
Try,
$(document).bind("click", function (e) {
if($(e.target).is('.DivOne')){
alert('Div one has been clicked..!')
}
});
$("div").click(function (e) {
var classOfDiv = this.className;
// do stuff depending on what class
});
You can select classes, or ids like so
$("#DivOne").click(function (e) {
if (e.which == '17') {
alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
}
});
or a class like
$(".DivOne").click(function (e) {
if (e.which == '17') {
alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
}
});
Alternately you can loop through all divs on the page and test for a click
$("div").each(function () {
$(this).click(function() {
var divClass = $(this).attr('class');
alert("You clicked on " + divClass);
});
});
Fiddle
I am trying to make a confirmation section with jquery. I have a cancel button that displayed the confirmation message. Then again click on that confirmation buttons that is YES and NO.
here is the jsfiddle of my script: http://jsfiddle.net/jogesh_pi/TVfM9/
first click on cancel then you get yes and no button, pressing no shows you first stat that is cancel button, then again click on cancel and after that press yes, yes show you the alert message but with bubble alert box as many time we try it without refresh, hope you understand,
Can anyone tell me where i missed something?
$('input[name="cancel_upload"]').click(function(e){
e.preventDefault();
e.stopPropagation();
var that = $(this),
s_t = $('.status'),
c_b = $('#cncl'),
c_c = $('#cncl-conf'),
c_y = $('input[name="cancel_y"]'),
c_n = $('input[name="cancel_n"]');
c_b.hide();
c_c.show();
s_t.html('Cancel Transfer')
.next()
.hide();
//Trigger Handle
var combo = c_y.add(c_n);
combo.click(function(e){
e.preventDefault();
e.stopPropagation();
if(e.target.name == 'cancel_n')
{
c_b.show();
c_c.hide();
s_t.html('Transferring...')
.next()
.show();
}
else
{
alert('Going to Cancel');
c_b.show();
c_c.hide();
s_t.html('Transferring...')
.next()
.show();
}
});
return false;
});
This problem does not have anything to do with event bubbling, it is because you have duplicate event handlers registered in each click of the cancel button
You should not register an event handler inside another event handler without removing teh previous handlers.
In this case I would suggest adding the event handlers outside the click handler
Try
var s_t = $('.status'),
c_b = $('#cncl'),
c_c = $('#cncl-conf'),
c_y = $('input[name="cancel_y"]'),
c_n = $('input[name="cancel_n"]');
//Trigger Handle
var combo = c_y.add(c_n);
combo.click(function(e){
e.preventDefault();
e.stopPropagation();
if(e.target.name == 'cancel_n')
{
c_b.show();
c_c.hide();
s_t.html('Transferring...')
.next()
.show();
}
else
{
alert('Going to Cancel');
c_b.show();
c_c.hide();
s_t.html('Transferring...')
.next()
.show();
}
});
$('input[name="cancel_upload"]').click(function(e){
e.preventDefault();
e.stopPropagation();
var that = $(this);
c_b.hide();
c_c.show();
s_t.html('Cancel Transfer')
.next()
.hide();
return false;
});
Demo: Fiddle
I've got the following code in my web page, where I need to click on the input field and add values using the number pad provided! I use a script to clear the default values from the input when the focus comes to it, but I'm unable to add the values by clicking on the number pad since when I click on an element the focus comes from the input to the clicked number element. How can I resolve this issue. I tried the following code, but it doesn't show the number in the input.
var lastFocus;
$("#test").click(function(e) {
// do whatever you want here
e.preventDefault();
e.stopPropagation();
$("#results").append(e.html());
if (lastFocus) {
$("#results").append("setting focus back<br>");
setTimeout(function() {lastFocus.focus()}, 1);
}
return(false);
});
$("textarea").blur(function() {
lastFocus = this;
$("#results").append("textarea lost focus<br>");
});
Thank you.
The first thing I notice is your selector for the number buttons is wrong
$('num-button').click(function(e){
Your buttons have a class of num-button so you need a dot before the class name in the selector:
$('.num-button').click(function(e){
Secondly, your fiddle was never setting lastFocus so be sure to add this:
$('input').focus(function() {
lastFocus = this;
...
Thirdly, you add/remove the watermark when entering the field, but ot when trying to add numbers to it (that would result in "Watermark-text123" if you clicked 1, then 2 then 3).
So, encalpsulate your functionality in a function:
function addOrRemoveWatermark(elem)
{
if($(elem).val() == $(elem).data('default_val') || !$(elem).data('default_val')) {
$(elem).data('default_val', $(elem).val());
$(elem).val('');
}
}
And call that both when entering the cell, and when clicking the numbers:
$('input').focus(function() {
lastFocus = this;
addOrRemoveWatermark(this);
});
and:
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
You'll see another change above - you dont want to use append when appends an element, you want to just concatenate the string with the value of the button clicked.
Here's a working branch of your code: http://jsfiddle.net/Zrhze/
This should work:
var default_val = '';
$('input').focus(function() {
lastFocus = $(this);
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
var text = $(e.target).text();
if (!isNaN(parseInt(text))) {
lastFocus.val(lastFocus.val() + text);
}
});
Live demo
Add the following function:
$('.num-button').live( 'click', 'span', function() {
$currObj.focus();
$currObj.val( $currObj.val() + $(this).text().trim() );
});
Also, add the following variable to global scope:
$currObj = '';
Here is the working link: http://jsfiddle.net/pN3eT/7/
EDIT
Based on comment, you wouldn't be needing the var lastFocus and subsequent code.
The updated fiddle lies here http://jsfiddle.net/pN3eT/28/
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!');
});
});