Catching the Submit works in Firefox but not in Chrome - javascript

I'm using this to catch the submit button press, validate everything, and then either stop it or let it go through, this works in Firefox, but not in Chrome, Chrome lets the form go through empty. I also have a reset function that works in Chrome but in firefox. I'm brand new to js and jquery and could use some help figuring this out since stuff working in one browswer and not in the other confuses the heck out of me :)
(Sorry about having my test alert in there still)
Here's the code:
$("form").submit(function(e){
if (e.originalEvent.explicitOriginalTarget.id=="btn") {
if (bizNameValid==false || bizWebValid==false || bizStreetValid==false || bizCityValid==false || bizStateValid==false || bizZipValid==false || bizPhoneValid==false || firstValid==false || lastValid==false || custStreetValid==false || custCityValid==false || custStateValid==false || custZipValid==false || custPhoneValid==false || custEmailValid==false || monValid==false || yearValid==false || typeValid==false || ccValid==false) {
alert("bizNameValid:" + bizNameValid+"\n bizWebValid:"+bizWebValid+"\n bizStreetValid"+bizStreetValid +"\n bizCityValid: "+bizCityValid+ "\n bizStateValid:"+bizStateValid+"\n bizZipValid: "+bizZipValid+"\n bizPhoneValid:"+bizPhoneValid+"\n firstValid:"+firstValid+"\n lastValid:"+lastValid+"\n custStreetValid:"+custStreetValid+"\ncustCityValid"+custCityValid+"\n custStateValid"+custStateValid+"\n custZipValid:"+custZipValid+"\n custPhoneValid"+custPhoneValid+"\n custEmailValid:"+custEmailValid+"\n monValid:"+monValid+"\n yearValid:"+yearValid +"\n ccValid:"+ccValid+" \nccType:"+typeValid);
e.preventDefault();
return false;
}
else if(total==0) {
$("#svc_desc").append("</br><label id='first_error' style='font-size:16pt;'>You must select a service to continue</label>");
alert("You must select a service to continue");
e.preventDefault();
return false;
}
else {
return true;
}
}
});

try
$("form").submit(function(e){
var target = e.originalEvent || e.originalTarget;
if($(target.srcElement || target.originalTarget).attr('id')=="btn"){
}
//rest of your code
});
ref: https://stackoverflow.com/a/8067990/1679410

Related

Javascript Alternative for Detecting Select Value Which Doesn't Use Xpath in IE?

I had a working solution to grab the value of a select using Xpath. Found out IE doesn't support Xpath and it throws an "XpathResult is undefined" error!!! I'm using a TMS (DTM) so I have to inject my code into the web app. I can't touch the web app code. In researching this, I read that a library (https://github.com/google/wicked-good-xpath) could fix this but I don't have that option. If you go to https://apply.essexcredit.com/ on the first page, you'll see only one select "What type of loan are you interested in? ". I need to set an event listener on this element and grab the value being selected (RV or Boat etc). Is there any other approach I can use to attach an event listener to this and grab the value? Here is the current code I had that works when Xpath is supported:
function _dtmSetProductSel() {
window.addEventListener("click", function() {
var prodSel = document.evaluate("//form/div/div/div/div/div/div/div/div/div/div/div/div/div/div/div[#class='option-selected']", document, null, XPathResult.ANY_TYPE, null).iterateNext();
if (prodSel) {
var currProd = prodSel.getAttribute("title");
if (currProd == "RV" || currProd == "Boat" || currProd == "Auto" || currProd == "Auto-IBG" || currProd == "Investment Line of Credit") {
sessionStorage.setItem("_dtmSelProd", currProd);
}
} else {
setTimeout(_dtmSetProductSel, 1000);
}
});
};
Check if you can use document.querySelector as shown below.
var prodSelCSS = document.querySelector("form div.option-selected")
function _dtmSetProductSel() {
window.addEventListener("click", function() {
var prodSel = document.getElementsByClassName("option-selected");
var tryAgain = true;
for(var i=0;i<prodSel.length;i++) {
var currProd = prodSel[i].getAttribute("title");
if(currProd && (currProd == "RV" || currProd == "Boat" || currProd == "Auto" || currProd == "Auto-IBG" || currProd == "Investment Line of Credit")) {
sessionStorage.setItem("_dtmSelProd", currProd);
tryAgain = false;
break;
}
}
if(tryAgain) {
setTimeout(_dtmSetProductSel, 1000);
}
});
};

Shift tab not retaining the element focus

Javascript version code -- Link
if (el.value.length > 1) {
el.value = el.value[el.value.length - 1];
}
try {
if (el.value == null || el.value == "") {
this.foucusOnInput(el.previousElementSibling);
} else {
this.foucusOnInput(el.nextElementSibling);
}
} catch (e) {
console.log(e);
}
AngularJS version code - Link
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "") {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
Not able to implement the javascript version of
Tab & Shift+Tab
functionality in AngularJS. Let me know what am missing here!
Requirement - Once you enter the value to the input text the next input text element should be focused; On Shift-Tab previous input text element should be focused.
The keyup event gets triggered for every key up including tab and shift. This is the difference between your javascript solution angularjs solution.
I'm not sure if there is an equivalent to oninput in angularjs. 'keyup', 'keydown', 'input' all work differently. There is ng-change in angularjs but it requires ng-model on the input element and I don't think $event works with ng-change.
Anyway, there is a working solution. Try this:
$scope.readKey = function(ele) {
console.log(ele);
if(ele.shiftKey) return;
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "" ) {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
};
This code, as listened on keyup instead of input, will not allow to go to next input field if current input field is empty. In your javascript example, the code in input handler never gets executed and so you can move to next input field if current one is empty.
If you want to achieve the same thing in angularjs solution as well, then try changing the condition to this:
if(ele.shiftKey || ele.keyCode === 9) return;
This prevents the code from getting executed if its shift key or tab key. 9 is the keycode for TAB.
Working solution -- Link
if(ele.key != "Tab" && ele.key != "Shift" ){
if (ele.currentTarget.value.length >= 1) {
ele.currentTarget.value = ele.currentTarget.value[ele.currentTarget.value.length - 1];
}
try {
if (ele.currentTarget.value === null || ele.currentTarget.value === "") {
foucusOnInput(ele.currentTarget.previousElementSibling);
} else {
foucusOnInput(ele.currentTarget.nextElementSibling);
}
} catch (e) {
console.log(e);
}
}

jQuery: selectionStart returns undefined

Situation
browser
Google Chtome 69
html
<textarea id="message" name="message">
// input some messsage
</textarea>
js(jQuery)
$(function () {
$("#message").on("keydown keyup keypress change", function () {
//this part runs correctly
})
$('#message').on('keydown', function (e) {
if ((e.wich && e.wich === 13) || (e.keyCode && e.keyCode === 13)) {
var $textarea = $(this);
var sentence = $textarea.val();
var position = $textarea.selectionStart;
var length = sentence.length;
var before = sentence.substr(0, position);
var after = sentence.substr(position, length);
sentence = before + "\n" + after;
}
});
});
When I input something in the #message textarea and push Enter key in the area, nothing would happen. According to Chrome developer tool, selectionStart method seems to return Undefined.
Needs
Enter key has been made disabled in this form page in order to avoid submitting the data mitakenly.
js
function fnCancelEnter()
{
if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
if (window.event.keyCode == 13)
{
return false;
}
}
return true;
}
However, in this textarea, I want to enable user to add a break line by pressing Enter key.
I'm sorry but I don't have much knowledge about jQuery and javascript. Please tell me how to do.
Please replace $textarea.selectionStart by $textarea.get(0).selectionStart. Then try again.

window.confirm not working in FireFox

Background:
The goal is to keep a user from going back a page using the backspace. I've created code to disable the the key, except for a few input fields. But if they do, in fact, want to go back, I'd like for the confirm dialog to ask them if they REALLY want to go back or not.
Problem:
The following code works in IE and Chrome, but not FF. The confirm pops up but it still goes 'back' a page. This doesn't happen in IE/Chrome as the confirm dialog waits for user input.
Code:
<script type="text/javascript">
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' &&
(
d.type.toUpperCase() === 'TEXT' ||
d.type.toUpperCase() === 'PASSWORD' ||
d.type.toUpperCase() === 'FILE' ||
d.type.toUpperCase() === 'SEARCH' ||
d.type.toUpperCase() === 'EMAIL' ||
d.type.toUpperCase() === 'NUMBER' ||
d.type.toUpperCase() === 'DATE' )
) ||
d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
}
else {
var r = window.confirm("Leaving the page can cause data to be lost. Are you sure?");
if (!r) {
doPrevent = true;
}
}
}
if (doPrevent) {
event.preventDefault();
//event.stopPropagation();
}
});
</script>
This fixed it and worked in each browser (Safari too):
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Leaving the page can cause data to be lost. Are you sure?";
e.returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
});

Prevent backspace button from navigating back in Sharepoint 2010 and IE

As a user requirement I have to disable the backspace button from navigating back in the history. I made the following piece of code
//Bind back nutton to prevent escaping the page with backspace
$j(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8)
{
if(event.target == document.body){
if(event.preventDefault()){ event.preventDefault(); }
event.stopEvent();
event.returnValue = false;
}
}
});
This is working perfectly in all the browsers except IE7 and IE8. I cannot bind the input types as exceptions because the content editor in SharePoint allows modification of the text in the elements div, paragraph, etc. The solution is not working in IE8 because the event.target returns the element that is on mouseover when there are no controls that have the focus.
I'd recommend a tweak to Machinegon's fix. The code should also prevent default behavior if the user clicks the backspace key in a readonly input control of type text.
if ((nodeName === "input" && event.target.type === "text") ||
nodeName === "textarea") {
doPrevent = event.target.readOnly;
}
Solved by myself, case closed.
EDIT: Working in 2012 with SharePoint 2010 and jquery 1.x, not sure about today.
//Bind back button to prevent escaping the page with backspace
$(document).unbind('keydown').bind('keydown', function (event) {
if (event.keyCode === 8)
{
var doPrevent = true;
//Chrome, FF, Safari
if(event.target == document.body){
doPrevent = true;
}
//IE
else
{
var nodeName = event.target.nodeName.toLowerCase();
if((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
{
doPrevent = false;
}
var SPEditTabInstance = $(document).find("li[id='Ribbon.EditingTools']");
if(SPEditTabInstance != "undefined" && SPEditTabInstance != null && $(SPEditTabInstance).children().length > 0){
doPrevent = false;
}
}
if(doPrevent)
{
//Chrome, FF, Safari
if(event.preventDefault()){ event.preventDefault(); }
//IE
else
{
event.returnValue = false;
}
}
}
});
Try pushing back to the person(s) creating the requirements that breaking a ubiquitous and important function of all browsers is not a particularly great idea from a usability perspective. The costs of doing so (including time spent explaining to users why thier browser "don't work no more") will greatly outweight the costs of having the back button be a bit annoying occaisionally.
Machinegon's answer works well, I'm just adding to it to handle one more case.
If the input boxes are readonly or disabled, and if you hit backspace on them, then it goes to previous page. So the following code will work to handle that scenario:
//Bind back button to prevent escaping the page with backspace
$(document).unbind('keydown').bind('keydown', function(event) {
if (event.keyCode === 8) {
var doPrevent = true;
//Chrome, FF, Safari
if (event.target == document.body) {
doPrevent = true;
}
//IE
else {
var nodeName = event.target.nodeName.toLowerCase();
if (((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
&& !event.target.disabled && !event.target.readOnly) {
doPrevent = false;
}
}
if (doPrevent) {
//Chrome, FF, Safari
if (event.preventDefault()) {
event.preventDefault();
}
//IE
else {
event.returnValue = false;
}
}
}
});

Categories

Resources