Validate a form without submitting - javascript

I have the following code that checks to see that two select fields are identical. The code works alright when called with onsubmit. However after doing this validation the form is still submitted. How can i prevent the script or my form from submitting the incorrect data.
Please see code below:
var fieldalias="Email address field"
function verify(element1, element2) {
var passed=false
if (element1.value=='') {
alert("Please fill out the "+fieldalias+"!")
element1.focus()
}
else if (element2.value=='') {
alert("Please verify the "+fieldalias+"!")
element2.focus()
}
else if (element1.value!=element2.value) {
alert("The two "+fieldalias+"s do not match")
element1.select()
}
else
passed=true
return passed
}

You didn't include your HTML, so I'm going to assume you've added onsubmit() to your form element.
If so, make sure your call looks like this:
onsubmit="return verify(element1, element2)"
(replace element1 and element2 accordingly)
If this assumption is not correct, please include some additional detail so we can better assist.

Try calling stopImmediatePropagation() on the event to prevent any further processing of the submit event by any other handlers in the form element or higher level elements.

Call that code with different event, like i.e: onchange, or onfocusout. This way the validation will be performed every time user enter some values to your fields, certainly before submitting.
EDIT:
I'm not sure if I understand you correctly but I would have attached your JS code this way:
First assign your select box to the variable:
var object_input = document.getElementById("selectId");
And then:
if(object_input.addEventListener)
{
object_input.addEventListener('blur', focus_lost);
object_input.addEventListener('keypress', checkForEnter);
}
else
{
object_input.attachEvent('onblur', focus_lost);
object_input.attachEvent('onkeypress', checkForEnter);
}
and then perform your validation ith focus_lost or checkForEnter.

Assuming that in the html code you have something like this:
<form action="test2.html" method="post" onsubmit="return verify(e1, e2);">
<input type="text" name="e1" /><br/>
<input type="text" name="e2" /><br/>
<input type="submit" value="Validate" />
</form>
You have to put in onsubmit event:
return verify(e1, e2);
so you will not go to the submiting page if the data is not valida
EDIT:
I think the problem is the
element1.select()
in the 3rd if, that this select method does not exist for a select object.
You can use a
element1.focus()
The code that will work is:
var fieldalias="Email address field"
function verify(element1, element2){
var passed=false;
if (element1.value==''){
alert("Please fill out the "+fieldalias+"!");
element1.focus();
}
else if (element2.value==''){
alert("Please verify the "+fieldalias+"!");
element2.focus();
}
else if (element1.value!=element2.value){
alert("The two "+fieldalias+"s do not match");
element1.focus();
}
else
passed=true;
return passed;
}
And
<form action="test2.html" method="post" onsubmit="return verify(document.getElementById('e1'), document.getElementById('e2'));">
<select id="e1">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<select id="e2">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<input type="submit" value="Validate" />
</form>

Related

onsubmit doesn't display text [duplicate]

I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" action="" METHOD="POST">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit" name="submit" onClick="myFunction()"/>
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as 'script type="text/javascript" src="script.js':
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
}
};
When I fill out the form and hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.
How do I make it so that the insertion of HEADING remains permanent?
Move the listener to the form's submit handler. Have the function return false to stop submission:
<form id="date_form" onsubmit="return myFunction();" ...>
Take the listener off the button:
<input type="submit">
Do not give it a name of submit as that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.
There is an error in your code, it's missing a closing double qoute:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false; // to stop submission
};
This may or may not fix you issues, you haven't said what you are actually trying to do.

Getting selected datalist option value, and innerHTML, without using jQuery

I have a situation where I want to let a user decide titles of books that I have on my db, using an input with a datalist (generated by php), after the user picked a title, he would click a submit button and the form would send the title in another file.
Everything worked fine but I didn't realized that I needed to send the ID of the book that the user selected, because there can be more than one book with the same title.
What I would like to have is the option of the datalist, that no longer has the title of the book inside its "value" attribute, but I want that title inside its innerHTML, so that the title gets displayed, while having the ID inside the "value" attribute. My problem is that if I do that, when the user clicks on the datalist option, the ID gets inside the text input, so the user may not know what book he choose.
summing up: I would like to have the datalist that displays the title, when an option is chosen, that title gets displayed in the text input, when I submit, the Id of the book gets sent in "FindBook.php" inside $_POST.
isIn() checks if the title is inside the array of titles, I would need to change that so that it can check if the ID is inside the array of IDs.
<form onsubmit="alert(document.getElementById('number').value);" action="FindBook.php" target="_blank" method="POST">
<input id="number" list="BooksById">
<input type="submit" value="Find">
</form>
<datalist id="BooksById">
<option value="1">Title1</option>
<option value="2">Title2</option>
<option value="3">Title3</option>
<option value="4">Title4</option>
</datalist>
<br>
<form onsubmit="alert(document.getElementById('string').value);" action="FindBook.php" target="_blank" method="POST">
<input id="string" list="booksByTitle">
<input type="submit" value="Find">
</form>
<datalist id="booksByTitle">
<option value="Title1"></option>
<option value="Title2"></option>
<option value="Title3"></option>
<option value="Title4"></option>
</datalist>
Since I don't understand jQuery I would really prefer a solution that doesn't imply that.
I think that in your case you must use a <select> tag instead of a <datalist> because you do not want the end user to enter new names (or yes?). However you can work with the data attributes like in the code below:
HTML:
<input list="titles" id="title-input" oninput="getBookId()">
<datalist id="titles">
<option data-value="5" value="A book name">
</datalist>
JavaScript:
function getBookId() {
var selectedTitle = document.getElementById("title-input").value;
var value2send = document.querySelector(`#titles option[value='${selectedTitle}']`).dataset.value; // Here now you have the book title id.
console.log("getBookId ~ value2send", value2send)
}
I hope it works for you.
Assuming you can provide distinct title values for each datalist option...
Add a dataset attribute, such as data-id, to your datalist option elements, containing the corresponding id, and add a hidden type input to your form. Then use the onsubmit event handler function to get the selected datalist option's dataset id value and assign it to the value of the hidden input:
function findBook(form) {
form.bookid.value = document.querySelector(`datalist option[value="${form.booktitle.value}"]`).dataset.id;
console.log(form.bookid.value);
return false;
}
<form onsubmit="return findBook(this)">
<input type="hidden" name="bookid">
<input name="booktitle" list="BooksById">
<input type="submit" value="Find">
</form>
<datalist id="BooksById">
<option data-id="1" value="Title1">
<option data-id="2" value="Title2">
<option data-id="3" value="Title3">
<option data-id="4" value="Title4">
</datalist>
Upon form submission, your PHP file will have the variables $_POST['bookid'] and $_POST['booktitle'] available.
Thanks for your suggestions. I prefer to use a datalist, instead of a select tag, because it looks more like a dropdown menu that works like a button. Using datalist allows me to find a book by a random word inside the title of it, while the select only finds the first word of an entry. I can also distinguish different books with the same name by another attribute that states if it's available or if it's taken.
I asked for no JQuery, i appreciate your help but I really don't understand them, even if it's cleaner to use them I would like a solution that doesn't use them.
I ended up using the solution CBroe suggested:
document.getElementById("bookTitle").addEventListener('input', function (evt) {
let data = this.value.split('');
document.getElementById("bookId").value = "";
if(isIn(data,'books')){
document.getElementById("bookId").value = data[0];
document.getElementById("bookTitle").value = data[1];
}
});
function checkForm(id, value, list){
if(isIn([document.getElementById(id).value,document.getElementById(value).value],list)){
alert("Book found");
return true;
}else{
alert("not found")
return false;
}
}
function isIn(value, list) {
switch (list) {
case 'books':
//this was generated by php in my code
if (value[0] == 1 && value[1] == "Title1"){
return true;
}
if (value[0] == 2 && value[1] == "Title2"){
return true;
}
return false;
break;
//I've cut out other cases
}
}
<form onsubmit="checkForm('bookId','bookTitle','books')" action="FindBook.php" target="_blank" method="POST">
<input id="bookTitle" list="booksByTitle" autocomplete="off">
<label>id:</label>
<input id="bookId" <!--type="hidden"-->
<input type="submit" value="Find">
</form>
<datalist id="booksByTitle">
<!-- value was generated by php in my code-->
<option value="1Title1">Title1</option>
<option value="2Title2">Title2</option>
</datalist>

Why The Validation is not working for the provided html/ js code

I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required

How to make the chosen value of select list visible

How I can make the selected choice still visible until I re-choose another one?The list may contain more than 10 options
=====
<form method="get" action="Chairman.php" >
<select name="courses" id="courses" class="styled-select" >
<option value="courses"><--Courses--></option>
<option value="PHYS220">Physics for Engineers</option>
<option value="MATH210">Calculus II</option>
<option value="MATH225">Linear Algebra with Applications</option>
</select>
<input type="submit" value="Search Instructor"
onClick="checkDropdown()"></input>
<div id="error" style="color:red"></div>
=====
Also when I am trying to validate the select list,The error is displayed and then quickly it disappears
<script>
function checkDropdown () {
var courses = document.getElementById('courses');
if(courses.value==="courses") {
document.getElementById('error').innerHTML="PLEASE selecttt";
return false;
}
}
</script>
The select is reset and the error disappears because the form is still posted. The value that you return from the function doesn't stop the submission.
You should use the onsubmit event on the form instead of onclick on the button. Use return in the event code to convey the value from the function back to the event:
<form method="get" action="Chairman.php" onsubmit="return checkDropdown()">

javascript myform.action doesn't

I'm trying to use javascript in JSP with a form. The form has a dropdownlist with an onchange event to call a function to sumbit the selected value to a servlet. I'm getting an error "Object doesn't support this action". What is the syntax error in my code?
Here is my code:
<form id="input" method="post" action="ResultServlet">
<input id=year type=text value="george">
<input id=year type=text value="mary">
<input id=year type=text value="fred">
<select id=casesId onchange = "sendCases();">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3 </option>
</form>
<script typ=text/javascript>
function sendCases(){
var id = document.forms[0].caseId.options[document.forms[0].caseId.selectedIndex.value;
if (id !='' || id == null{
document.forms[0].action('CaseServlet').submit();
}
}
</script>
Any help you could give would be great. Thanks!
Change:
if (id !='' || id == null{
document.forms[0].action('CaseServlet').submit();
}
For:
if (id!='' || id == null) {
document.forms[0].action = 'CaseServlet';
document.forms[0].submit();
}
You have a syntax error where you forget to close the if. It might be a typo though.
action is not a method, it's a property. You don't execute it, you assign a value to it.
The submit() method only works on the form object, not something else :)

Categories

Resources