How to get search bar to take input and go to page - javascript

I'm trying to get a search box that when it takes an input it sends the user to a specific page. But for some reason that, I cannot figure out, it doesn't do anything when an input is given. My code is the following:
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script type="text/javascript">
var input = document.getElementById("search");
function sendToPage(){
if (input.value == "happy"){
location.href="suggestion_happy.html";
}
else if (input.value == "sad"){
location.href="suggestion_sad.html";
}
else {
alert('Invalid Input.');
}
}
</script>
</head>
<body>
<div>
<form onsubmit="sendToPage()">
<input type="text" method="put" id="search" placeholder="Search" value="">
</form>
</div>
</body>
</html>
Please help I'm still kind of new to javascript :)

you don't need to create a form to do this
check out this code
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script type="text/javascript">
function sendToPage(){
var input = document.getElementById("search").value;
//alert(input);
if (input == "happy"){
location.href = "suggestion_happy.html";
return false;
}
else if (input == "sad"){
location.href = "suggestion_sad.html";
return false;
}
else {
alert('Invalid Input.');
}
}
</script>
</head>
<body>
<div>
<input type="text" method="put" id="search" placeholder="Search" value="">
<input type='submit' onclick="sendToPage();" />
</div>
</body>
</html>

<script type="text/javascript">
function sendToPage(){
var input = document.getElementById("search").value;
//alert(input);
if (input == "happy"){
//location.href="suggestion_happy.html";
location.replace("suggestion_happy.html");
return false;
}
else if (input == "sad"){
location.replace("suggestion_sad.html");
return false;
}
else {
alert('Invalid Input.');
}
}
</script>
<div>
<form action="" onsubmit="return sendToPage()" method="post">
<input type="text" id="search" placeholder="Search" value="">
</form>
</div>
I have edited my asnwer plz try this

there are two problems here:
submitting a form will always refresh the page. So onsubmit is
killing your app
by putting the js in the <head> your
document.getElementById call fails because that element doesn't
exist yet. Javascript belongs at the end of the page, just before
the closing </body> tag

Related

Why `return()` & `onsubmit()` do not work while creating a login form to welcome page in html

While creating login form to welcome page in HTML, CSS, js the problem faced is the return statement is not working.
create code for HTML inbuilt javascript.
<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="loginbox">
<img src="C:\Users\Hp\Pictures\Camera Roll\avatar2.png" class="avatar">
<h1>Login Here</h1><br>
<form action="loginbox.html" method="post" onsubmit="return validate()">
<div>
<p>user name</p>
<input type="text" name="" placeholder="Enter User name" id="user name">
</div><br>
<div>
<p>password</p>
<input type="password" name="" placeholder="Enter password" id="password">
</div><br>
<input type="submit" name="" value="login"><br>
Lost your pasword??<br>
don't have an account??
</form>
</div>
<script type="text/javascript">
var attempt = 3;
function validate()
{
var user name= document.getElementById("user name").value;
var password= document.getElementById("password").Value;
if(user name.value=="dr" && password.value=="8428")
{
return true;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
</script>
</body>
</html>
Using return false statement it should stop entering into welcome page, but in this code it's not working, it goes to next page.
Tried that onsubmit="return false; validate();" while using this code entire block gets stop & won't enter to welcome page.
You are using spaces in your id attribute which is incorrect, the id attribute must not have anykind of spaces. Plus, you are missing id="submit" on the submit button. In your code the JS is unable to execute this line
document.getElementById("submit").disabled = true;
Because the submit button doesn't have any ID.
Below has the errors fixed. This should work
<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="loginbox">
<img src="C:\Users\Hp\Pictures\Camera Roll\avatar2.png" class="avatar">
<h1>Login Here</h1><br>
<form action="loginbox.html" method="post" onsubmit="return validate()">
<div>
<p>user name</p>
<input type="text" name="" placeholder="Enter User name" id="username">
</div><br>
<div>
<p>password</p>
<input type="password" name="" placeholder="Enter password" id="password">
</div><br>
<input type="submit" name="" value="login" id="submit"><br>
Lost your pasword??<br>
don't have an account??
</form>
</div>
<script type="text/javascript">
var attempt = 3;
function validate()
{
var username= document.getElementById("username").value;
var password= document.getElementById("password").Value;
if(username == "dr" && password == "8428")
{
return true;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
</script>
</body>
</html>
The problem was that id was missing in submit, you have to declare id in the input that has type submit. Secondly, the logic was incorrect when you validate the form, return statement was missing in the else part when the attempt was not equal to zero.
<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
var attempt =3;
function validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "dr" && password == "8428") {
return true;
} else {
attempt--;// Decrementing by one.
alert("You have left " + attempt + " attempt!");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
return false;
}
}
</script>
</head>
<body>
<div class="loginbox">
<h1>Login Here</h1><br>
<form action="/loginbox.html" name="myForm" onsubmit="return validateForm()">
<div>
<p>user name</p>
<input type="text" name="userName" placeholder="Enter User name" id="username">
</div><br>
<div>
<p>password</p>
<input type="password" name="password" placeholder="Enter password" id="password">
</div><br>
<input type="submit" id="submit" value="login"><br>
Lost your pasword??<br>
don't have an account??
</form>
</div>
</body>
</html>

form onsubmit won't work unless in Javascript [duplicate]

This question already has an answer here:
Javascript not working on submit
(1 answer)
Closed 5 years ago.
I recently started doing form validation and I am trying to understand something. I have yet to find this anywhere else on SE.
When I have onsubmit="return validateForm()" or onsubmit="validateForm()" in the <form> element, the form does not do anything. However, when I remove onsbumit from the form tag and instead do document.forms["favorite"].onsubmit = function validateForm() in the JS file, it works fine.
I got it working, but I am trying to understand why the "normal" method of onsubmit in the html isn't working.
For reference, here is my code as it works now:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="form.js"></script>
<title>Form</title>
</head>
<body>
<form name="favorite" action="#" method="post">
Favorite Car Brand: <input type="text" name="car">
<input type="submit" value="Submit">
</form>
</body>
</html>
JS:
window.onload = function(){
document.forms["favorite"].onsubmit = function validateForm(){
var input = document.forms["favorite"]["car"].value;
if(input == ""){
alert("You missed an entry");
return false;
}
}
}
First of all we define a function and then we call that function. and you are calling that function before defining as you are using window.load.You need to define the validation function before window.load as you are using. Sorry for my poor English.
<script>
window.onload = function () {
function validateForm() {
var input = document.forms["favorite"]["car"].value;
if (input == "") {
alert("You missed an entry");
return false;
}
}
}
</script>
define validateForm() function before window.load you do not need to write this function inside the window.load.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form</title>
<script>
function validateForm() {
var input = document.forms["favorite"]["car"].value;
if (input == "") {
alert("You missed an entry");
return false;
}
}
</script>
</head>
<body>
<form name="favorite" action="#" onsubmit="return validateForm();" method="post">
Favorite Car Brand: <input type="text" name="car">
<input type="submit" value="Submit">
</form>
</body>
</html>

value is not displayed when enter the value to the text box

This is works fine when the form does not have any value. But, Once i entered the value on the textbox, it still alert the same messages i.e it is omitting 'You must enter value' for both cases,see at the if else statement. what is the mistake on the below code?
<!doctype html>
<html>
<head>
<title>A Basic Example</title>
</head>
<body>
<p>A Basic Form Example</p>
<form action="#">
<p>Name <em>(Required)</em>: <input id="textbox1" name="textname" type="text" /></p>
<p><input id="submitbutton1" type="submit" /></p>
<script type="text/javascript">
var item = document.getElementById("textbox1").value.length;
var item1 = document.forms[0].textname;
function formValid() {
if (item == 0) {
alert("You must enter value");
}
else {
alert(item1);
}
}
var formEl = document.getElementById("submitbutton1");
formEl.addEventListener("click", formValid());
</script>
</form>
</body>
</html>
You are fetching the length of the value when the page loads instead of when the the function runs.
Move
var item = document.getElementById("textbox1").value.length
inside the function.
Use this syntax in addEventListener formEl.addEventListener("click", formValid,false);
Also replace var item inside the function formValid().
Here is the fiddle
try this
<!doctype html>
<html>
<head>
<title>A Basic Example</title>
</head>
<body>
<p>A Basic Form Example</p>
<form action="#">
<p>Name <em>(Required)</em>: <input id="textbox1" name="textname" type="text" /></p>
<p><input id="submitbutton1" type="submit" /></p>
<script type="text/javascript">
var item1 = document.forms[0].textname;
var formEl = document.getElementById("submitbutton1");
function init() {
formEl.addEventListener("click", formValid());
}
function formValid() {
var item = document.getElementById("textbox1").value.length;
if (item == 0) {
alert("You must enter value");
}
else if {
alert(item1);
}
}
</script>
</form>
</body>
</html>

Why is the a form fade function not allowing validation?

Is this code correct? I want the 'submit' to validate the field (to make sure a value has been entered) and if this is correct (there is a value) then fade and display.
Currently, the form fades even when no value is entered? I feel I'm missing something really simple here!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />
<link rel='stylesheet' type='text/css' href='styles.css' />
<meta charset="utf-8"-->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<div id="sidebarf">
<form id="sidebarform" name="myForm" onsubmit="return validateForm()" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" required>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
<script>
$("#sidebarformsubmit").click( function(){
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() )
});
});
</script>
</body>
</html>
Judging by your comment on the other answer, you don't care if this actually gets submitted, so you could do the following:
HTML:
<div id="sidebarf">
<form id="sidebarform" name="myForm" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" />
<input type="submit" id="sidebarformsubmit" value="Submit" />
</form>
JS:
$(document).ready(function() {
$('#sidebarform').on('submit', function() {
if ($('#sidebarusername').val() == '') {
alert('First name must be filled out');
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() );
});
return false;
});
});
Working example:
http://jsfiddle.net/3z5x8/
Your validation is bound to the submit event. The click event will always be fullfilled.
Bind your handler to the submit event also
$("#sidebarformsubmit").submit( function(){.....
Unless you are submitting with ajax the form will cause a page refresh also which means your fade and show new html won't work

Form validation problem, code doesn't work

I really don't know why this validation doesn't work.
this is my html:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type='text/javascript' src="scripts.js"></script>
<title>Test Page!</title>
</head>
<body>
<form onsubmit ="return validateFormOnSubmit(this)" name="myForm" action = "testForm.html">
<input name="textField" type="text" value="" size="50" id= "textfield" /> <br />
<input name="button" type="submit" value="Submit"/>
</form>
</body>
</html>
and this is my javascript file:
function isURL(fld){
var error = "";
var regex = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
if(regex.test(fld.value)){
error = "No URL's Allowed!";
}
else{
error = "";
}
return error;
}
function validateFormOnSubmit(myForm) {
var reason = "";
reason += isURL(myForm.textField);
if (reason != "") {
alert("there's something wrong: \n" + reason);
return false;
}
return true;
}
Thanks for your help.
update: is the action really required? testpage.html is just an empty html file here!
update 2: The problem is I don't see any message or alert.
It works fine, your scripts.js file isn't loaded properly or an old version is cached in your browser
Looks like you're passing in the form, rather than the field that you're trying to validate.

Categories

Resources