Why this code is not generating any alert message - javascript

Here i have written some that is for validation on form in html and javascript
<!DOCTYPE html>
<html>
<body>
<form name="registration">
<input style="font-size:16px;" type="text" name="Name" placeholder="Full Name" onchange="checkName()" required />
</form>
<script>
function checkName()
{
var uname=document.registration.Name.value;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
alert('fg');
}
else
{
alert('Username must have alphabet characters only');
//uname.focus();
}
}
</script>
</body>
</html>
Please describe why it is not working?

The problem is that you're trying to get the value property TWICE. Like such:
var uname=document.registration.Name.value;
if(uname.value.match(letters))
Your uname variable already contains the value, so you don't need to get it again. Change your if statement to this...
if (uname.match(letters))
And it works just fine :)

Using onchange with input type = "text" is quite uncommon
onchange event usually occurs only after you leave (blur) the control.
onchange is mainly associated with change of select element.
For your case it is better to use keydown, keyup and keypress events as well.
HTML
<input style="font-size:16px;" type="text" name="Name" placeholder="Full Name" onkeyup="checkName()" required />
Jsfiddle

Related

Can't get my simple JavaScript Event Handler working

I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

OnInvalid html event triggering after Required modifier removed through JS

I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.

Multiple form validation with same function

I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})

Validating input text field using Javascript

I guess I'm doing a trivial error somewhere but will be grateful if someone can spot it.
I am trying to validate a postcode in a form field once it has been typed in. Similar code works fine in PHP but I've spent hours and the JS does not seem to be executing whatever I do.
Here is part of the form (all within body tags):
<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
...
<script type="text/javascript" src="common.js">
</script>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onchange="isValidPostcode(this.form)" required />
Here are versions of the javascript (stuffed with alerts just to print out something).
Version 1:
function isValidPostcode(form) {
alert("called");
var p = document.register.postcode.value;
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
Version 2 (is called without a parameter):
function isValidPostcode() {
alert("called");
var p = document.getElementById('postcode').value.replace(/\s/g,'');
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
I tried binding to other events but can't get a single alert out. Even exact reproduction of the examples is not working. Hope someone gives me an idea of what is wrong.
you should replace onchange with keyup and remove quotes from regex :)
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onkeyup="isValidPostcode(this.value)" required />
function isValidPostcode(value) {
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(value)) console.log("OK");
else console.log("This does not look a valid UK postcode...");
}
You should use the keyup event to do that and add the event using JS, not inline it.
postcodeRegEx is a regex, not a string, you need to remove quotes around it.
function isValidPostcode() {
var p = document.getElementById('postcode').value.replace(/\s/g, '');
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
document.getElementById("postcode").addEventListener("keyup", function() {
isValidPostcode();
});
<form name="register" method="post" action="" autocomplete="off">
<input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' required />
</form>

Categories

Resources