How to get validation of input field and button to play nice? - javascript

I have the following input field:
<input id="filename" type="text" name="filename" onchange="checkfilename()"></input>
A button:
<button onclick="openSave()">Save</button>
I have the following functions:
function openSave()
{
var filename = document.getElementById('filename').value;
if(!filename || filename.trim()==="")
{
return;
}
else
{
//Do some work to save file
mySaveFunction();
}
}
function checkfilename()
{
var input = document.getElementById('filename');
input.value = input.value.trim();
var vals = input.value;
if(!vals || vals==="")
{
clearerrormessage();
var statusMessageDiv = document.getElementById("errormessage");
var errorTextNode = document.createTextNode("You forgot to specify a filename.");
statusMessageDiv.appendChild(errorTextNode);
}
else
{
clearerrormessage();
}
}
When I input nothing in the input field, and leave, or click on the button, it works as expected and the error message is displayed and mySaveFunction() is not called.
Immediately after this, if I go back to the text field, enter some text, and then IMMEDIATELY click on the button, the error message is cleared, but mySaveFunction() is not called! I have to click on the button one more time to get mySaveFunction() to execute! Why does this happen and how can I fix it? The bug repros every time.

It works for me look at this FIDDLE and look at the javascript console
<input id="filename" type="text" name="filename" onchange="checkfilename()"></input>
<button onclick="openSave()">Save</button>
<div id="errormessage"></div>
function openSave(){
var filename = document.getElementById('filename').value;
if(!filename || filename.trim()==="") {
return;
}else{
//Do some work to save file
console.log("save");
}
}
function checkfilename(){
var input = document.getElementById('filename');
input.value = input.value.trim();
var vals = input.value;
if(!vals || vals===""){
console.log("clear message")
document.getElementById("errormessage").innerHTML = "";
var statusMessageDiv = document.getElementById("errormessage");
var errorTextNode = document.createTextNode("You forgot to specify a filename.");
statusMessageDiv.appendChild(errorTextNode);
}else{
document.getElementById("errormessage").innerHTML = "";
}
}

I figured out the problem:
As I was updating the dom while I was clicking on the button, the button moves away from the pointer just enough so that the "click" didn't complete.
The second time I was clicking on the button, the dom wasn't changing, so the click could complete.
I fixed it, by ensuring my button was not moving when I clicked on it.

Related

Required field in form doesn´t change to red after erasing input content

Basic form validation
In this question, you’re going to make sure a text box isn’t empty. Complete the following steps:
Create a text input box.
Write a function that turns the text box’s border red if the box is empty.
(It’s empty if the value equals "").
The border should go back to normal if the value is not empty.
When the user releases a key (onkeyup), run the function you just created.
please correct my code where I'm coding wrong?
let form = document.getElementById("form_Text").value;
document.getElementById("form_Text").onfocus = function() {
if (form == "") {
document.getElementById("form_Text").style.backgroundColor = "red";
document.getElementById("showText").innerHTML = "Form is empty";
} else {}
document.getElementById("form_Text").onkeyup = function() {
document.getElementById("form_Text").style.backgroundColor = "white";
document.getElementById("showText").innerHTML =
"Form is not Empty, No red Background";
};
};
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
You are trying to get the input value with let form = document.getElementById("form_Text").value; right after the js is loaded. Therefore it will always be empty. You need to call it inside the event listener.
document.getElementById("form_Text").onfocus = function() {
let form = document.getElementById("form_Text").value;
...
}
But instead of writing two separate event listeners, you can use input event instead of focus and keyup
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.addEventListener('input', function(evt) {
const inputValue = evt.target.value;
if (inputValue == '') {
formText.style.backgroundColor = "red";
showText.innerHTML = "Form is empty";
} else {
formText.style.backgroundColor = "white";
showText.innerHTML = "Form is not Empty, No red Background";
}
})
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
UPDATE
You can find the other way of binding below. Instead of using two separate events (keyup and focus), you can use oninput event listener.
Here's a SO thread comparing keyup and input events: https://stackoverflow.com/a/38502715/1331040
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");
formText.oninput = function(evt) {
const inputValue = evt.target.value;
if (inputValue == '') {
formText.style.backgroundColor = "red";
showText.innerHTML = "Form is empty";
} else {
formText.style.backgroundColor = "white";
showText.innerHTML = "Form is not Empty, No red Background";
}
}
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>

How to implement Try Catch Finally Statement with form input - Javascript

I'm trying to use this to create a message that states "Please enter a number" when you hit submit on a form and there's no number in the input for "If you would like to state a specific amount type it in the box below". It's doing absolutely nothing, so I don't know what's going on. I'm still in school and this is my first class with JavaScript so I would appreciate any help you can give.
Here is the JavaScript portion:
```
// test page form exception code - Chapter 4
function verifyFormCompleteness() {
var specificAmountBox = document.getElementById("specificamount");
var completeEntry = true;
var messageElement = document.getElementById("message");
var messageHeadElement = document.getElementById("messageHead");
var validity = true;
var messageText = "";
try {
if (specificAmountBox.value == "" || specificAmountBox.value == null){
window.alert = "Please enter a number in the specific amount box";
}
}
catch(message) {
validity = false;
messageText = message;
specificAmountBox.value = ""; // removes bad entry from input box
}
finally {
completeEntry
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = "";
alert("This is happening in the finally block");
}
if (validity = true) {
return submit;
}
}
```
Here is the HTML portion:
```If you would like to state a specific amount type it in the box below:<br>
<input type="number" id="specificamount" name="specificamount">
<h1 id="messageHead"></h1>
<p id="message"></p>
<br>
<br>
```

Having trouble displaying an array value within console.log event using .push function in Jquery

The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">

Why doesn't my reset() function remove my red error lines?

function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.

Javascript form validation

I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}

Categories