my jquery event handler for a button only works once - javascript

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

Related

why unable to get alert on click of button

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

How do I trigger a click event on a disabled button element (using pure vanilla JS)?

I have this event: this.show.onclick = this.sendData.bind(this);
in my bindEvents() function:
bindEvents: function() {
var that = this;
// On click "Show" BTN
this.show.onclick = this.sendData.bind(this);
// On Change inputs
this.$form.change(function(){
that.updateDatesInputs(this);
});
},
That runs this:
sendData: function(e) {
e.preventDefault();
let that = this;
console.log(this.show.disabled);
if (this.show.disabled) {
alert('a disabled button has just been clicked!');
this.showErrorDiv("Please select a new date range.");
} else {
$.ajax({
....
}
});
that.dataDisplayed = true;
}
Clicking on my "show" button-element doesn't activate any click event. All I found googling this is that jQuery can fix it, but I want to use vanilla JS.
How can I trigger an event on a disabled element so that my alert will get executed using only pure JS?
It cannot be done, nor should it for accessibility reasons. Someone who navigates with a keyboard can never get to the button to interact with it.

Show a Div first and then Submit on second click of button in a form

I have a form with multiple divs with same names (full-width). They all are on the same level. One of them is hidden (with a class hide). What I want is that if I select Submit, it should not submit, first hide all the brother divs of the hidden div (in this case full-width) and unhide the one with the class hide.
Now when I press again, it should just submit the Form.
JSFiddle is here:- http://jsfiddle.net/xmqvx/2/
Your code had a couple issues:
You used event.preventDefault but passed event in as e - should be e.preventDefault
Your ID selector targeted an ID that didnt exist (changed to #submit-this)
The working code:
$("#submit-this").click(function (e) {
e.preventDefault();
if ($(".full-width").hasClass("hide")) {
$(".full-width").hide();
$(".full-width.hide").removeClass("hide").show();
} else {
alert("Submitting");
$("#this-form").submit();
}
});
http://jsfiddle.net/xmqvx/4/
You could also take advantage of JavaScript's closures like so, to avoid having your behavior be dependent on your UI:
$(document).ready(function () {
var alreadyClicked = false;
$("#submit-this").click(function (e) {
e.preventDefault();
if (alreadyClicked) {
$('#this-form').submit();
} else {
$('.full-width').hide();
$('.hide').show();
alreadyClicked = true;
}
});
});

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

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