Javascript onClick Globally - javascript

I have a web application with many forms that submit data to a MySQL Database.
On all pages i have include 'settings.php'; so whatever i put in there will be on every page (CSS Links, JS Code etc)
Whats the best JS Code i can put in my settings.php file to put an "onClick" event on every single button on all pages.
I want it to do this:
onClick="this.disabled=true; this.value='Please Wait…';"
So on all forms within the site, every button that is clicked will display the Please Wait... text until the form is submitted

Clearly most of the people answering this question have never heard of event delegation.
window.addEventListener("click",function(e) {
var t = e.srcElement || e.target;
if( !t.tagName) t = t.parentNode;
if( t.tagName == "INPUT" && t.type.toLowerCase() == "submit") {
t.disabled = true;
t.value = "Please wait...";
}
},false);

You really shouldn't be using onClick=... Instead, bind the actions via JS:
document.getElementById('element-id').onclick=function(){
alert('Hello World');
}

Something like this ought to do it:
(function() {
var buttons = document.getElementsByTagName('button');
for (var i=0,len=buttons.length; i<len; i++) {
buttons[i].addEventListener('click', function() {
this.disabled = true;
this.innerHTML = "Please Wait...";
});
}
})();
http://jsfiddle.net/ryanbrill/5WYN9/

// very simple with jQuery
$(document).on('click', 'button,input[type="button"],input[type="submit"]', function (e) {
var $this = $(this).prop('disabled', true);
if ($this.is('button')) {
$this.html('Please wait...');
} else {
$this.val('Please wait...');
}
});

Related

How to redirect to another page using javascript

I am trying to find a way to redirect to another page using javascript once the user presses the submit form. I know how to do it using HTML but I can not get it to work here. The form submits but then it won't take you anywhere. I have tried a couple of different things I found online but nothing seems to work.
Here is my code
"use strict";
// global variables
var profile = {};
var formValidity = true
// validate entered password
function validateEmail() {
var email1Input = document.getElementById("email");
var email2Input = document.getElementById("email_retype");
email1Input.value = email1Input.value.toLowerCase();
email2Input.value = email2Input.value.toLowerCase();
var errorDiv = document.getElementById("emailError");
try {
if (email1Input.value.localeCompare(email2Input.value) !== 0) {
throw "The e-mails do not match";
}
// remove any password error styling and message
email1Input.style.background = "";
email2Input.style.background = "";
errorDiv.style.display = "none";
errorDiv.innerHTML = "";
}
catch(msg) {
// display error message
errorDiv.style.display = "block";
errorDiv.innerHTML = msg;
// change input style
email1Input.style.background = "rgb(255,233,233)";
email2Input.style.background = "rgb(255,233,233)";
formValidity = false;
}
}
/* create event listeners */
function createEventListeners(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
}else if (form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
/* validate form */
function validateForm(evt) {
if(evt.preventDefault) {
evt.preventDefault(); // prevent form from submitting
}else {
evt.returnValue = false; // prevent form from submitting in IE8
}
formValidity = true; // reset value for revalidation
validateEmail();
if (formValidity === true) {
document.getElementsByTagName("form")[0].submit();
location.href = "about.php";
}
}
/* run setup functions when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
You are unable to submit the form and then redirect. because the submit will redirect to the page defined in the form's "action". I see that your javascript function is just validating the fields
Example:
<form action = "action_page.php" method = "get">
This should help some... your if statements, such as:
if(window.addEventListener){ ... } || if(document.addEventListener){ ... }
will not execute the way you are expecting in your current implementation. If you would like to set up your event handlers when the window loads, you'd be better of implementing something like:
window.onload = createEventListeners;
// or
window.onload = function() {
var form = document.getElementsByTagName("form")[0];
form.addEventListener("submit", validateForm, false);
}
Here is some documentation on window.onload
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
and submitting an HTML with examples using javascript event handlers
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Although, if you really need/want to manually redirect the user using js, one way you can achieve this through window.location:
https://developer.mozilla.org/en-US/docs/Web/API/Window/location
I normally wouldn't normally recommend redirecting users this way, but I don't know enough about your code entirely, and it's still something that is very good to understand.

Javascript Run function on all input fields on focus

I want to execute a function when any of the text field is focused.
Something like this, BUT purely in Javascript - NOT IN JQUERY
$("input").focus(function() {
alert("Hello World");
});
I am trying:
document.getElementById("text1").onfocus = alert(1);
But this only shows the alert after loading page, nothing else.
Thanks
Get elements by tag name & loop("Iterate") on them for attaching focus.
http://www.w3schools.com/jsref/met_doc_getelementsbytagname.asp
var x=document.getElementsByTagName("input");
EDIT : Put this at the end of page
<script>
var x=document.getElementsByTagName("input");
for(i=0;i<x.length;i++)
{
x[i].addEventListener('focus',function(){
alert("focus");
});
}
</script>
Yet another way with document.querySelectorAll for new browser
var inputs = document.querySelectorAll('input');
and then in loop for example use addEventListener
for(var i=0,len=inputs.length;i<len;i++){
inputs[i].addEventListener('focus',function(){
//handle event
})
}
If you like some aspects of jQuery, but do not want to include the entire library in your project, you can check out You Might Not Need jQuery. You can set the minimum version of IE that you support, in the settings at the top of the page.
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function(){
handler.call(el);
});
}
}
function addEventListeners(selector, type, handler) {
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++) {
addEventListener(elements[i], type, handler);
}
}
addEventListeners('input', 'focus', function(e) {
if (this.value !== this.placeholder) {
this.value = this.placeholder;
} else {
this.value = '';
}
});
input {
display: block;
}
<input type="text" placeholder="One" />
<input type="text" placeholder="Two" />
<input type="text" placeholder="Three" />
I know I am probably late to this, but I just wanted to add my 2 cents, as I see a lot of Stackoverflow answers like this still using JQuery and many people have moved on from JQuery, and might want another option
You could either use the focusin event or capture the focus in the Capturing phase from the top down, in either JQuery or JS, If It works in JS, it should work in the other, as I dont use JQ
let form = document.forms.myForm;
form.addEventListener('focus', (event) => {
console.log('Focused!');
console.log(event.target);
}, true);
//Work around focusin
form.addEventListener('focusin', (event) => {
console.log('Focused In!');
console.log(event.target);
});
This one supports input elements that are loaded asynchronously too.
document.addEventListener("focusin", inputBoxListener)
function inputBoxListener(event) {
if (event.target.tagName === "INPUT") {
console.log("focused on input")
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/focusin_event

How to disable window.onbeforeunload from <a> tag?

First I used window.onbeforeunload on my application. It's working on over page but when click on anchor link it should be disabled Click. Any ideas? Please share. My code is below it is not working:
var submitFormOkay = false;
window.onbeforeunload = function () {
if (!submitFormOkay) {
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
}
<a class="navbar-brand" href="http://www.google.com">Click</a>
You could attach a global click handler on document.body which, if the click passed through an a element, sets submitFormOkay to true (or you could use another variable to bypass the check, or just clear the handler by assigning null to window.onbeforeunload), e.g.:
$(document.body).on("click", "a", function() {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
});
Without jQuery (since I missed the jquery tag initially):
document.body.addEventListener("click", function(e) {
var element;
for (element = e.target; element != document.body; element = element.parentNode) {
if (element.tagName.toUpperCase() === "A") {
submitFormOkay = true; // Or set another flag you'll check,
// or clear onbeforeunload entirely
break;
}
}
}, false);
using jquery it can be follow:
var submitFormOkay = false;
$(window).on('beforeunload',function () {
if (!submitFormOkay) {`enter code here`
return "Don't delay your Success. Get FREE career counselling session. Fill in the details below";
} else {
submitFormOkay = '';
}
})
<a class="navbar-brand" href="http://www.google.com">Click</a>
$('a').on('click',function(e){
e.preventDefault();
$(window).off('beforeunload');
window.location = $(this).attr('href');
});

JS: How to detect whether cursor is in textfield

I want to use some letters ( keys ) as shortcut for some actions in javascript. I want to check whether the cursor is focused on any textfield, form input, etc. so that the shortcut action will be canceled when user is typing something in a form or textfield.
For example, i want an alert() to be executed when user presses 'A'. But if the user is typing some text in a textarea like 'A website' then he will be pressing 'A', this time alert() should not be executed.
$(document).keydown( function( e ) {
if( e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA" ) return;
if( e.target.isContentEditable ) return;
// Do stuff
}
window.onkeydown = function(e){
if ( e.target.nodeName == 'INPUT' ) return;
handle_shortcut();
};
jQuery
$(window).bind('keydown',function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
});
or pure js
window.onkeydown = function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
};
What you can do in addition to this is define an array of non-alert element types, so input, textarea etc and then check none of those elements are currently the target.
Demo: http://jsfiddle.net/7F3JH/
You can bind and unbind the shortcut events depending on which element currently has focus on your page.
JavaScript
window.onload = initWindow();
function initWindow () {
attachShortcutHandler();
var inputs = document.getElementsByTagName('input');
for (var i = 0, max = inputs.length; i < max; i++) {
inputs[i].onfocus = removeShortcutHandler;
intputs[i].onblur = attachShortcutHandler;
}
}
function removeShortcutHandler () {
window.onkeypress = null;
}
function attachShortcutHandler() {
window.onkeypress = function () {
//your code here
}
}
jQuery
$(function () {
initShortcutHandler();
$('input, [any other element you want]')
.on('focus', function () {
$('body').off('keypress');
})
.on('blur', function () {
initShortcutHandler();
});
});
function initShortcutHandler() {
$('body').on('keypress', function () {
//do your stuff
});
}
jQuery mouseover()
$('element').mouseover(function() {
alert('over');
});
you need to make a flag as global. and set it false when any textbox has focus.
var flag = true;
$('input:type="text").focus(function(txt) {
flag= false; });
if(flag) //shortcut keys works...
Better use the focusOut method defined in JQuery. As per my understanding you can do something like this
$("input").focusout(function() {
if($(this).val() == "A"{
alert("your message");
return false;
}else{
//do other processing here.
}
});
Hope this helps :)

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

Categories