Im taking input from user and keeping those values in new array called movie2. If user enters input again it should check the value from movie2 array and if it matches should give a pop up like it already added and if it is a different input it should add those values to movie2 array. I have tried many times but whatever the user inputs it is getting added, it is not comparing.
<!DOCTYPE html>
<html>
<head>
<title>Movie Mania</title>
<link rel="stylesheet" type="text/css" href="Movie.css" >
<script src="Movie.js"></script>
</head>
<body>
<div class="content">
<div class="matter">
<p class="header">Movie Mania</p>
<div class="regis">
<form class="reg">
<input type="text" name="user" id="movie" placeholder="Please enter any
movie name" size="40"><hr>
<div><input type="submit" class="button" value="Search" id="sub"
onclick="validation()" /></div >
</form></div>
</div>
</div></body>
</html>
Javascript:
var movie1 = ["Bahubali", "The Final Destination", "The Cars ","P.K "," Bajarangi Baijaan ","Force "];
var movie2=[];
function validation() {
var movie = document.getElementById("movie").value;
if (!movie.trim()) { //its validate the input empty undefined null
var name2 = "Please enter your favoite movie name";
alert(name2);
}
else if (movie1.includes(movie)) { // includes used for find the value is in array or not
var name2 = "Movie exists in our database";
alert(name2);
}
else {
insert();
}}
function insert(){
var movie = document.getElementById("movie").value;
if(movie2.indexOf(movie)==true){
var name2="Movie already added to Array 2";
alert(name2);
}
else{
movie2.push(movie);
var name2 = "Movie added into Array2";
alert(name2);
}
}
.includes() is part of ES2016, which isn't fully implemented in all browsers yet. Use .indexOf() instead. Now, indexOf() returns -1 when the value doesn't exist or the index position of the item when it does. You have:
if(movie2.indexOf(movie)==true){
Which is not the correct way to test against indexOf(). If indexOf() were to return 0, it would mean that the item was found at the first position in the array (indices start with 0). But, because you are attempting to compare it against true, true will be converted to a number (to perform a number to number comparison) and it will convert to 1. Since 0 doesn't equal 1, the test will fail, and insert the movie even though it already exists.
Also, JavaScript does not have block level scope when using the var keyword for declaration. If you declare a variable with var anywhere in a function, its scope is the entire function. So, you can't declare the variable in one branch of the if and then again in the other. In reality, you don't even need to set up your name variable because all you are doing with it is immediately displaying it in an alert(). Instead, you can just put your string in the alert().
Additionally, don't use inline HTML event attributes (onclick, etc.). Here's why.
Lastly, it appears that you are not actually trying to submit data anywhere. In that case, don't use a submit button, just use a regular button.
// Get refrence to button and textbox
var btn = document.querySelector("form.reg input[type=button]");
// Don't create references to DOM properties because if you decide you want
// to get the value of a different property later, you'll have to scan the DOM
// for the element all over again. Just get a reference to the element once and
// then you can access whatever property you need when you need it.
var movie = document.getElementById("movie");
// Set up click event handler
btn.addEventListener("click", validate);
var movie2 = [];
// Your two functions are redundant. They can be combined into this one:
function validate(evt){
// Access the property of the DOM object you want (user input should always be trimmed)
var mv = movie.value.trim();
// Quick test for input:
if(mv === "") {
alert("You didn't enter anything!");
return;
}
// If we've gotten this far, there is input, so test to see if it is already in the array
var message = "";
if(movie2.indexOf(mv) > -1){
message = "Movie already added to Array 2!!!!";
} else {
movie2.push(mv);
message = "Movie added to Array 2";
}
alert(message);
// Just for testing:
console.clear();
console.log(movie2);
}
<div class="content">
<div class="matter">
<p class="header">Movie Mania</p>
<div class="regis">
<form class="reg" action="#">
<input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40">
<hr>
<div>
<input type="button" class="button" value="Search" id="sub">
</div>
</form>
</div>
</div>
</div>
The includes() method determines whether a string contains the
characters of a specified string. This method returns true if the
string contains the characters, and false if not.
Hence we shall not use includes() method to compare/search strings.
There are multiple ways you can search for a string in an array of string.
I check for string given to me in given array of string using
indexOf()
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
And where you are adding the movie to the array, you do not need to read data from input box again. The better idea is to clean up the input, validate it and provide it as input to insert(movie).
Here is the sample code, which is working for me.
var movie1 = ["Bahubali", "The Final Destination", "The Cars ","P.K "," Bajarangi Baijaan ","Force "];
var movie2=[];
function validation()
{
var movie = document.getElementById("movie").value;
movie = movie.trim();
if (!movie) //its validate the input empty undefined null
{
var name2 = "Please enter your favoite movie name";
alert(name2);
}
else if (movie1.indexOf(movie) > -1) // check if movie already exists
{
var name2 = "Movie exists in our database";
alert(name2);
}
else
{
insert(movie);
}
}
function insert(movie)
{
if(movie2.indexOf(movie) > -1)
{
var name2="Movie already added to Array 2";
alert(name2);
}
else
{
movie2.push(movie);
var name2 = "Movie added into Array2";
//alert(name2);
for (var i=0; i < movie2.length ; i++)
{
console.log(movie2[i]);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Movie Mania</title>
<script type="text/javascript" src="testjs.js"></script>
</head>
<body>
<p class="header">Movie Mania</p>
<form>
<input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40">
<hr>
<div>
<input type="submit" class="button" value="Search" id="sub"
onclick="validation()" />
</div >
</form>
</body>
</html>
Related
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 5 years ago.
The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.
Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.
For the purposes of my assessment it needs to be done without using a third party library.
I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1> Prototype Book Storage and Display </h1>
<form id = "formWrapper">
Search<br>
<input id="myTextBox" type="text" name="search">
<br>
<input onClick="submitData()" type="button" value="Submit Book">
<input onClick="printBooks()" type="button" value="Find Book">
<input onClick="deleteData()" type="button" value = "Delete Book">
<p id = "booktitle"></p>
</form>
</body>
</html>
Javascript:
var myFormData = []; //declare an array
var value1;
//Prints My Books to a list
function printBooks() {
clearBook();
alert(myFormData);
document.getElementById('booktitle').innerHTML = myFormData;
}
//Submits input to array
function submitData()
{
value1 = document.getElementById("myTextBox").value;
myFormData.push(value1);
alert(myFormData);
clearField();
}
//Deletes data from the array
function deleteData()
{
deleteValue = document.getElementById("myTextBox").value;
myFormData.splice(deleteValue);
alert(deleteValue + " " + "Deleting your book");
}
//clears textbox field
function clearField()
{
var txt2 = document.getElementById("myTextBox");
txt2.value = "";
}
//Refreshes book object model
function clearBook()
{
var txt3 = document.getElementById("booktitle");
txt3.value="";
}
The problem is in
myFormData.splice(deleteValue);
splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.
In your case it would be
// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
myFormData.splice(index, 1);
}
Edit: |SOLVED| user Jaromanda X's solution worked perfectly. Thank you
My goal is to have the user enter a bit of text into the textbox and submit it. I want to check and see if the textbox is empty and, if so, it should alert the user that a name needs to be entered. If it is not empty I want it to display the text they had entered.
The issue is this: Every time I hit submit it takes the value of the textbox - empty or not - and displays it without ever alerting the user of an empty text field. I feel like I'm missing something very basic. Thank you for your help!
HTML File
<body>
<div id="statusBar">
<h1 id="playerName"></h1>
<h2 id="playerHP"></h2>
</div>
<div id="gameWindow">
Player Name: <input id="inputName" type="text" name="Player Name">
<br>
<input type="button" value="submit" onclick="getStats()";>
</div>
<script src="script.js"></script>
</body>
JS File
function getStats(){
if(document.getElementById("inputName").len === " "){
alert('You must enter a name!');
} else {
var playerHP = 10;
var playerName = document.getElementById('inputName').value;
//Display player name on screen
document.getElementById('playerName').innerHTML = playerName;
//remove the value placed in the text box
document.getElementById('inputName').value = "";
//Display the player's HP
document.getElementById('playerHP').innerHTML = playerHP;
}
};
Change your if statement to:
if (document.getElementById("inputName").value.length === 0) {
Right now you're trying to get a property len of your <input> element, which doesn't exist. You should first be getting the value of the input, and checking if its length is zero. Hence, .value.length.
It should be:
if (document.getElementById("inputName").value === "") {
// do something
}
You're not using the right conditional.
Replace the
document.getElementById("inputName").len
with
document.getElementById("inputName").value.length === 0.
var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?
I am new to HTML forms and I was wondering how I can easily (or not) change it's input to a JavaScript variable. Here is my code:
<head>
<title>Begin</title>
<link type="text/css" rel="stylesheet" href="begin.css"/>
</head>
<body>
<form action="begin-create-done.html" method="get">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
<br>
New Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pass">
<br>
Repeat Password: <input type="password" name="rpass">
<input type="submit" value="Submit">
</form>
</body>
</html>
I want each part of the form (e.x. First Name, Last Name, New Username, etc.) to be it's own JavaScript variable. Thank you very much!
Accessing HTML input elements from JavaScript
Assuming you don't have other elements with same names, you can access input values from JavaScript by name as follows:
var firstName = document.getElementsByName("firstname")[0].value;
You now have the value from firstname field in JavaScript variable called firstName. Just keep repeating and you got the other input fields too. You can then proceed and wrap these statements to a function and call it when input data changes. For example:
function formChanged() {
var firstName = ...
var lastName = ...
}
Now register this function call to change / keyup events and you have a function that monitors changing form values:
<input type="text" name="firstname" onkeyup="formChanged()" onchange="formChanged()"/>
Should you prefer a more structured approach, or if you have more than one form on the page, you could:
Create an object that will hold all form values and update them. After that you could simply access them with formValues.inputName.
Store your default values in an array (in the same order as your inputs).
Execute a function that will take care of outputting the default values & updating the object when the values are changed. It takes the form (selected by Id, Class, whatever) and an array of default values as parameters.
// create the object that will hold the input values
var formValues = {};
// store code in the function for a more 'modular' approach
function inputObj(formNR, defaultValues) { // where defaultValues is an array
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].type === 'text' || inputs[i].type === 'password') {
formValues[inputs[i].name] = defaultValues[i]; // store default in object
}
inputs[i].value = defaultValues[i]; // output default in input
inputs[i].addEventListener('keyup', function() { // update object on change
formValues[this.name] = this.value;
}, false);
}
}
// build a little array with the defaultValues for each input
var defValues =['defaultFirstName','defaultLastName','defaultUser',
'defaultPass','defaultPass'];
// this will push all inputs from the given form in the formValues object.
inputObj(document.forms[0], defValues);
// Access the values like this, eg.
console.log(formValues.firstname); // will return 'defaultFirstName'
See it in action here. Or with CodeView. Note: The code in the example has some additions to show the object's values on the page.
Try to first create a function that grabs the value from the input field:
<script>
function XX()
{
var first2 = document.getElementById("firstname").value;
}
</script>
Then you have to fire it up when the input changes with onchange:
FirstName: <input type="text" id="firstname" name="firstname" onchange="XX()">
i m trying to get a list of outputs which doesn't divide evenly by number which are smaller than the input value.For example if the input value is 10,the list should be 10,9,8,7,6,4,3,1. below is my code and doesn't give me any output nor any error message.I m new to javascript and i need to know what i m doing wrong.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>An example of using "for" and "while" in PHP</title>
<script type="text/javascript">
function displayResult()
{
if(text_form.numberfield.value){
var number=document.getElementsByName("numberfield").value;
var div=document.getElementsByName("numberfield").value;
while (div>0)
{
if(number%div==0 && div!=number && div!=1)
{
div--;
continue;
}
if (div == 0)
{
break;
}
document.write(div--);
document.write(",");
}
}
else
{
document.write("Enter a number");
}
}
</script>
</head>
<body>
<H1>An example of using "for" and "while" in PHP</H1>
<form name="text_form">
Please input a number: <input type="text" name="numberfield"> </label>
<input type="submit" value="Submit" onclick="displayResult()" />
</form>
<p> Result is shown as below.</p>
</body>
</HTML>
getElementsByName returns an array, not an element.
Try:
var number=document.getElementsByName("numberfield")[0].value;
var div=document.getElementsByName("numberfield")[0].value;
Notice the [0]. You also have to modify a bit to make it work.
DEMO
the getElementsByName returns a list of elements having the specified name not a single element. You can access each element using loop:
var elems=document.getElementsByName("name")
for(var i=0;i<elems.length;i++){
var elem=elems[i]
//access each element using iterator
}
Also the getElementsByTagName returns a list of elements having the specified tag name.