why unable to get alert on click of button - javascript

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();
}
});

Related

Change the function code after clicked once

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');
});

How to call one button click event in another by stopping specific properties

After clicking on btn triggering btn1 click event, but clicking on btn it is triggering btn1 event and closing the popup but it should not how can i stop that.
While clicking on btn only form validation should happen need to stop closing fancybox.
$('.btn').on('click', function(){
$('.btn1').css('display','block');
$('.btn1').trigger('click');
});
$('.btn1').on('click', function(){
//form validation
$.fancybox.close();
});
you can pass a parameter while triggering click event on btn1.
Javascript code:
$('.btn').on('click', function(){
$('.btn1').css('display','block');
$('.btn1').trigger('click', [true]);
});
$('.btn1').on('click', function(event, dontClose){
//form validation
if(error == 0 && !dontClose){
$.fancybox.close();
}
});
when click event is triggered automatically on btn1, dontClose will be undefined in which case depending on error fancy box will close.
I don't know if i understood what you need, if not tell me and i'll remove this answer.
$('.btn').on('click', function(){
console.log("click btn");
$('.btn1').trigger('click', 1);
});
$('.btn1').on('click', function(e, data){
//form validation
if (data != 1) { // if event is not triggered
$.fancybox.close();
}
});

Need click event to trigger alert during else

So, this code is working:
<script>
$(document).ready(function(){
  var btn = $('#submit_send_order');
  btn.attr({disabled: 'disabled'});
  var chk = $('.end-box');
  chk.click(function(){
    if ($(this).attr('checked'))
      btn.removeAttr('disabled');
    else
      btn.attr({disabled:'disabled'});
  });
});
</script>
but I can't get any working version of a click, onclick, or event handler to cause a popup message during the else condition. Unless users checks a box, they cannot send their order on my site. Right now they click the button and nothing happens until they check the box. But I'd like an alert to show as well, e.g.:
$(document).ready(function(){
$('#submit_send_order').click(function(){
alert("You cannot proceed until you check the end box");
});
});
As Verhaeren said above, if the button is disabled, then it can't fire the click event. Rather than disabling the button, I would just put an if/else check in the click event.
So...
$(document).on('click', '#submit_send_order', function(event) {
event.preventDefault();
if ($('.end-box').prop('checked')) {
//Handle form submission
} else {
alert('You cannot proceed until you check the end box');
}
});
The onclick event doesn't fire when the element is disabled. Also, notice which is the right method to see if the checkbox is checked:
$(document).ready(function(){
var btn = $('#submit_send_order');
btn.attr({disabled: 'disabled'});
var chk = $('.end-box');
chk.on('click', function(){
if ($(this).is(':checked'))
btn.removeAttr('disabled');
else
btn.attr({disabled:'disabled'});
});
btn.on('click', function(){
alert("You cannot proceed until you check the end box");
});
});
I build a "solution" for this if you REALLY whant to do that. You can check it at this fiddle:
http://jsfiddle.net/2f1wsb8c/3/
It's placing an element with the same size of the button over it to catch the click when the button is disabled.

my jquery event handler for a button only works once

Im making a sort of like social network website like twitter.
When the user wants to edit a post I open a div append a textarea, a "save" button and a "cancel" button with jquery.
But the cancel button only works once, the 2nd time the user clicks for editing a post, the cancel button doesn't work anymore.
$(function()
{
function edit(chirp_id)
{
var div1 = $('<div></div>');
div1.addClass('thumb2');
div1.attr('id', chirp_id);
$(div1).css('display','none');
if($(div1).is(':visible'))
{
return;
}
else
{
// Before the 'cancel' button I append the textarea and 'save' button
var cancel = $('<button></button>');
cancel.attr("id","cancelEdit");
cancel.text("Cancel");
cancel.addClass('button');
cancel.appendTo(div2);
$('#cancelEdit').click(function()
{
$(div1).fadeOut("slow");
});
}
my_edit = edit;
});
I call my function with javascript
function edit_chirp(chirp_id)
{
my_edit(chirp_id);
}
Try this .. bind event with dom not with ID ..
$(function () {
function edit(chirp_id) {
var div1 = $('<div></div>');
div1.addClass('thumb2');
div1.attr('id', chirp_id);
$(div1).css('display', 'none');
if ($(div1).is(':visible')) {
return;
} else {
//Before the 'cancel' button I append the textarea and the 'save' button
var cancel = $('<button></button>');
cancel.attr("id", "cancelEdit");
cancel.text("Cancel");
cancel.addClass('button');
cancel.appendTo(div2);
cancel.click(function () {
$(div1).fadeOut("slow");
});
}
my_edit = edit;
});
Better use delegates using .on event handler because your div1 is created dynamically
$(document).on('click', '#cancelEdit', function () {
$(div1).fadeOut("slow");
});
Missing to close edit function
probably to do with closure. try:
cancel.click(function (event) {
$(event.target).closest(".thumb2").fadeOut("slow");
});

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!');
});
});

Categories

Resources