The problem I am having is that I cannot get the event.preventDefault() to stop the form from submitting in the nested if statements below the first condition testing the Parent Ticket against Original Ticket (which does work as expected). It appears to loose the ability to call the event handler. I have tried return false, event.stopPropagation(), event.stopImmediatePropagation() and nothing works inside the nested conditions. Could anyone shed some light on this for me?
$( "#editTicket" ).submit(function( event ) {
var inputTicket = $('input[name=parentTicketID]').val();
var orginalTicketID = $('input[name=id]').val();
// Parent Ticket cannot be the original ticket
if ( inputTicket == orginalTicketID )
{
$("#parentTicketMessage").html("The parent ticket number is the same the original ticket. Please change the parent ticket number.");
$('input[name=parentTicketID]').focus();
event.preventDefault();
}
if ( inputTicket != orginalTicketID && inputTicket.length > 0)
{
$.get("/resources/cfc/qmdata/ticket.cfc?method=getTicketArray&returnformat=json",{id:inputTicket}).done(function(data)
{
var thisTicketID = JSON.parse(data);
if ( thisTicketID.toString().length == 0 )
{
alert("inside bad ticket");
$("#parentTicketMessage").html("This is not a valid ticket number. Please change the parent ticket number.");
$('input[name=parentTicketID]').focus();
event.preventDefault();
}
else if (thisTicketID[0].ticketID.toString().length > 0 && thisTicketID[0].parentTicketID.toString().length > 0)
{
$.get("/resources/cfc/qmdata/ticket.cfc?method=getTicketArray&returnformat=json",{parentTicketID:inputTicket}).done(function(data2)
{
var thisParentTicketID = JSON.parse(data2);
// We need to check to see if the parentTicketID has not been used on this page.
if (thisParentTicketID.toString().length != 0 && thisParentTicketID[0].ticketID != inputTicket)
{
alert("already used");
// This is the child ticket check and is already being used...stop processing and display message
$("#parentTicketMessage").html("This ticket number is already a child ticket and cannot be used."); $('input[name=parentTicketID]').focus();
event.preventDefault();
}
});
};
});
}
});
'''
What I am trying to accomplish is simply add a message to the form when certain conditions are met and stop the form from being posted until the user fixes the issue.
Related
I am currently trying to synchronize two checkboxes on a page.
I need the checkboxes to be synchronized - to this end, I'm using a Tampermonkey userscript to pick up when one of them is clicked. However, I'm at a loss as to how to do it.
I believe they are not actually checkboxes, but ExtJS buttons that resemble checkboxes. I can't check whether they're checked with JQuery because of this: the checked value is appended to a class once the JS behind the button has run.
I have tried preventDefault and stopPropagation, but either I'm using it wrong or not understanding its' usage.
I'm not quite clever enough to just call the JS behind the box instead of an onclick event. Otherwise, that would solve my issue.
This is my code:
//Variables - "inputEl" is the actual button.
var srcFFR = "checkbox-1097";
var destFFR = "checkbox-1134";
var srcFFRb = "checkbox-1097-inputEl";
var destFFRb = "checkbox-1134-inputEl";
//This checks if they're synchronised on page load and syncs them with no user intervention.
var srcChk = document.getElementById(srcFFR).classList.contains('x-form-cb-checked');
var destChk = document.getElementById(destFFR).classList.contains('x-form-cb-checked');
if (srcChk == true || destChk == false) {
document.getElementById(destFFRb).click();
} else if (destChk == true || srcChk == false) {
document.getElementById(srcFFRb).click();
}
//This is where it listens for the click and attempts to synchronize the buttons.
$(document.getElementById(srcFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(destFFRb).click();
}
});
$(document.getElementById(destFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(srcFFRb).click();
}
});
I'm at a bit of a loss...any help would be greatly appreciated.
Figured it out - I was comparing class lists without singling out what I wanted to actually match.
My solution:
$(document.getElementById(srcFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(destFFRb).click();;
}});
$(document.getElementById(destFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(srcFFRb).click();;
}});
can someone explain this to me? why is it prompt() running again?
And please give me some advice where and what should i change to have a better code. thank you.
function welcomeGuest() {
do {
guestName = prompt("Welcome to my Anime Website! May I know your name?");
if (guestName === null || guestName === false) {
alert("Please come back again.");
window.close();
}
if (guestName === "") {
alert("Please enter your name!");
} else if (guestName.length < 4) {
alert("Your name should be atleast 4 characters!");
} else if (!(isNaN(guestName))) {
alert("Your name can't be number!");
} else {
guestNamesmall = guestName.slice(1, guestName.length);
alert("Welcome to my Anime Website, " + guestName.charAt(0).toUpperCase() + guestNamesmall + "!");
//bodyContent();
}
} while (guestName.length < 4 || !(isNaN(guestName)));
}
// EDIT: adding call to function for demo purposes
welcomeGuest();
EDIT : I'm sorry but my question is when I enter correct input(it should go to else statement, right?) but what happens to me is that the prompt is running again if else statement is met. Why is that?
if you call your welcomeGuest function only once and the condition inside your while loop is respected guestName.length < 4 || !(isNaN(guestName))it will not running again.
The reason prompt is showing up again is because you have it in a loop until your condition is met. Therefore if guestName.length < 4 || !(isNaN(guestName)) is never met, then it will continue to show.
I would avoid using a loop for something like this. You can use css to prevent a user from going through your site instead of continuously prompting them through a loop. Then use events to handle your logic. Do you have a submit/enter button? Then add your logic on the click event. If not, then you can do it on the key down event and look for the enter key.
for example:
var textbox = document.getElementById("idOfTextbox")
with option 1
textbox.addEventListener("keydown", function(event) {
//stop the click event from propagating
event.preventDefault();
//check if enter key was clicked (#13)
if (event.keyCode == 13) {
//do your logic to verify pass/fail of user input
}
});
or option 2
textbox.addEventListener("click", function(event) {
//stop the click event from propagating
event.preventDefault();
//do your logic to verify pass/fail of user input
});
There are other events you may use, but I think these two would be the most beneficial in this situation.
$(document).ready( function()
{
// hides the story and error text when the page loads
$('.errorText').hide();
$("#story").hide();
// global variables for the blanks and the textarea forms
var input = $("form").children();
var storyBlank = $('#story').children();
// Main Event on Click
$('button.submit').on( "click", function (event)
{
// if the form is not validated, highlights errors and prevents the submit from going through
if(!validate())
{
event.preventDefault();
}
// if the form is validated, fills the blanks in the story and displays it
else
{
fillInTheBlanks();
}
});
// Checks to see if there are any empty fields and highlights them if they are empty
function validate()
{
console.log('validate() initiated')
var success = false;
errcnt = 0;
cnt = 0;
while (cnt < 9)
{
if (input.eq(cnt).val().length == 0)
{
errcnt++;
input.eq(cnt).removeClass("hide");
console.log('errorcount', errcnt, 'at input', cnt);
}
else if (input.eq(cnt).val().length !== 0 && !(input.eq(cnt)).hasClass("hide"))
{
input.eq(cnt).addClass("hide");
}
cnt++;
}
if (errcnt == 0)
{
success = true;
}
return success;
}
// Fills in the blanks of the story
function fillInTheBlanks()
{
console.log('fillInTheBlanks() executed');
var blankCount = 0;
while (blankCount < 9)
{
storyBlank.eq(blankCount).empty().append(input.eq(blankCount).val());
blankCount++;
}
$("#story").show();
}
});
I am trying to make a mad libs style page with 9 textboxes for input. I am running into two problems.
First, when I click submit with all textboxes empty, only the the first four show an error (this is done in css, I have two classes on all the textboxes "error hide", I remove the class hide in my loop to show the error).
The second problem I'm having is if I click submit with text in all the textboxes, my validate functions errorcount goes up to 4 errors at every other textbox. I've even tried '$('input').eq(0).val().length == 0' for every textbox in the index and it's returning false every time. I don't understand how it's getting into that if then statement if it doesn't satisfy the argument.
i don't understand your problem, but if is validation on inputs empty... using
http://parsleyjs.org/
Hi all im new to jscipt,,, well, programming in general to be honest, but learning slowly for personal use.
I seek guidence on how i could place all the textboxes(inputs) in my index file into a list container, loop through them to check if they are empty or not before clicking the calculate button. If they are empty then inform the user of which one is empty.
Also, is there a way of preventing users from entering text into the textboxes and numbers only.
Background: im creating a form that requires all fields to be populate with numbers(in hours), a graph will then be generated from those values.
ive placed the file in skydrive for folks to download with the link below.
Index file
I did try the following but this alerts me regardless of weather the texboxes are populate or not.
function checkInputsGenerateGraph()
{
if( $('#hutz-hoursInput').val() == ""||$('#hutz-weeksPerYearInput').val() == ""||$('#hutz-jobsPerWeekInput').val() == ""||$('#hutz-hourlyMachineRateInput').val() == ""||$('#hutz-maintneneceDowntimeInput').val() == ""||$('#hutz-scrapRateInput').val() == ""||$('#hutz-toolsPerJobInput').val() == ""||$('#hutz-timeToLoadToolInput').val() == ""||$('#hutz-timeToSetPartsInput').val() == "")
{
alert('One them is empty!!');
}
else
{
$("#hutz-graph").slideDown();
$("#hutz-lblImproveMyProcess").slideUp();
$("#hutz-hoursInput").slideUp();
$("#hutz-weeksPerYearInput").slideUp();
$("#hutz-jobsPerWeekInput").slideUp();
$("#hutz-ourlyMachineRateInput").slideUp();
$("#hutz-ntneneceDowntimeInput").slideUp();
$("#hutz-scrapRateInput").slideUp();
$("#hutz-toolsPerJobInput").slideUp();
$("#hutz-timeToLoadToolInput").slideUp();
$("#hutz-timeToSetPartsInput").slideUp();
$("#hutz-lblMachineDetails").slideUp();
$("#hutz-lblPartSetting").slideUp();
$("#hutzcurrencyPreferenceInput").slideUp();
createChart();
}
}
First off, give all the required elements a common class, for examples sake we'll call this required:
<input type="text" class="required" id="hutz-hoursInput" />
Then, when your checkInputsGenerateGraph() function is called, you can loop over the required elements and check them:
$('.required').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
}
});
You could also do something like the following to remove all non-digits from your inputs:
$('.required').change(function() {
this.value = this.value.replace(/[^\d]+/, '');
});
See it in action
Hope that points you in the right direction!
edit
Here's a complete example:-
function checkInputsGenerateGraph() {
var isValid = true;
$('.example').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
isValid = false;
}
});
if (isValid) {
alert('do calculations!');
}
}
So, loop over all of the elements first, and make sure they are all populated. If not, set isValid to false so that once the loop completes, the calculations are not performed.
I'm adding a mechanism in my website that's supposed to warn users whenever they are about to close a page they were working in. I'm binding a function dropDraftConfirmation to the window.onbeforeunload event, like this:
window.onbeforeunload = dropDraftConfirmation;
function dropDraftConfirmation()
{
if (<there is an input or textarea element not empty on the page>) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
But this is called every time I close a page. So my question is, how to detect if there is an input or textarea element in the page that is not empty? I'm using jQuery by the way.
I think this should do the trick.
window.onbeforeunload = dropDraftConfirmation;
function dropDraftConfirmation()
{
if ($("input:empty,textarea:empty").length == 0) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
rewrite your function like the one below to check any unsaved changes before unload
window.onbeforeunload = checkUnSaved;
function checkUnSaved(){
if($("#textarea").val() === ""){
dropDraftConfirmation();
}else
return;
}
function dropDraftConfirmation()
{
if (<there is an input or textarea element not empty on the page>) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
you could also do something like:
var errors = 0;
$("input, textarea").map(function(){
var val = $.trim( $(this).val() );
if( val.length < 1 ) {
errors++;
}
});
if( errors > 0 ) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
Your condition will look like this:
if ($("input[value!='']").length > 0 || $('textarea:not(:empty)').length > 0 ){