The code below displays two text input fields and either creates either an enabled or disabled button depending on whether. There is also a Javascript timer to enable the button when people complete the form.
With dynamic button creation and code on a loop to enable or disable the button when the form is populated with autocomplete the button does not enable until the web page is clicked on anywhere or the user enters a character into the form. This confuses people as the form is complete but the button is disabled.
It seems like the form is not actually completed, just that Chrome/Firefox show the fields as complete but do not actually do so until the user interacts with the page.
How do I get the button to enable when the form is completed automatically with autocomplete?
<input type='text' id='username' autofocus />
<input type='password' id='password' />
<script type="text/javascript">
if (document.getElementById('username').value != '' && document.getElementById('password').value != '') {
document.write('<input type="submit" value="Login" />');
} else {
document.write('<input type="submit" disabled="disabled" value="Login" />');
}
</script>
For reference this is the code run on a timer used to check is the form is complete.
window.onload = function () {
var check_interval = 250;
window.setInterval( function() {
if (document.getElementById('username').value != '' && document.getElementById('password').value != '') {
document.getElementById('button').removeAttribute('disabled');
} else {
document.getElementById('button').setAttribute('disabled', 'disabled');
}
}, check_interval);
};
Edit: onChange is not a good solution for this problem as autocomplete does not generate events across all browsers. There is some information in the answer to this question. onChange does not work well with our forms anyway, one form has a user set a password where the button enables only when the password is deemed strong enough by zxcvbn lib. Polling works well for that, onChange only seems to kick in once the user has moved to another field.
Using an interval timer to check the values of forms is definitely not the best approach. Instead I would suggest having that code in an event handler for the onChange event on the two form fields that does the same thing. The button will be enabled when there is text in both fields instantly.
Related
Ran into a small oddity here.
When I submit a form, I have a JS click event listener on the submit button - this is to remove the HTML values and add a thank you message (pretty simple stuff).
Oddly, however, it seems that the JS is acting before the PHP because all emails have blank values until I remove the JS that removes the HTML values.
The code is:
pretty simple HTML form (this has been cut down to show what the problem might be)
HTML:
<form method="post" action="contactForm.php" id="contact-form" target="hiddenForm">
<textarea class="form-control input-outline reqItem" rows="6" cols="50" name="message" form="contact-form" placeholder="Message" required></textarea>
<button type="submit" class="btn btn-outline rounded-0 d-block d-md-inline-block submit-button">Submit</button>
</form>
JS (has an event listener on the submit button for click):
if(document.querySelector('.submit-button')){
document.getElementById('contact-form').addEventListener('submit', function(e){
// Check that form is valid
if(document.querySelector('form').checkValidity()){
document.querySelectorAll('.checkbox').forEach(e => {
if(e.classList.contains('checked')){
e.classList.remove('checked')
}
})
// Change messagae to thank you
e.target.classList.add('submit-hide')
document.querySelector('.submit-thankyou').classList.add('submit-show')
// remove all field values <<<<< issue seems to be being caused here
document.querySelectorAll('.form-control').forEach(e => {
// this causes the form to lose all data
e.disabled = true;
})
}
})
}
The e.disabled = true;
Is going over each form input and making it disabled, I have also used e.value = "".
Both of these stop PHP action in the form of setting variables as the values of the inputs.
So the question is,
am I doing something wrong (maybe right.....?)
is there a way to allow the PHP to act first getting the values before removing them with the JS?
Feel free to ask any questions here.
Any insights are welcome.
The submit event as part of the browser's form submission algorithm, before the browser even looks at the form's fields, so any changes you make as part of that event will be submitted to the server and you'll have access to them from PHP.
In order to change the form without affecting the submission, you'll have to do that at some point after the browser's form submission finishes, but before the page navigates to the form's action:
document.getElementById('contact-form').addEventListener('submit', function(){
setTimeout(function() {
// Modify the form here.
}, 0);
});
Remember that setTimeout(func, msecs) means "run func whenever you have the chance, but no earlier than msec milliseconds". While the browser is running the form submission algorithm, no Javascript code (other than that for the synchronous events submit and formdata) can run, so the earliest chance for func to run will be after the form is submitted.
I have an html page published as a web app through Google app scripts. On the page is an input box (textbox) the user types a number to search for. If they click the 'search' button beside the box, it works fine. If they type the number and then press 'enter' on the keyboard, it throws a 400 error ('The requested URL was not found on this server. ').
input area code:
<input type="text" id="claimSearchBox" class="form-control" placeholder="Search" />
<input type="button" id="btnsearchClaims" class="btn-md btn-success" onclick="getOrders" value="Search for a Claim" />
javascript:
(this works for the button)
document.getElementById("btnsearchClaims").addEventListener("click", getOrders);
(this does not work for the input box)
document.getElementById("claimSearchBox").addEventListener("keyup", function(event) {
event.preventDefault();
console.log('event: ' + event.keyCode);
if (event.keyCode == 13) {
console.log('correct key');
getOrders();
}
});
I also tried this, which shows what keys are pressed, but as soon as I press enter, it goes to the 400 error.
$(document).ready(function(){
$("claimSearchBox").keyup(function(e){
console.log(e.keycode);
console.log("worked");
});
});
Any suggestions? Is there a way to disable the 'enter' if I can't redirect it to the getOrders()?
**Edited to add...if I don't have any programming for the input box and the user presses enter - it goes to the error (page is blank - error is shown in console).
***Found the problem: Turns out it was an issue of this input box being the only input box on the form. When the user hits enter, it automatically submits the form! I found the issue/solution here: Why does forms with single input field submit upon pressing enter key in input
This may help you get further with your code.
I see that you are invoking jQuery.
$(document).ready(function(){
Can you confirm that the page you are displaying is properly loading jQuery?
Your html should have something like this present.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If you use your debugger and successfully enter your readythen you have jQuery loaded.
With jQuery, you could simplify your event handling.
Replace
document.getElementById("btnsearchClaims").addEventListener("click", getOrders);
With
$("#btnsearchClaims").on("click", getOrders);
Replace
document.getElementById("claimSearchBox").addEventListener("keyup",
function(event) {
With
$("#claimSearchBox").on("keyup", function(event)...
I'm trying to use PureCSS forms in my web app and I can't figure out how to retain the nifty form validation while stopping the page reload.
I know I can stop the page reload using onsubmit="return false;"
Then I can use AJAX to post the form data using onClick="PostSettings();", where PostSettings() is my javascript function containing the AJAX request. I also have to include event.preventDefault(); at the top of that function to stop the reload.
Unfortunately these steps which stop the reload also stop the nice in-built PureCSS validation.
Is there a way to retain that without triggering the page reload or will I need to make my own validation in the javascript?
FYI, here's the html:
<button type="submit" class="pure-button pure-input-1-2 pure-button-primary"
id="save-simulation-button" onClick="PostSettings();"
onsubmit="return false;">
<i class="fa fa-save"></i> Submit Simulation Parameters
</button>
Use 'return false' instead of event.preventDefault() inside the 'PostSettings()' method.
Thanks for your replies Lucas and Vignesh -- they didn't quite solve the problem, but they got me thinking and I developed a solution:
In the html I had to add a return here: onClick="return PostSettings();"
Then in the javascript I return true or false depending on whether or not the form passes validation, which I have to check:
function PostSettings() {
//event.preventDefault(); <<- commented out per Vigneshs suggestion
var name = $("#simulation-name").val(); // jquery to get form values
var description = $("#description").val();
// Code to validate form: name and description cannot be blank
if (name === "" || description === "") {
console.log("name or description fields cannot be blank");
return true; // <<- returning true allows PureCSS validation to continue
}
// Code passed validation so post the data...
// POST code omitted for brevity
return false; // <<- returning false stops the page reload
}
So in summary, returning true allows the PureCSS form validation to take place as per normal (and there's no page reload because the form hasn't passed validation). And when the form passes validation I return false to stop the page reload -- this also stops any other default events of the PureCSS form, but that's okay because I manually checked if it validated in the javascript.
Hope this helps others who want to accomplish this in the future!
You only need a onsubmit="return MyValidFunction();" in the Form tag and nothing else in the "submit" button
When the form is not ok PureCSS make the validation with his message, When All is ok call your "MyValidFunction()" function
function MyFunction() {
/// your Ajax Code here
return false;
}
<form class="pure-form" onsubmit="return PostSettings();">
<input id="form_url" type="url" class="pure-input-1-3">
<button type="submit" class="pure-button pure-input-1-1">OK</button>
</form>
I had the same issue. Adding onsubmit="event.stopPropagation()" in the form tag prevents the refresh when the form is valid, and retains validation flags when it's invalid.
This is about a regular responsive website with a dictionary lookup feature. The page consists of an input text box and an adjoining submit button. Currently if you open the page in a mobile browser and tap on the text box, the soft keyboard fires up automatically which is desirable. What's not desirable though is that the keyboard stays up even after the user taps on the enter key on the soft keyboard. I know there's got to be some method to change that. Does this situation calls for a special Android/iOS-specific library or something? Can I just add something to the button's onclick() to make it happen? If so, what function can one use? Do note that the keyboard disappears fine when the on-page submit button is tapped...it's just the soft keyboard enter key that's not having an effect on itself even though it does successfully submits the form.
I have tried the following and failed:
function lookup_check(lookupterm){
close_kb();
$('#word').blur();
if(lookupterm != ""){ lookup_word(lookupterm); }
else{
var testing = $('#word');
testing.addClass('empty');
setTimeout(function(){ testing.removeClass('empty'); },500);
}
}
The HTML calling the above function goes:
<button class="btn btn-lg btn-primary lookup-submit" type="submit" id="lookup" onclick="lookup_check($('#word').val());" style="display: inline-block;">Lookup</button>
P.S.: Just so we're absolutely sure, this is a desktop website and not an app.
Update: The accepted answer on the thread proposed by #NovaLogic is already stated to not work consistently across all versions of Android. Besides, I am looking for some way to accomplish this on not just Android but also on iOS/Windows devices. So, no, this question is NOT a duplicate.
You could just use
$('form').on('submit', function() {
$('input').blur();
});
To lose focus on the button once submitted
I came here when looking to solve the same issue in my React app.
So providing an answer without jquery.
Hope this would be helpful for others that face similar issue.
The solution is to make the active input element blur when the user taps the "Go" button / icon in the soft / virtual keyboard.
This will make the virtual keyboard disappear.
Example
Suppose you have the following form:
<form onSubmit={this.handleSubmit}>
<input aria-label="Search site" autoCorrect="off" id="my-input-box"
placeholder="Search country..."
type="search"/>
<input type="submit" value="Submit">
</form>
The example onsubmit handler to make the virtual keyboard disappear:
handleSubmit = (event) => {
event.preventDefault(); // Prevent default action of submitting data to web server
document.activeElement.blur();
}
Alternatively, you could get the element by id and blur it.
handleSubmit = (event) => {
event.preventDefault(); // Prevent default action of submitting data to web server
const myInputBox = document.getElementById('my-input-box');
if (myInputBox) {
myInputBox.blur();
}
}
I have a function that is supposed to display a message in a P element if conditions are met. The function runs fine but the text that is sent to 'output1' appears briefly when you press the button and then disappears. I have tried putting the JS in the head and in the body but it doesn't seem to make a difference. Any ideas? Thanks.
HTML:
<p id="output1"><p>
Javascript:
<script>
function logicProcess() {
// alert('function launched');
if(document.getElementById('q1Y').checked || document.getElementById('q2Y').checked || document.getElementById('q3Y').checked) {
document.getElementById("output1").innerHTML = "Sorry, you don't qualify for our shared ownership properties";
}
else {
document.getElementById("output1").innerHTML = "You may qualify for our shared ownership scheme. Please complete the registration form.";
}
}
</script>
The reason the innerHTML is not staying visible is because there is some type of onclick method that is resetting the form. If that is true edit your onclick method like so:
onClick="function();return false;"
The change in here is the ;return false;
You haven't show us how you are calling that function, but the odds are that you are doing so in response to a form's submit button being pressed.
This will modify the DOM, and then submit the form, which will cause a new page to be loaded.
You need to cancel the default behaviour of the form to stop it being submitted.
function logicProcess(evt) {
// All your other code
evt.preventDefault();
}
document.getElementById('myForm').addEventListener('submit', logicProcess);
I think you are using input type submit, so the meaning of submit button is to submit the form and reload it, that's why your output is not holding your inner html.
change it to
<input type="button" />