Cannot Read Property Split of Undefined for text input - javascript

I am trying to build a text to morse code translator, and when trying to take the input value which is a string and turn it into an array of letters, I get this error.
var inputValue = getInputValue();
var inputValueLetters = inputValue.split();
function getInputValue(){
// Selecting the input element and get its value
var inputVal = document.querySelector("#myInput").value;
// Displaying the value
console.log(inputVal);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Text Input Field Value in JavaScript</title>
</head>
<body>
<h1>Morsi: Translate Plain Text Into Morse Code</h1>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="getInputValue();">Get Value</button>
<script src="morsi.js"></script>
</body>
</html>

You called function "getInputValue" at first line of your script.
var inputValue = getInputValue();
This function return undefined, and then you are trying to call .split method of undefined and got that error.
If you remove first two lines of your script - you will got no error.
If you need some additional logic, and not just print input value to console, then you need to place this logic in function getInputValue after reading value of input. Like:
function getInputValue(){
// Selecting the input element and get its value
var inputVal = document.querySelector("#myInput").value;
// Displaying the value
console.log(inputVal);
const letters = inputVal.split('');
console.log(letters);
};
Also, check that i used empty string argument in split function to split value by letters. If you don't do it you will have array with only one element,that is whole input value

This line :
var inputValue = getInputValue();
Is assigning whatever the function getInputValue(); return to the variable inputValue
That function is return undefined which is basically nothing, because there's no return statement inside it, So the second line becomes like this:
var inputValueLetters = undefined.split();
The error you get Cannot read property 'split' of undefined" is clear enough undefined is nothing and nothing has nothing so how can you expect nothing to have split().
What you want is only when the button is clicked get the value of the input then call split() on that value.
Also if you want to split the text into an array of letters you need to tell the split function by which char it want it to split a space or a forward slash (/) etc..
In our case it's nothing so we pass an empty string ""
function getInputValue() {
// Selecting the input element and get its value
var inputValue = document.querySelector("#myInput").value;
var inputValueLetters = inputValue.split("");
// Displaying the value
console.log(inputValueLetters);
};
<h1>Morsi: Translate Plain Text Into Morse Code</h1>
<input type="text" placeholder="Type something..." id="myInput" value="text">
<button type="button" onclick="getInputValue();">Get Value</button>

You have to use .split('')
const hello = 'hello'
console.log(hello.split())
console.log(hello.split(''))

Related

How to read input box line by line in Javascript and return various values depending on input?

I am trying to create a function in Javascript which can read an input box line by line and return different values depending on the input.
For example, if someone enters several protein mutations on separate lines with the format Arg86Lys, I want the function to read the first three and last three letters to get Arg Lys. Then, if I have a value stored for Arg Lys (let's say 100), I want the output to be a textbox which prints out the value 100 (and prints out the rest of the values on separate lines).
I am stuck on how to read the input box value line by line, and only extract the first three and last three letters from each line. I also do not understand how I can store values (like Arg Lys = 100) and return said values when a certain input is found.
So far I have created a multiline textbox (in HTML) and tried to make a function that reads line by line:
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea rows = "5" cols = "60" name = "description">
</textarea><br>
<input type = "submit" value = "submit" />
</form>
<script>
var lines = document.getElementById('textareaId').innerHTML.split('\n');
for(var i = 0;i < lines.length;i++){
\\
}
</script>
</body>
textarea is an input, so its value is going to be stored in its value property, and passed along with the form submission. Here is an answer I found that goes over how to intercept the submit event for the form:
Intercept a form submit in JavaScript and prevent normal submission
Once you've intercepted the form submission event, pull the value from the description input, and do with it what you want from there
let form = document.getElementById("form");
let data = {"Arg Lys":100}; // store data like this
form.addEventListener("submit",function(e){
e.preventDefault();
var lines = document.getElementById('textareaId').value.split('\n');
document.getElementById('textareaId').value = '';
for(var i = 0;i < lines.length;i++){
let val = lines[i].substring(0,3);
let lastval = lines[i].substring(lines[i].length - 3)
document.getElementById('textareaId').value += val+' '+lastval + ' - ' +data[val+' '+lastval]+'\n';
}
})
<body>
<form id="form" action = "/cgi-bin/hello_get.cgi" method = "get">
Enter mutations on separate lines with format Arg86Lys
<br>
<textarea id="textareaId" rows = "5" cols = "60" name = "description"></textarea><br>
<input type = "submit" value = "submit" />
</form>
</body>
Are you looking for something like that?

In JS validation - trying to remove spaces from text-box, but getting undefined value

I want to remove leading and trailing spaces from the values provided in a text box. For that I am using JavaScript validation. In that I have declared two variables and when I tried to check the values assigned to these variables, I am getting undefined as value. Can you please let me know where I am wrong?
function trim(StringtoTrim){
StringtoTrim.replace(/^\s\s*/, '');
}
function validate()
{
alert("in validate ");
var value1 = myform.fname.value;
alert(value1.value);
var value2 = trim(value);
alert(value2.value);
if(value2.length != value1.length)
{
document.getElementById('errfn').innerHTML="please remove leading and trailing spaces ";
return false;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="myform" onsubmit="return validate();">
First_Name
<input type="text" name="fname"/><span id="errfn"></span>
<br> <br>
<input type="submit"/>
</form>
</body>
you are trying to get value of value
var value1 = myform.fname;
alert(value1.value);
and second value is not defined
var value2 = trim(value);
it should be value1 but still the script is more problems than that. See below
function validate()
{
alert("in validate ");
var value1 = myform.fname.value;
alert(value1);
var value2 = value1.trim();
alert(value2);
if(value2.length != value1.length)
{
document.getElementById('errfn').innerHTML="please remove leading and trailing spaces ";
return false;
}
}
Your own made trim function is broken, it leaves the trailing spaces.
String has a built in trim() function.
This removes all leading and trailing spaces but leaves the spaces inside the word.
" de mo ".trim()
Will result in:
"de mo"
In the validate function there are other problems, you try to access
in alert(value1.value) you try to access myform.fname.value.value which is invalid, this should be alert(value1)
var value2 = trim(value), here value is undefined and should be var value2 = trim(value1)

Not able to know whether values are being inserted or not

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>

Passing on a variable to a JS function from HTML

I'm currently working on a little programming task for school. I chose the task because I had an idea how to get the core of the program running in Java, but I'm having issues translating this into a very simple web page, no experience with HTML or JS.
My issue is: I'm receiving input via a button. When clicked, a function is called and that function gets the value of the input. However, all I get as the alert window is objectHTMLinputElement. What am I doing wrong?
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH() {
var risikoHoehe = parseInt(document.getElementById('input2')).value;
alert(input2);
}
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
Get the value of the input before parsing it. Plus, you are alerting an input element instead of the variable that you are setting the value to. Use:
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
Change this part parseInt(document.getElementById('input2')).value; as :
parseInt(document.getElementById('input2').value)
You're calling the wrong variable, try 'risikoHoehe' instead of 'input2':
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH(){
var risikoHoehe = document.getElementById('input2').value;
alert(risikoHoehe);
}
1) You are trying to parse a DOM element to an int so it returns undefined.
Use document.getElementById('input2').value.
2) Use parseInt only if needed, if its just for alerting then you can skip it
3) You cannot directly refer to an dom element by id, you have to get that element in a variable and then use it.
alert(input2); should be alert(risikoHoehe);
Well, Here is the complete working code-
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
alert(risikoTraeger);
}
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
</script>
</head>
<body>
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
</br>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
</body>
</html>
Hoping this will help you :)
Let's see what you are doing wrong:
var risikoHoehe = parseInt(document.getElementById('input2')).value;
document
document itself
getElementById()
the function which gives us the element that has the specific ID parameter
'input2'
the ID of the desired input
.value
the element's value if it has any.
parseInt()
the function that converts any string to it's integer value.
now look at here:
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
parseInt(objectHTMLInputElement) => what can we get if we try to convert the html input element to an integer?
(integer).value => does integers have value property?
But if you write it like this:
var risikoHoehe = parseInt(document.getElementById('input2').value);
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
objectHTMLInputElement.value => the value of the input as string
parseInt(string) => Parse the integer value of the string

Changing value of input text after button click using javascript's addeventlistener

I am trying to have the input text that was entered via a text field form change on button click using JavaScript. I'm having difficulty figuring out why it is not working. Any help would be appreciated.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> </title>
<script type="text/javascript">
function start(){
var button = document.getElementById("button");
button.addEventListener("click", buttonPressed, false);
}
function buttonPressed(){
var text = document.getElementById("textField").value;
text.value = "GMU";
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<form>
<input id="textField" type="text" value="">
<input id="button" type="button" value="Button">
</form>
</body>
</html>
The problem lies here:
var text = document.getElementById("textField").value;
text.value = "GMU";
Take a look at the lines above. You are getting the value of an element and storing it into text but you then try to assign text.value? Consider this situation:
Say that the input currently has a value of "Apples". Doing:
var text = document.getElementById("textField").value;
Will store "Apples" in text. Now you do:
text.value = "GMU";
Since text is a string, and you try to access property value which does not exist for strings, it doesn't work - you've access the value property one too many times.
Now - note that the variable stores the value not reference to the element's value, meaning that in your code above, text only holds the property value, it's not pointing to the actual element's value property. Thus you would need to directly modify the value property like so:
document.getElementById("textField").value = "GMU";
This works because you modify the property of the element itself, you don't copy it into a variable.
You can alternatively store the element into a variable, and do element.value = "val" because an element is an object, and objects have references that point to memory, so when you assign to an object, reference is assigned and it points to the same place in memory.
To change the input text on button click you can use addEventListener just on the button. Then you can change the input field after that.
var button = document.getElementById("button");
var text = document.getElementById("textField");
button.addEventListener('click', function() {
text.value = "GMU";
});
<form>
<input id="textField" type="text" value="">
<input id="button" type="button" value="Button">
</form>

Categories