Chrome not validating required fields - html

I am using the required to show form fields that are required. I heard this is a bug in chrome but wanted to know if there was a work around. My code is posted below.
echo "<br><br><input class=button id=submitbutton type=submit value=\"".pcrtlang("Submit Service Request")."\" onclick=\"this.disabled=true;this.value='".pcrtlang("Sending Request")."...'; this.form.submit();\">";
I believe it will work if you remove the onlick function but then you have an issue if a user double clicks the submit button it will submit twice.
I use a javascript to disable the submit button to prevent double submissions, and then javascript to make the form submit.

The problem is that onclick is being called everytime (even when its not going to submit by the browser).
You can fix by changing the onclick to onsubmit (JSFiddle)
<input class="button" id="submitbutton" type="submit" value="Submit" onsubmit="this.disabled=true;this.value='Sending Request';">

I would be tempted to bind to the submit event of the containing form, and use the concept from _.debounce to limit the repetition of submissions:
jQuery:
// prevent the user from submitting the form twice within a second
var DELAY = 1000;
var lastSubmit = null;
$("#form").submit(function(e) {
if (lastSubmit === null || Date.now() - lastSubmit > DELAY)
return true;
// two ways to prevent the default action
e.preventDefault();
return false;
});
Or staight JavaScript:
// prevent the user from submitting the form twice within a second
var DELAY = 1000;
var lastSubmit = null;
document.getElementById('form').addEventListener('submit', function(e) {
if (lastSubmit === null || Date.now() - lastSubmit > DELAY)
return true;
// two ways to prevent the default action
e.preventDefault();
return false;
});
You can tune DELAY to meet your requirements, or handle the form submission failing to reset a disabled state.
If a requirement is to use attributes for the hooks, then:
echo "<form onsubmit=\"var stop = lastSubmit && Date.now() - lastSubmit <= 1000;stop && e.preventDefault();return !stop;\">";

Related

How to send a single request through p:commandButton inside p:dialog? [duplicate]

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});

How to set Text Input field to focus when user start typing on page

I am trying to autofocus on a text input when a user starts typing on a webpage.
i have tried this, but this is only for page load
<input type="text" name="text_input" autofocus>
How can i set it so it will focus when the user starts typing on the page
Use jQuery.
$('body').on('keydown', function() {
var input = $('input[name="text_input"]');
if(!input.is(':focus')) {
input.focus();
}
});
Edit
If you only want this to happen once, you can set some sort of flag, like this:
var flag = false;
$('body').on('keydown', function() {
var input = $('input[name="text_input"]'),
if(!input.is(':focus') && flag === false) {
input.focus();
flag = true;
}
});
Building on Josh Beam's answer, if you want to also tack whatever key the user pressed to the end of the input you could do something like the code below. It also only triggers if the pressed key is a number or letter, so it won't take focus if the user presses an arrow key, page up, etc.
$('body').on('keydown', function(keyPress) {
var input = $('input[name="text_input"]');
if(!input.is(':focus') && keyPress.key.match(/^[0-9a-zA-Z]+$/)) {
input.focus();
input.val(input.val()+keyPress.key);
}
});

<button> with form attribute does not work on IE

my question is why something like that:
<form id="aaa" action"xxx">
</form>
<button form="aaa" type="submit">Button</button>
does work in Firefox,Opera,Chrome and does NOT work in IE 11 and mobile devices with Windows system? Example above does nothing, button seems not to belongs to form.
thank You in advance.
As already mentioned, the button should ideally be within the form. However, one way to proceed, with the button outside of the form, is to have the button trigger the form submit via JavaScript.
A quick and dirty jQuery example to illustrate:
$('button[form="aaa"]').click(function()
{
$('#aaa').submit();
});
You can replace this with an in-line onclick="" attribute on the button element if preferred.
This question is old but I thought I'd share how I got this working with a React app. I needed the onSubmit callbacks to be run when a form was submitted, and that wasn't happening when calling submit directly on the form. Here was my quick solution to the problem. It only accounts for buttons outside of the form:
/**
* Is the [form] attribute supported?
*/
const isSupported = (() => {
const TEST_FORM_NAME = 'form-attribute-polyfill-test';
const testForm = document.createElement('form');
testForm.setAttribute('id', TEST_FORM_NAME);
testForm.setAttribute('type', 'hidden');
const testInput = document.createElement('input');
testInput.setAttribute('type', 'hidden');
testInput.setAttribute('form', TEST_FORM_NAME);
testForm.appendChild(testInput);
document.body.appendChild(testInput);
document.body.appendChild(testForm);
const sampleElementFound = testForm.elements.length === 1;
document.body.removeChild(testInput);
document.body.removeChild(testForm);
return sampleElementFound;
})();
/**
* If it's not, listen for clicks on buttons with a form attribute.
* In order to submit the form and have all the callbacks run, we insert
* a button, click it and then remove it to simulate a submission from
* inside the form.
*/
if (!isSupported) {
window.addEventListener('click', e => {
const {target} = e;
const formId = target.getAttribute('form');
if (target.nodeName.toLowerCase() === 'button' && formId) {
e.preventDefault();
const form = document.getElementById(formId);
const button = document.createElement('button');
form.appendChild(button);
button.click();
form.removeChild(button);
}
});
}
A submit button is generally used to submit data from a form to the server (JavaScript not taken into account). As the button in your example is not part of the form, it has no associated data to submit.
EDIT: After noticing the form attribute, the user JayC's answer is correct. Internet Explorer does not support that attribute on buttons, whereas the other browsers do. Its a part of the HTML 5 standards which has not been implemented yet.

Html5 form element "required" on iPad/iPhone doesn't work

iPad safari is supposed to be html5 compliant, but it seems that the required element doesn't work. Anyone know why, or have a decent workaround that doesn't require a ton of JavaScript?
My code
<input type=email class=input placeholder="Email" name="email" required>
It's not supported in iOS yet: when can I use: required.
This is a jQuery solution to the issue, it highlights the input fields that have failed in a pinky colour too.
$('form').submit(function(){
var required = $('[required="true"]'); // change to [required] if not using true option as part of the attribute as it is not really needed.
var error = false;
for(var i = 0; i <= (required.length - 1);i++)
{
if(required[i].value == '') // tests that each required value does not equal blank, you could put in more stringent checks here if you wish.
{
required[i].style.backgroundColor = 'rgb(255,155,155)';
error = true; // if any inputs fail validation then the error variable will be set to true;
}
}
if(error) // if error is true;
{
return false; // stop the form from being submitted.
}
});
Since iOS 10.3 this atrributes are supported. Also e-mail type require writing the # symbol and so on...
If you are already using jQuery, Modernizr, and yepnope, this is one way to deal with it. If you aren't then this will add a lot of extra javascript.
My solution
I guess you can do something before the submit action like this
<form name="myForm" action="valid.html" onsubmit="checkValid()" method="post">
... ...
</form>
after pressing submit button, checkValid() is evoked before it actually submits. a return value of truewill continue the submit action.
refer to this post for further explanation.:)
If you use PHP, you can add a validation like this
function validation(){
if(isset($_POST['submit'])){
$email = $_POST['email'];
if(empty($email)){
echo $error = "Your email cannot be empty";
} else {
return true; //or do something next here
}
}
You then add this function in php before your form.

Set an image button to fire when enter key is pressed

Obviously I know how to do this with DefaultButtons within an ASP.NET web form. However, the way our client side developer wrote the code, he has a submit button done via javascript:
So the javascript is rendering the HTML.
<img id="submitBMI" onclick="quizCalc(); return false;" class="btnHover" src="Submit.gif">
Is there anyway to make this a DefaultButton?
Thanks guys.
If you mean to have the quizCalc() method be called when, for example, the enter key is pressed in a textbox of that form, then you could just set the onsubmit handler of the form to call that method:
<form ... onsubmit="quizCalc(); return false;">
If you want a little more control on which input elements call the method then you could look at using onkeypress with a single handler onKeyPress(event), check out a similar question
Update
You could do what Jonathan says, but just remove the return false as that cancels the keypress from adding characters to the textbox.
document.onkeydown = function(e)
{
var keyCode = document.all ? event.keyCode : e.which;
if(keyCode == 13) quizCalc();
}
Assuming you aren't using a js library, this will work if enter is pressed anywhere on the page:
document.onkeydown = function KeyDown(e)
{
var keyCode = document.all ? event.keyCode : e.which;
if(keyCode == 13) {
quizCalc();
return false;
}
}