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.
Related
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>
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>
```
In a js code, i created 3 buttons --- button 1...button 2...button 3
and 3 input fields --- input field 1...input field 2...input field 3
From the beginning of the script all buttons are disabled
button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values
button 2 will only be activated when input field 1 and 3 have numerated values
button 3 will only be activated when input field 2 and 3 have numerated values.
My problem is when i entered a numerated value for input field 1 and 2, button 1 will not activate (in-clickable) even though it was suppose to
And lets say i redid my code and got my whole code backwards so, at the beginning of my script all the buttons were not disabled (you could click on them). Then i made a simple conditional statement like so
input field 1 = if1
input field 2 - if2
if (if1.length = 0 || isNaN(if1) && if2.length = 0 || isNaN(if2) ) {
document.getElementById("button 1").disable = true;
}
Button 1 will not immediately disable until the user clicks on the button. And if the user were to re-enter the appropriate value type in input field 1, button 1 will not activate (be-clickable) because apparently its permanently disabled.
So down to summary, I'm asking if there is a way to make JavaScript be instantly interactive. Such as a web browser search bar. The moment you type something, you immediately get a list of possible questions and when you don't type anything in them the list disappears and the browser regains its original state.
Any Advice/help shall be greatly appreciated
Due to Life and its problems my code some how got deleted. Thus the lack of code and bunch of words. Sorry.
Generic solution (using attributes)
You can check the answer below which is using oninput event and the attributes to handle your situation effectively.
I have added a data-target attribute to link the elements together to fit with your requirement.
For an instance, to match the rule button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values, data-target of button1 is id of textbox 1 & 2.
Working snippet:
function checkInput() {
var dataTarget = 'data-target';
var elm = event.target;
var targetAttrs = getAttr(elm, dataTarget);
if(targetAttrs) {
var targetButtons = targetAttrs.split(',');
for(var i = 0; i < targetButtons.length; i++) {
var button = document.getElementById(targetButtons[i]);
targetAttrs = getAttr(button, dataTarget);
if(targetAttrs) {
var targetTextBoxes = targetAttrs.split(',');
var valid = true;
for(var j = 0; j < targetTextBoxes.length; j++) {
var textBox = document.getElementById(targetTextBoxes[j]);
if(textBox) {
valid = isValidNumber(textBox.value);
}
if(!valid) {
break;
}
}
button.disabled = !valid;
}
}
}
}
function isValidNumber(val) {
return (val && val.length > 0 && !isNaN(val));
}
function getAttr(elm, name){
var val;
if(elm) {
var attrs = elm.attributes;
for(var i = 0; i < attrs.length; i++) {
if(attrs[i].name === name) {
val = attrs[i].value;
break;
}
}
}
return val;
}
<div>
<input type="text" id="textBox1" oninput="checkInput()" data-target="button1,button2" />
</div>
<br/>
<div>
<input type="text" id="textBox2" oninput="checkInput()" data-target="button1,button3" />
</div>
<br/>
<div>
<input type="text" id="textBox3" oninput="checkInput()" data-target="button2,button3" />
</div>
<br/>
<input type="button" id="button1" value="Submit" data-target="textBox1,textBox2" disabled />
<input type="button" id="button2" value="Submit" data-target="textBox1,textBox3" disabled />
<input type="button" id="button3" value="Submit" data-target="textBox2,textBox3" disabled />
Note: With this code, when you add more elements, you don't need to change/add any Javascript code. Just add the elements and attributes
var field1 = document.getElementById('if1');
var field2 = document.getElementById('if2');
var field3 = document.getElementById('if3');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
field1.addEventListener('input', function(){
if(this.value!= '' && field2.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button2.disabled = false;
else
button2.disabled = true;
});
field2.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
field3.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button2.disabled = false;
else
button2.disabled = true;
if(this.value!= '' && field2.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
<input type="text" id="if1">
<input type="text" id="if2">
<input type="text" id="if3">
<br>
<button type="button" id="button1" disabled="true">Button1</button>
<button type="button" id="button2" disabled="true">Button2</button>
<button type="button" id="button3" disabled="true">Button3</button>
Here is how you do it
Disabling a html button
document.getElementById("Button").disabled = true;
Enabling a html button
document.getElementById("Button").disabled = false;
Demo Here
Edited
Try this...
You apply addEventListener to that DOM object:
document.getElementById("IDTeam").addEventListener("change", function() {//call function here});
For IE
document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} );
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.
i made a sign up form in which if you keep name or last name input it shows a error written byside of the input i did the same in radio input.every thing is working but,the problem is
when the submit button is clicked the errors blinks and go away. the button type is submit
i am writting the code down
function SignUp() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").text();
var date = $("#dd option:selected").text();
var month = $("#mm option:selected").text();
var yy = $("#yy option:selected").text();
var sex = $("input:radio[name=sex]:checked").val();
if ($.trim($("#firstname").val()) == "") {
document.getElementById("firstnameerror").innerHTML = "Please write firstname";
if ($.trim($("#lastname").val()) == "") {
document.getElementById("lastnameerror").innerHTML = "Please write lastname";
if (!$("input[name='sex']:checked").val()){
document.getElementById("gendererror").innerHTML = "Please select your gender";
}
}
}
}
You problem is that you don't prevent default behavior of the form which is submiting. Try this (simplified code):
function SignUp(e) {
var firstname = $("#firstname").val();
var lastname = $("#lastname").text();
if ($.trim($("#firstname").val()) == "") {
$("#firstnameerror").text("Please write firstname");
e.preventDefault(); // <!-- prevent form submit in case of errors
}
else {
$("#firstnameerror").text('');
}
if ($.trim($("#lastname").val()) == "") {
$("#lastnameerror").text("Please write lastname");
e.preventDefault();
}
else {
$("#lastnameerror").text("");
}
}
$('#form').submit(SignUp)
http://jsfiddle.net/fh6Ar/
Also don't bind click events to submit buttons. Form has special event for this submit event.
When you call SignUp() function as your submit button is clicked you must return false for the form to not be submitted.
With jquery you could easily do:
$('#submitButtonId').click(function(){
SignUp();
return false;
})
If all goes right after the javascript validation you could do:
$(#myFormId).submit();
Or just plain:
<input type="submit" name="send" value="SEND" onclick="SignUp(); return false;" />