I tried doing it two different ways:
$(document).ready(function()
{
$('input[type=button]').on('click', function(evt){
if ($(this).val() == 'Close')
return true;
var totalHours = 999; // here I am computing a total number of hours but that is irrelevant to my question
var reportedTotalHours = parseFloat($("#TotalHours").text());
var difference = Math.abs(totalHours - reportedTotalHours);
if (difference >= 0.25) // discrepancy must be less than a quarter hour
{
alert("Total of hours for each activity must equal " + reportedTotalHours + ".");
evt.preventDefault();
return false;
}
return true;
});
});
return false; should be cancelling the button click, as should evt.preventDefault();, but neither of them is working for me. What happens when the button is clicked is the form is submitted, but I want to prevent the form from being submitted until the discrepancy in hours is less than 0.25.
Try changing your input[type=button] to a button tag. Then submit your form in your onclick callback when the conditions are right.
In some browsers an input[type=button] element will submit a form if there's no input[type=submit] element.
const prev = document.querySelector('.prev')
let current = 2
if(current >= 1) {
prev.disabled = false
}else {
prev.disabled = true
}
<button class="prev">Prev</button>
Related
When the submit button is clicked that event is also handled by some code that submits the form - I would share that code too but I'm having trouble finding it. My problem is that I want to be able to cancel the form submission from the button click event (as you can see I tried several methods of doing so), but instead what happens is that the validation message appears that the hours don't match up and then a few seconds later a message appears saying that the form was submitted.
$(document).ready(function() {
// find total hours
var reportedTotalHours = parseFloat($("#TotalHours").text());
if (!reportedTotalHours) {
reportedTotalHours = parseFloat($("#EventDuration").text());
$("#TotalHours").text(reportedTotalHours)
}
// handle button click
$('input[type=button]').on('click', function(evt) {
if ($(this).val() == 'Close')
return true;
var totalHours = 0;
$('select.dropdownQuestion').each(function(i, sel) {
var hours = $(sel).find(":selected").text();
var f = parseFloat(hours);
if (f != 0 && !Number.isNaN(f))
totalHours += f;
});
// validate that hours are within a quarter hour of each other
var difference = Math.abs(totalHours - reportedTotalHours);
if (difference >= 0.25) // discrepancy must be less than a quarter hour
{
alert("Total of hours for each activity must equal " + reportedTotalHours + ".");
evt.preventDefault();
evt.stopPropagation();
$("#SkipSave").val('true');
return false;
}
return true;
});
});
I think the problem might be that I'm in a button click event handler and I'm trying to cancel a form submit event instead, but if I change this:
$('input[type=button]').on('click', function(evt) {
to
$('form').submit(function(evt) {
then the validation never seems to happen at all.
I'm trying to write a program in JavaScript in which certain functions must be performed before a button can be pressed again.
The button performs a function that should only be performed once per turn, but I want other actions to be performed before the next turn, and to have a sort of confirmation before progressing to the next turn. In psuedocode it might look something like this:
buttonFunction();
actionOne();
actionTwo();
turnOverConfirm();
etc.
But I'm not so sure how to do that. Right now the button can be pressed at any time. How do I make it so that the user must confirm before the button can be pressed again?
You can disable and enable buttons via javascript. You could block it like that:
document.getElementById("button").disabled = true
Just set it to false again to make it clickable again!
You can use the javascript confirm function. This function will popup a message box with ok and cancel
Here is an example
var r = confirm("Press a button!");
if (r == true) {
alert("OK was clicked");
} else {
alert("Cancel was clicked");
}
What you can do is when a user clicks on a button, popup a confirm box, then if they click ok you can then run the function you listed above.
There are few ways
You can hide the button till processing is ready or replace with an "please wait..." image
You can create an prevent varaible or remove temporary click event function
var Action = (function(){
var prevent = false;
function _start() {
if (prevent === false) {
prevent = true;
_process();
}
}
function _process() {
// DO Action
prevent = false;
}
return { start: _start }
})();
Fire
you can make event for evry click here is an example with alert and change button color all in one function
var clicked = 0;
var btn = document.getElementById("btn");
function clickBtn(){
if (clicked == 0) {
alert("it's first click");
btn.style.background = "black";
clicked = 1;
}else if (clicked == 1) {
alert("it's second click");
btn.style.background = "orange";
clicked = 2;
} else if (clicked == 2) {
alert("it's third click");
btn.style.background = "green";
clicked = 3;
}
}
#btn{
border-radius:15px 0 15px 0;
color:white;
border:none;
padding:15px;
background:blue;
font-weight:bold;
}
#btn:hover{
border-radius:0 15px 0 15px;
}
<button id="btn" onclick="clickBtn()">Click Me</button>
I apologize in advance for my ignorance... We have an order form where we'd like the users to order at least 6 items (not each necessarily but sum/combination of items that equals 6 or more). I have it totaling the quantities up but not a working onclick/onsubmit function that can alert you to reach the minimum order quantity before submitting the form. Any ideas? Thanks in advance. In lieu of posting all the actual code i'm hoping this is enough info to go on. If not I can create some dummy text to apply if necessary.
Add a class to the inputs you want to tally:
<input name="LEDname" type="text" id="v8" class="tallyable" />
Then scrub and tally them up on keyup, then enable or disable submit if value is >= 6:
$('.tallyable').on('keyup', function () {
var total = getTotal();
$('#orderCount').html(total);
enableOrDisableSubmit(total);
});
function getTotal(){
var total = 0;
$('.tallyable').each(function(){
if ($(this).val().trim().length > 0) {
var currentVal = isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
total += currentVal;
$(this).val(currentVal);
}
});
return total;
}
function enableOrDisableSubmit(val) {
if (val >= 6) {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', 'disabled');
}
}
Here is a fiddle
I am creating a math problem website and in one page I have a part where the user clicks submit and it will check whether the answer is right or wrong.
Here is the main part of my code that I am having trouble with:
var newProblem = function(){
var textHide = true;
var submitTimes = 0
$("#content").append("<h2 class='middle_text'>Notice, this page is in BETA stage, improvement is still needed.</h2>")
$(".middle_text").fadeTo(1000,.8)
setTimeout(function(){$(".middle_text").fadeTo(500,0,function(){$(".middle_text").hide()})},4000);
setTimeout(function(){
var denominator = getNumbersEquivFrac.den()
var numerator = getNumbersEquivFrac.num(denominator);
var equivalent = getNumbersEquivFrac.equiv()
var problem = new equivalFrac(numerator,denominator,equivalent);
$("#content").append("<div class ='problem-choice' id='solve'>SOLVE THIS!</div>")
$("#content").append("<div class='problem-choice' id='answer'>SKIP AND GET ANSWER</div>")
$("#content").append("<div style='margin:auto; width:450px; text-align:center'><p id='question'>" + problem.printQuestion() + "</p>")
$("#content").append("<div id='instructions'></div>")
$("#question").fadeTo(750,1);
$(".problem-choice").fadeTo(750,1);
$("#solve").click(function(){
if(textHide === true){
$("#content").append("<form name='answer'><input class='problem-text' type='text' name='answer-input'><input type='button' class='problem-submit' value ='SUBMIT ANSWER'></form>");
$(".problem-text").fadeTo(300,.8)
$(".problem-submit").fadeTo(300,.8)
textHide = false
}
})
},4500)
}
newProblem();
$(".problem-submit").click(function(){
var checkAnswer = function(){
var answer = document.forms["answer"]["answer-input"].value;
if(answer === null || answer === ""){
alert("You must type in an answer.")
}
else{
submitTimes = submitTimes + 1;
if(answer !== problem.answer()){
if(submitTimes < 2){
$("#content").append("<div class='result' id='wrong'><div id='problem-des'><p>The correct answer was " + problem.answer() + "." + "</p></div><button id='next'>NEXT</button></div>");
$(".result").fadeTo(500,1)
}
}
else if(answer===problem.answer()){
if(submitTimes < 2){
alert("Correct!")
}
}
}
}
checkAnswer()
});
This is where the event is for the form submit button
$(".problem-submit").click(function(){
var checkAnswer = function(){
var answer = document.forms["answer"]["answer-input"].value;
if(answer === null || answer === ""){
alert("You must type in an answer.")
}
else{
submitTimes = submitTimes + 1;
if(answer !== problem.answer()){
if(submitTimes < 2){
$("#content").append("<div class='result' id='wrong'><div id='problem-des'><p>The correct answer was " + problem.answer() + "." + "</p></div><button id='next'>NEXT</button></div>");
$(".result").fadeTo(500,1)
}
}
else if(answer===problem.answer()){
if(submitTimes < 2){
alert("Correct!")
}
}
}
}
checkAnswer()
});
I don't know if it is the fact that the event is being called on a selector that was appended through the code and not originally in the html document.
I tried calling the event on parts of the page that were originally there, it worked.
But it isn't working for these, if you have any idea why, please say so.
You can asign an ID to your form, an use in the submit function:
$(document).on('submit','id_form',function(e) {
e.preventDefault();
}
Have you tried using using jquery's .on() function which essentially attaches the click event handler to any element that may have been created after the DOM was originally completed.
more info here: http://api.jquery.com/on/
$(".problem-submit").on('click',function(){
//function here
});
I have created a form with malsup's Form Plugin wherein it submits on change of the inputs. I have set up my jQuery script to index drop down menus and visible inputs, and uses that index to determine whether keydown of tab should move focus to the next element or the first element, and likewise with shift+tab keydown. However, instead of moving focus to the first element from the last element on tab keydown like I would like it to, it moves focus to the second element. How can I change it to cycle focus to the actual first and last elements? Here is a live link to my form: http://www.presspound.org/calculator/ajax/sample.php. Thanks to anyone that tries to help. Here is my script:
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
var shiftDown = false;
$('input, select').each(function (i) {
$(this).data('initial', $(this).val());
});
$('input, select').keyup(function(event) {
if (event.keyCode==16) {
shiftDown = false;
$('#shiftCatch').val(shiftDown);
}
});
$('input, select').keydown(function(event) {
if (event.keyCode==16) {
shiftDown = true;
$('#shiftCatch').val(shiftDown);
}
if (event.keyCode==13) {
$('#captured').val(event.target.id);
} else if (event.keyCode==9 && shiftDown==false) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var nextEl = fields.eq(index+1).attr('id');
var firstEl = fields.eq(0).attr('id');
var focusEl = '#'+firstEl;
if (index>-1 && (index+1)<fields.length) {
$('#captured').val(nextEl);
} else if(index+1>=fields.length) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(firstEl);
} else {
event.preventDefault();
$(focusEl).focus();
}
}
return false;
});
} else if (event.keyCode==9 && shiftDown==true) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var prevEl = fields.eq(index-1).attr('id');
var lastEl = fields.eq(fields.length-1).attr('id');
var focusEl = '#'+lastEl;
if (index<fields.length && (index-1)>-1) {
$('#captured').val(prevEl);
} else if (index==0) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(lastEl);
} else {
event.preventDefault();
$(focusEl).select();
}
}
return false;
});
}
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 100 );
}
}
Edit #1: I made a few minor changes to the code, which has brought me a little closer to my intended functionality of the script. However, I only made one change to the code pertaining to the focus: I tried to to disable the tab keydown when pressed on the last element (and also the shift+tab keydown on the first element) in an attempt to force the focus on the element I want without skipping over it like it has been doing. This is the code I added:
$(this).one('keydown', function (event) {
return !(event.keyCode==9 && shiftDown==true);
});
This kind of works. After the page loads, If the user presses tab on the last element without making a change to its value, the focus will be set to the second element. However, the second time the user presses tab on the last element without making a change to its value, and every subsequent time thereafter, the focus will be set to the first element, just as I would like it to.
Edit #2: I replaced the code in Edit #1, with code utilizing event.preventDefault(), which works better. While if a user does a shift+tab keydown when in the first element, the focus moves to the last element as it should. However, if the user continues to hold down the shift key and presses tab again, focus will be set back to the first element. And if the user continues to hold the shift key down still yet and hits tab, the focus will move back to the last element. The focus will shift back and forth between the first and last element until the user lifts the shift key. This problem does not occur when only pressing tab. Here is the new code snippet:
event.preventDefault();
$(focusEl).focus();
You have a lot of code I didn't get full overview over, so I don't know if I missed some functionality you wanted integrated, but for the tabbing/shift-tabbing through form elements, this should do the work:
var elements = $("#container :input:visible");
var n = elements.length;
elements
.keydown(function(event){
if (event.keyCode == 9) { //if tab
var currentIndex = elements.index(this);
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
if (el.attr("type") == "text")
elements.eq(newIndex).select();
else
elements.eq(newIndex).focus();
event.preventDefault();
}
});
elements will be the jQuery object containing all the input fields, in my example it's all the input fields inside the div #container
Here's a demo: http://jsfiddle.net/rA3L9/
Here is the solution, which I couldn't have reached it without Simen's help. Thanks again, Simen.
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
$('#calculator :input:visible').each(function (i) {
$(this).data('initial', $(this).val());
});
return $(event.target).each(function() {
$('#c_main :input:visible').live(($.browser.opera ? 'keypress' : 'keydown'), function(event){
var elements = $("#calculator :input:visible");
var n = elements.length;
var currentIndex = elements.index(this);
if (event.keyCode == 13) { //if enter
var focusElement = elements.eq(currentIndex).attr('id');
$('#captured').val(focusElement);
} else if (event.keyCode == 9) { //if tab
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
var focusElement = el.attr('id');
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(focusElement);
} else if ((currentIndex==0 && event.shiftKey) || (currentIndex==n-1 && !event.shiftKey)) {
event.preventDefault();
if (el.attr('type')=='text') {
$.browser.msie ? "" : $(window).scrollTop(5000);
el.select().delay(800);
} else {
$.browser.msie ? "" : $(window).scrollTop(-5000);
el.focus().delay(800);
}
} else if (el.is('select')) {
event.preventDefault();
if (el.attr('type')=='text') {
el.select();
} else {
el.focus();
}
}
}
});
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 1 );
}
}
I put my files available to download in my live link: http://www.presspound.org/calculator/ajax/sample.php