Click on button first time show alert, click second time execute code - javascript

I want to show users, when they click on a button for the first time, an alert when in a date field a value is chosen which lies before the current date. When they insist to this choice for good reasons, I want them to give a second chance to click on the same button, and then the value has to be submitted.
The click event is defined in a function:
$("#edit_date_btn").click(function(){
// do something and save
}
In an other function the comparing is handled. The basic code is:
function edit_date_compare() {
....
if(usersDate < today)
{ //show alert
return false; // needed for the first click so the input is not submitted
}
I've tried several options e.g. with a count on the click function (on a second click 'return true;' instead of 'return false;') but it seems difficult to handle this situation. Any ideas how to make this successful? It could be with Javascript or jQuery.

You have the right idea with the count on the click function. I suspect you might have difficulty implementing it. You need a separate variable that tracks the number of clicks. Here's a working fiddle: http://jsfiddle.net/zwmquxaL/
$(document).ready(function () {
var clickCount = 0;
$("#btnSave").click(function () {
if (clickCount > 0) {
AlertSave();
} else {
AlertFirst();
clickCount++;
}
});
});
function AlertSave() {
alert("Some code has been executed!");
}
function AlertFirst() {
alert("Are you sure you want to perform this operation?");
}

Related

Call a method once, only if button is clicked (atleast once)

I would like to call loadNext() method only once, if any of the other buttons are clicked at least once.
I have checked out: Calling a Method Once
For example, I am making a quiz app, having question and some options for each question types.
User will select an option and hit on next button to load the next question(with options), (those are predefined in an array). loadNext() shouldn't be called multiple times even if the options are clicked more than once (to prevent this I avoided calling loadNext() inside onclick method of those options(buttons), and also wont load if none of the options are selected,
and my idea is something like pre-defining isClicked as false, and inverting inside onclick method of those options, but that is not working.
What I have done, so far:
var optButtons = $(".opt button");
var isClicked = false;
optButtons.click(function () {
isClicked = true;
console.log("clicked on opt buttons: " + this.id);
console.log("Current button is: " + this.id + " set as active");
//other stuffs
});
//some other stuffs
if (isClicked) {
console.log("Clicked once!");
//other stuffs
loadNext();
} else {
alert("Please select an option");
//browser is alerting very first time after opening `index.html` file
// and Next button click isn't working after that
}
Any instruction will be appreciated, thanks in advance!
I am new in JS.
How about something of the sort, assuming you have an id="next" for your Next button
$("#next").on('click',function(){
if(isClicked){
loadNext();
// Set isClicked to false to reset mechanism
isClicked = false;
}
});
Would this be what you' re looking for ? I understood it this way
you are logging to console when the option buttons are clicked, and that is Ok, but in the onClick listener for the next button, check if the only one option is clicked or not.. and you can create a variable in global scope to check how many
times the next button is clicked, code snippet is
//function called on clicking the next button
function abcd(){
counter++;
if(counter!=-1){
return;
}
else{
//call the loadnext()
}
}
I guess you have your answer with radio buttons. You can try 'radio buttons' for the options. There are enough and more references online. Please let me know if that doesn't suit your requirement.

Disable button until one radio button is clicked

So I'm busy on a registration, and I want people to choose their gender. I do this by the use of radio buttons. Now, what I want, is to have a disabled post button untill one of the two boxes is selected, this I do with jQuery:
var $radio = $("input:radio");
$radio.change(function()
{
var checkedButtons = false;
$radio.each(function() {
if (this.checked)
{
var checkedButtons = true;
return false;
}
});
if (checkedButtons)
{
$("#postGender").removeAttr("disabled");
}
else
{
$("#postGender").attr("disabled", "disabled");
}
});
This little piece is code, was found by me on stackoverflow. The only thing wrong is that it doesn't work.
See this for more code and ofcouse a demo: JsFiddle
You could reduce all that to one line:
$("input:radio").change(function () {$("#postGender").prop("disabled", false);});
jsFiddle example
Remove the var within the first if block. var checkedButtons = true; is creating a different checkedButtons within the scope of that block. So the first checkedButtons will be unchanged, and the other is gone once the if block is finished.
It should just be checkedButtons = true;
You can simplify this greatly.
If you think about it, once they click on a radio button, they can't really deselect it: they can only click on another radio button. So, once the button has changed once, there's really no need to monitor it anymore and you can just enable the button from there.
$("input:radio").change(function () {
$("#postGender").attr("disabled", false);
});
Demo
Something like this should do:
var $radio = $("input:radio");
$radio.change(function () {
if ($radio.filter(':checked').length > 0) {
$("#postGender").removeAttr("disabled");
} else {
$("#postGender").attr("disabled", "disabled");
}
});
http://jsfiddle.net/n6sta3dp/8/
A few sidenotes:
Once a radio button has been checked, it can never be unchecked by the user (unless he starts using the js console). I think it would be safe to remove the 'else' part in your function.
Don't forget that a form can also be submitted by using the enter key, so just disabling the button will not be enough. You should probably listen for the submit event of your form as well and check if the user made a choice before letting the submit go trough.

Preventing multiple clicks on button

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]
Is there a better method to prevent the second click on the button before the page loads back?
Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?
Note: I am looking for a solution that won't require any new API
Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()
Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.
Present Code
$(document).ready(function () {
var noIndicator = 'No';
var yesIndicator = 'Yes';
var isOperationInProgress = 'No';
$('.applicationButton').click(function (e) {
// Prevent button from double click
var isPageValid = Page_ClientValidate();
if (isPageValid) {
if (isOperationInProgress == noIndicator) {
isOperationInProgress = yesIndicator;
} else {
e.preventDefault();
}
}
});
});
References:
Validator causes improper behavior for double click check
Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
Note by #Peter Ivan in the above references:
calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).
I found this solution that is simple and worked for me:
<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>
This solution was found in:
Original solution
JS provides an easy solution by using the event properties:
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
// code here. // It will execute only once on multiple clicks
}
});
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
working example
I modified the solution by #Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
After hours of searching i fixed it in this way:
old_timestamp = null;
$('#productivity_table').on('click', function(event) {
// code executed at first load
// not working if you press too many clicks, it waits 1 second
if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
{
// write the code / slide / fade / whatever
old_timestamp = event.timeStamp;
}
});
you can use jQuery's [one][1] :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
May be this will help and give the desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>
We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.
$(document).ready(function () {
$("#disable").on('click', function () {
$(this).off('click');
// enter code here
});
})
This should work for you:
$(document).ready(function () {
$('.applicationButton').click(function (e) {
var btn = $(this),
isPageValid = Page_ClientValidate(); // cache state of page validation
if (!isPageValid) {
// page isn't valid, block form submission
e.preventDefault();
}
// disable the button only if the page is valid.
// when the postback returns, the button will be re-enabled by default
btn.prop('disabled', isPageValid);
return isPageValid;
});
});
Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).
The absolute best way I've found is to immediately disable the button when clicked:
$('#myButton').click(function() {
$('#myButton').prop('disabled', true);
});
And re-enable it when needed, for example:
validation failed
error while processing the form data by the server, then after an error response using jQuery
Another way to avoid a quick double-click is to use the native JavaScript function ondblclick, but in this case it doesn't work if the submit form works through jQuery.
One way you do this is set a counter and if number exceeds the certain number return false.
easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.
First set add a style to your button:
<h:commandButton id="SaveBtn" value="Save"
styleClass="hideOnClick"
actionListener="#{someBean.saveAction()}"/>
Then make it hide when clicked.
$(document).ready(function() {
$(".hideOnClick").click(function(e) {
$(e.toElement).hide();
});
});
Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.
<script type="text/javascript">
$(document).ready(function(){
$("#button1").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script
Plain JavaScript:
Set an attribute to the element being interacted
Remove the attribute after a timeout
If the element has the attribute, do nothing
const throttleInput = document.querySelector('button');
throttleInput.onclick = function() {
if (!throttleInput.hasAttribute('data-prevent-double-click')) {
throttleInput.setAttribute('data-prevent-double-click', true);
throttleInput.setAttribute('disabled', true);
document.body.append("Foo!");
}
setTimeout(function() {
throttleInput.removeAttribute('disabled');
throttleInput.removeAttribute('data-prevent-double-click');
}, 3000);
}
<button>Click to add "Foo"!</button>
We also set the button to .disabled=true. I added the HTML Command input with type hidden to identify if the transaction has been added by the Computer Server to the Database.
Example HTML and PHP Commands:
<button onclick="myAddFunction(<?php echo $value['patient_id'];?>)" id="addButtonId">ADD</button>
<input type="hidden" id="hasPatientInListParam" value="<?php echo $hasPatientInListParamValue;?>">
Example Javascript Command:
function myAddFunction(patientId) {
document.getElementById("addButtonId").disabled=true;
var hasPatientInList = document.getElementById("hasPatientInListParam").value;
if (hasPatientInList) {
alert("Only one (1) patient in each List.");
return;
}
window.location.href = "webAddress/addTransaction/"+patientId; //reloads page
}
After reloading the page, the computer auto-sets the button to .disabled=false. At present, these actions prevent the multiple clicks problem in our case.
I hope these help you too.
Thank you.
One way I found that works is using bootstrap css to display a modal window with a spinner on it. This way nothing in the background can be clicked. Just need to make sure that you hide the modal window again after your long process completes.
so I found a simple solution, hope this helps.
all I had to do was create a counter = 0, and make the function that runs when clicked only runnable if the counter is = 0, when someone clicks the function the first line in the function sets counter = 1 and this will prevent the user from running the function multiple times when the function is done the last line of the code inside the function sets counter to 0 again
you could use a structure like this, it will execute just once:
document.getElementById('buttonID').addEventListener('click', () => {
...Do things...
},{once:true});

Multiple clicks required to complete two functions

I have some javascript that for some reason requires two consecutive clicks in order to function correctly. Here is the code for the link:
Select All
Now, here is the code for the function that is called with the onclick:
function select_all_com(){
$("[name=file_com_appeal].com-checkbox").each( function() {
$(this).attr('checked', true);
});
UpdateTotalFee();
}
and finally, here is the last bit of code:
function UpdateTotalFee(){
var AppealCount = 0;
$('input[name=file_com_appeal].com-checkbox').each(function(){
if( $(this).next().hasClass('checked') ){
AppealCount++; }
});
$('#AppealFeeTotal').text("$"+(AppealCount*140));
}
This final part is supposed to run the first time the link is clicked but some reason it does not run the first time, only the second time. Specifically what I mean is that the first click updates all of the checkboxes from off to on, but does not update the #AppealFeeTotal. A subsequent click of the Select All link when the checkboxes are already selected then causes the #AppealFeeTotal to update.
Any ideas why this might be requiring two clicks? I should also add that there is one line of code in particular that I am unsure about. I inherited the code from someone else, and I'm not sure of the reason why this is used:
if( $(this).next().hasClass('checked') ){
Thanks for any ideas you might have.
A few things, first attr('checked') is not the same as hasClass('checked') I suspect this is where your problem is. Your code does not add a "checked" class that I can see, but you're counting where that is the case. You should be using is:checked selector for this.
Second, if I read your code correctly, you're just counting checked checkboxes to get your total. You can do this more efficiently like this:
$(":checkbox").filter(':checked').length
Naturally you'll want to refine that selector (so it only counts specific checkboxes) but without more html, I can't help with that.
$(document).ready( function() { // this is a function which execute when document is ready in jQuery
var clicks = 0; // I am taking clicks variable so, to check whether the user have clicked for the first time
$("a").on("click", function() { // this is a function which execute when target anchor tag is clicked
clicks++; // now user have clicked the anchor tag so, i have to increase value to 1
if(clicks==1) { // this condition checks whether user have clicked the anchor tag for the first time? if yes, then execute the code
$("[name=file_com_appeal].com-checkbox").each( function() { // this is a each function which loops through all targets perform operations
$(this).attr('checked', true); // while looping through all targets this will set attribute or property "checked" to true means its checked
});
}
else if(clicks==2) { // this conditions check that whether anchor tag is clicked for second time
var AppealCount = 0;
$('input[name=file_com_appeal].com-checkbox').each(function(){
if( $(this).prop('checked') ){
AppealCount++;
}
});
$('#AppealFeeTotal').text("$"+(AppealCount*140));
clicks = 0; // set to zero because if user repeatedly clicks the anchor tag
}
});
});

Button needs to be clicked twice to trigger function

I know this would be difficult to understand but please give a try.
Have a look at the screenshot.
The small input box's name is murl.
add() is used to submit the form. if murl is empty the form has to be submitted directly, if its not empty the murl entry has to be checked against the database if it exists. if it doesn't exist add() is called.
The problem is the button has to be clicked twice to trigger the function.
The code on the button is:
<button type="button" value="My button value" onclick="javascript: niju();" name="microsubmit" id="microsubmit">button</button>
the JavaScript which that button calls is:
function niju()
{
var flag=1;
var micro=document.getElementById('murl').value;
$('#microsubmit').click(function()
{
if(micro=="")
{
add();
}
else
{
//remove all the class add the messagebox classes and start fading
$("#msgbox")
.removeClass()
.addClass('messagebox')
.text('Checking...')
.fadeIn("slow");
//check the username exists or not from ajax
$.post("<?php echo SITE_ROOT;?>inc/user_availability.php",
{ murl: $("input:murl").val() },
function(data)
{
if(data=='no') //if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this)
.html('This User name Already exists')
.addClass('messageboxerror')
.fadeTo(900,1);
flag=0;
});
}
else
{
$("#msgbox")
//start fading the messagebox
.fadeTo(200,0.1,function()
{
//add message and change the class of the box and start fading
$(this)
.html('Username available to register')
.addClass('messageboxok')
.fadeTo(900,1);
flag=1;
add();
});
}
});
}
});
if(micro=="" && flag==1)
{
add();
}
}
Screenshot:
It has to be clicked twice because you are defining #microsubmit's click event inside the function. So the first time you click you bind the event handler, and the 2nd time the event handler is in place and gets fired. I haven't gone over the logic behind what you're trying to accomplish but my guess is that if you move the event binder outside the function and make sure all your variables are in the right scopes then it'll work.
The first time you load the page, the click handler is not hooked to the button, is only until you click the button the first time that you are calling the niju() and hooking the click event. You need to do something like
$(document).ready() {
niju();
}
and remove the onclick from the button declaration
Move your flag out of the function niju.
var flag=1;
function niju()
{
}

Categories

Resources