JavaScript Form validation not working; something wrong with onsubmit() attribute? - javascript

I cannot work out what is wrong with my code, and why the form validation simply is not firing. The code is an HTML form for inserting books into a database. I removed the PHP and CSS for simplicity's sake, but I can edit it back in if necessary.
function validateNewBook() {
var isbn = document.forms['addNewBook']['isbn'].value;
var title = document.forms['addNewBook']['title'].value;
if (title == ""){
alert("Please enter the book's title.");
return false;
}
return true;
}
<form name="addNewBook" action='#' onsubmit="return validateNewBook()" method="post">
<section id="controls">
<input class="button" type="submit" name="save_new_book" value="Save Book"/>
<input class="button" type="submit" name="browse_books" value="Browse"/>
</section>
<section id="input">
<span>* required field</span>
<span class="flex-input">
<label>ISBN</label><input type="text" name="isbn" id="isbn" size=20 value="" /> <span class="errorMessage">*</span>
</span>
<span class="flex-input">
<label>Title</label><input type="text" name="title" size=50 id="title" value="" />
<span class='errorMessage'>*</span>
</span>
</section>
</form>
However, when I run this code in my fuller program, the form still enters the new book into the database, even when the Title field is empty. What is happening?

It may be the case that user have input blank space on inputbox. So are required to filter that inputbox with trim function.For example.
title.trim();
You need to do before you mention any expresion.

Related

Disable or enable only the current button

With a PHP for each cycle, I'm bringing articles from the database. In those articles, we have a comment section with a form. I want to check with jQuery if there is something written on the input before the comment is sent.
As the articles are being brought with a PHP cycle, I want to check only the article in which it is being written a comment, but jQuery checks all the articles and only enables or disables the first or top result being brought from the database. I want jQuery to check only on the article with a written comment.
Here's what I'm doing:
$(document).ready(function() {
$(".comment-submit").attr("disabled", true);
$("#group-post-comment-input").keyup(function() {
if ($(this).val().length != 0) {
$(".comment-submit").attr("disabled", false);
} else {
$(".comment-submit").attr("disabled", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
As you can see on the snippet above, the buttons only get enabled when text is written on the first input only. I want the buttons to get enabled when text is written on their dependent input. If input 2 has text on it, enable button 2, and so on and so on.
How can I do that?
Since IDs must be unique to the DOM tree, you might consider using a class instead.
$(function() {
$(".group-post-comment-input").on('keyup', function() {
let $button = $(this).next('.comment-submit');
let disabled = !this.value;
$button.prop('disabled', disabled);
});
});
form {
margin: 0 0 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
In my demonstration, I use jQuery's next() to traverse from the input on which the "keyup" event is fired to its associated button.
.next( [selector ] )
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Another method is to traverse up to the form element with closest() and back down to the button with find(). This might be useful if you expect your HTML structure to change in a way that could break the next() traversal.
let $button = $(this).closest('form').find('.comment-submit');
I also recommend using prop() instead of attr() to enable and disable inputs.
ID must be unique,
but you need to use a name for sending information to your PHP server
document.querySelectorAll('button.comment-submit').forEach( bt => bt.disabled = true )
document.querySelectorAll('input[name="group-post-comment-input"]').forEach( inEl =>
inEl.oninput = e =>inEl.nextElementSibling.disabled = (inEl.value.trim().length === 0) )
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>

Clear input field without reloading of the page

I have a input field where a user enters in a name at the end of a quiz and i have tried various methods of clearing the field. The page cannot re-load as the user is able to restart a quiz.
Here is my HTML:
<div class="js-quiz-submit">
<input type="text" class="js-name" placeholder="Please Enter Your Name"/>
<input type="button" class="js-submit" value="Submit"/>
</div>
If your input field is in a form say #quiz-form, then you can clear the fields of form as follows:
var form = document.querySelector('#quiz-form');
form.reset();
I guess the better way will be :
document.querySelector(".js-name").value = "";
Html:
<div class="js-quiz-submit">
<input type="text" id="js-name" class="js-name" placeholder="Please Enter Your Name"/>
<input type="button" class="js-submit" value="Submit"/>
</div>
Javascript:
document.getElementById('js-name').value='';

Issue with form validation Javascript

I am using Bootstrap and I have two identical forms. I am trying to add form submission to Google Search results and it works but when I include two of the same form it doesn't work because of the id being the same on both. How can I fix this? The ID needs to be the same because google looks for the "G". The reason I have two forms is because I have it displayed differently on mobile. Using media queries. Below is my code thanks.
<form name="globalSearch" class="navbar-form" role="search" form action="" onsubmit="return validateSearch()">
<div class="input-group add-on">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:11;NB:1" />
<input type="hidden" name="ie" value="UTF-8" />
<input class="form-control" placeholder="Search entire site..." id="q" name="q" type="text">
<div class="input-group-btn">
<button class="btn btn-default btnSubmit" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
function validateSearch() {
if (globalSearch.q.value.length == 0) {
document.getElementById("q").value = "Enter a Value";
document.getElementById("q").style.color = "red";
return false;
}
}
You probably want to change the placeholder, so the user don't have to delete the text than type in a query. Please view updated function.
function validateSearch() {
var q = document.getElementById('q');
if (q.value.length == 0) {
q.setAttribute('placeholder', 'Enter search term')
q.style.borderColor = "red";
return false;
}
}
Two elements can not share same ID.
Either use CSS styling to make different looks in mobile, either hide one of forms from webserver (PHP/etc) side either dont use getElementById - instead, use jQuery:
<form name="globalSearch" ... >
<input name="q" data-input-type="desktop" id="q">
..
</form>
<script>
function validateSearch() {
var field = $("input[data-input-type="desktop"]');
field.val("Enter value here...");
field.css("color","red");
}
</script>

HTML5 validation executes before custom validation

I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>

Issue with javascript retrieve form data for url

I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.

Categories