I'm trying to access an element in javascript function so as to autocomplete the user search, using autocomplete API.
It is not working as the JS code is not able to access that element.
My javascript code:
<script>
$(function() {
$("#q").autocomplete({
source: "/api/get_drugs/",
minLength: 2,
});
});
</script>
My reference for search.
My Form:
<form id = "myForm" method="GET" action="{% url 'search' %}">
<input style="width:340px;height:37px;" size="30" type="text" id = 'q' name = 'q' placeholder="Search products or categories"/>
<input type="submit" value="Search" >
</form>
Here the input target field has id and name- 'q'.
The bellow code works perfect . Now make sure that the response you are getting from the api is an array .
Or else do one thing , store the response of API in some variable and assign that variable to key Source . For example :
source : apiResponseVariable //must be array .
$(function() {
$("#q").autocomplete({
source: ["hello" , "how"],
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>GnG</title>
</head>
<body>
<form id = "myForm" method="GET" action="{% url 'search' %}">
<input style="width:340px;height:37px;" size="30" type="text" id='q' name = 'q' placeholder="Search products or categories"/>
<input type="submit" value="Search" >
</form>
</body>
</html>
You can checkout my running run .
Related
I am learning JavaScript so I decided to make a small project of simple if/else statement login. Everything is fine, but it is not redirecting.
If you know what I am doing wrong please help me in simple language
because I am learning it.
'use strict'
function validate(){
var username=document.getElementById('login-username').value;
var passowrd=document.getElementById('login-password').value;
if (username === "daksh" && passowrd === 'daksh'){
alert('You have sucessfully logged in');
window.location.href("http://stackoverflow.com");
} else{
alert('Wrong username or password');
return true;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="login.css">
<title>Login</title>
<script src="login.js"></script>
</head>
<body>
<DIV class="container">
<form method="POST" class="login-form">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<input type="submit" value="Login" id="login-submit" onclick="validate()">
</form>
</DIV>
</body>
</html>
ALWAYS use the submit event handler on a form, NEVER the submit button - you want to block the submission in case of error, or in your case blcok because you are handling the processing yourself
Use eventListener instead of inline event handler
You use location.href as a function, it is not. You could use location.replace(href) if you wish
For obvious security reasons, do not do client side passowrd validation, but I assume it is just for learning purposes
window.addEventListener("load", function() { // when the page has loaded
document.getElementById("myForm").addEventListener("submit", function(e) { // passing the event
e.preventDefault(); // you do not want to let the form submit because you handle the nex page
const username = document.getElementById('login-username').value;
const password = document.getElementById('login-password').value;
if (username === "daksh" && password === 'daksh') {
alert('You have sucessfully logged in');
window.location.href = "http://stackoverflow.com";
} else {
alert('Wrong username or password');
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="login.css">
<title>Login</title>
<script src="login.js"></script>
</head>
<body>
<div class="container">
<form method="POST" class="login-form" id="myForm">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<input type="submit" value="Login" id="login-submit">
</form>
</div>
</body>
</html>
window.location.href is a property, not a method, so your code should be like:
window.location.href = "http://stackoverflow.com";
More info about it on MDN Web Docs
window.location.href is not a function.
You need to assign the url to window.location.href.
window.location.href = 'http://stackoverflow.com';
However, window.location.href simulates a click. If you want to simulate a HTTP redirect use window.location.replace instead.
window.location.replace('http://stackoverflow.com');
Edit:
You are also submitting the form, because there is a form method and a submit input specified. This triggers a form post and because no action is specified it will reload the page. Remove the form method and use a button instead.
function validate(){
var username=document.getElementById('login-username').value;
var passowrd=document.getElementById('login-password').value;
if (username === "daksh" && passowrd === 'daksh'){
alert('You have sucessfully logged in');
location.href = 'http://stackoverflow.com';
} else{
alert('Wrong username or password');
return true;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<DIV class="container">
<form class="login-form">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<button type="button" value="Login" id="login-submit" onclick="validate()" value="login">Login</button>
</form>
</DIV>
</body>
</html>
This is what you should do as regards redirecting to another page using javascript
Here is the index.html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="login.css">
<script src="demo.js"></script>
<title>Login</title>
</head>
<body>
<div class="container">
<!-- Form was given an id of 'formLogin' which will be refernced from javascript. -->
<form method="POST" class="login-form" id="formLogin">
<h1 class="login-heading">LOGIN FORM</h1>
<input type="text" placeholder="User Name" id="login-username">
<br><br>
<input type="password" placeholder="Password" id="login-password">
<br><br><br>
<input type="submit" value="Login" id="login-submit" onclick="validate()">
</form>
</div>
</body>
</html>
From
demo.js
javascript file, the below code
'use strict'
// a function to validate the fields supplied from the form
function validate(e){
e.preventDefault(); // this is to prevent the form from refreshing on submitting
//getting the values from the textfields in the form
let username=document.getElementById('login-username').value;
let passowrd=document.getElementById('login-password').value;
// if the name and password matches the required credentials,
if (username === "daksh" && passowrd === 'daksh'){
alert('You have sucessfully logged in'); //display a successful login alert
location.href = "http://stackoverflow.com"; //redirect to the URL specified
} else{
alert('Wrong username or password'); // display alert for wrong credentials
return false;
}
}
// Here we are adding an event listener to the form in our index.html file
// When the form is submitted, the custom validate function is called.
document.getElementById('formLogin').addEventListener('submit', validate);
</script>
I've been trying to make a simple login system (local) and I'm a bit confused.. How can I take the input the user wrote into the text field print it in console and store it in a variable?
My HTML code:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form name="">
<label for="text1">Username:</label>
<input type="text" name="text1">
<label for="text2">Password:</label>
<input type="text" name="text2">
<button onclick="password(), username()">login</button>
</form>
</body>
</html>
For my JS I wanted to have the ''password() and username()'' functions checking both seperatly in seperate files.
JS Password file:
const Psword = 'Password9' //just an example
function password() {
console.log(Psword)
// if (user input from password field) = Psword
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
JS Username file:
var Username = 'Subject09'
function username() {
console.log(Username)
// if (user input from username field) = Username
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
EDIT: Added my JS code.
(Note: I've split my code into 2 diffrent JS files because I just want it to be simple in the outcome.)
We can do a form submit using onsubmit event.
UPDATE: I am showing you the form submit approach.
const form = document.querySelector("form");
form.addEventListener("submit",(e)=>{
e.preventDefault();
if(form["text1"].value && form["text2"].value){
console.log("Submitted the form");
form.reset();
}else{
console.log("Provide required values");
}
})
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<div>
<label>Username:</label>
<input type="text" name="text1" >
</div>
<div>
<label>Password:</label>
<input type="text" name="text2">
<div>
<button type="submit">login</button>
</form>
</body>
</html>
Set ids to you input and your button. You can prevent submitting by adding type="button" to your button.
Simply set an onclick event on your button, and get your inputs values.
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<label for="text1">Username:</label>
<input type="text" name="text1" id="username">
<label for="text2">Password:</label>
<input type="text" name="text2" id="password">
<button type="button" id="submitBtn">login</button>
</form>
window.onload = function() {
document.getElementById('submitBtn').addEventListener('click', onSubmit);
}
function onSubmit() {
console.log(document.getElementById('username').value);
console.log(document.getElementById('password').value);
// Do what you want with data
// You can submit with .submit()
document.forms['form'].submit();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input type="submit">
</form>
<script type="text/javascript">
let actualWord = document.getElementById('word');
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
</script>
</body>
</html>
Im very new to the world of coding and im hoping someone could help me with a "simple" test I was trying to perform.
I want this HTML code to replace the "Placeholder" text at the top of the screen with "oh Yeah" if the user types "yes" in the form.
Im hoping someone can tell me what im doing wrong or point me in the right direction.
https://github.com/Uken81/Form-test.git
1.You need to listen to form submit event and trigger a function
HTML
<form onsubmit="return handleSubmit()">...</form>
Javascript
function handleSubmit(evt) {
...
}
2.You get user's input value like this
document.getElementById('word').value
3.Also you need to prevent form from submitting, By returning false
Full Example
function handleSubmit(evt) {
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
}
return false;
}
<h1>placehold</h1>
<form onsubmit="return handleSubmit()">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
</form>
You can achieve that by adding click event listener to the <submit> button inside the form, and then perform the check on the text <input> and use .value attribute to get the <input> text value, note that I used [e.preventDefault()][3] to prevent the form from redirect, here is a working snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>placeholder</h1>
<form method="get">
<label for="word">enter word</label>
<input id="word" name="word" type="text" maxlength="15">
<input id="change-placeholder" type="submit">
</form>
<script type="text/javascript">
document.getElementById('change-placeholder').addEventListener('click', function(e){
e.preventDefault();
let actualWord = document.getElementById('word').value;
if (actualWord === 'yes') {
document.querySelector('h1').innerHTML = "oh yeah";
} else {
document.querySelector('h1').innerHTML = "error";
}
})
</script>
</body>
</html>
I'm trying to clear my input field's ,but when i clear them php pushes empty string to my database .could someone help me?
this is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'phpAdd.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
function submitForm(){
var form = document.getElementById("myForm");
form.reset();
$('#firstname').focus();
}
</script>
</head>
<body>
<center>
<form action="phpAdd.php" method="post" id="myForm">
<h1>Please enter your info.</h1>
First Name: <input type="text" name="firstname" id="firstname" class="firstname"><br>
Last Name: <input type="text" name="lastname" id="lastname" class="lastname"> <br>
<input type="submit" value="SUBMIT" class="SUBMIT" onclick="submitForm()">
</form>
</center>
</body>
</html>
how could i clear the field's after it pushes the data to php?
I have the following code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
</body>
</html>
Another HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript">
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
</script>
</body>
</html>
I am trying to pass on the value 'name' and retrieve it on a different html page (results.html). How do I accomplish this? I am not sure what I am doing wrong. Please help. Thank you!
pass the variable in the url using GET like :
<form method="get" action="result.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
and retrieve it in the other page like :
<h2> Your Form Has Been Submitted </h2>
<script>
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
console.log(name) // this is your variable
document.querySelector('h2').innerText += name;
</script>
One way is: you could use the 'get' method on the form, and not 'post':
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OrderUp</title>
</head>
<body>
<!-- Use method 'GET', not 'POST', to pass the form values via the url in the address bar -->
<form method="GET" action="results.html">
Name :
<input name="name" type="text">
<br>
<input value="Submit" type="submit">
</form>
</body>
</html>
Then, in result.html, use javascript to extract the name value from the page url.
result.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<span>Name Submitted: </span>
<span id="name-label"></span>
<script type="text/javascript">
// Get the value passed in the url by the form
var querystring = location.search;
// => ?name=Roger
// Remove the '?' at the beginning
var nameValuePair = querystring.replace(/^\?/, '');
// => name=Roger
// Split into parts
var parts = nameValuePair.split('=');
// The name is the second value
var name = parts[1];
// Set the name in the HTML element.
document.getElementById('name-label').innerHTML = name;
</script>
</body>
</html>
You cannot simply take a function from one html and put it into another. Using pure JavaScript and HTML the best way to accomplish this would be to make a JavaScript file, put the function there and load it on both pages. That way if you edit the function in one place, it will change in both.
The code would look like this:
Page 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
Page 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
results.js
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
Probably the simplest would be to append it to the url:
<script>
function goToResults() {
window.location = "results.html#" + document.getElementbyId('name').value;
}
document.getElementById("submit").onclick = goToResults;
</script>
<input id = "name" />
<button id = "submit" > Submit </ button>
And on results.html just get it from the location:
document.body.innerHTML += document.location.href.split("#")[1];
You need a way to save the information you want to share between pages. There are many options for javascript each with pros and cons
use the uri hash:
location.hash = myValue / var retrieveValue = location.hash;
use localstorage:
localStorage.setItem("key", "value"); / localStorage.getItem("key");
also document.cookie is an option, (you can look that one up as it's slightly more involved to implement with many good answes already around)