Unable to test the value of a number in external javascript file - javascript

I am trying to send a number from a user to an external javascript file ie .js and determine if it is less than or greater than another number
function processFormData() {
var name_element = document.getElementById('txt_name');
var x = name_element;
var x = Number(+x);
if (x > 10) {
alert("large number");
} else {
alert ("small number");
}
}
<script src="demo2.js"></script>
<p>
<label for="name">Your Name: </label>
<input type="number" name="name" id="txt_name">
</p>
</label>
<input type="button" name="submit" value="submit"
onclick="processFormData();" >

I think you are doing some pointless things here, first of all, why do you create two variables that points to the same object?
The second line is totally unnecessary. You are good to go with name_element.
var name_element = document.getElementById('txt_name');
var x = name_element;
And the solution to your problem is, you are trying to convert a DOM element to the number. Instead you should access to textContent first.
var numericalValue = Number(name_element.textContent);
// If you are expecting that input from a input box
// then you need to use name_element.value
if (x > 10) {
alert("large number");
} else {
alert ("small number");
}

Your code attempts to convert the text field itself into a number, rather than the value of the text field.
NOTES:
There's no need to set a variable up for the text field and then another to the first.
You have an extra </label> tag in your code.
The for attribute of a label must point to the id of some form
field, not the name attribute value.
Don't give elements a name or an id of name as this often
causes problems with the Global name property of the window
object.
function processFormData() {
var name_element = document.getElementById('txt_name');
// Convert the value of the element by prepending + to it
var x = +name_element.value;
if (x > 10) {
alert("large number");
} else {
alert ("small number");
}
}
<script src="demo2.js"></script>
<p>
<label for="txt_name">Your Name: </label>
<input type="number" name="txt_name" id="txt_name">
</p>
<input type="button" name="submit" value="submit" onclick="processFormData();">

Related

Why is if block executing and not the else block in javascript? [duplicate]

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
And this is my JavaScript code:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
How do I get the value from the text field into JavaScript?
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1
document.getElementById('textbox_id').value to get the value of
desired box
For example
document.getElementById("searchTxt").value;
 
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0],
for the second one use [1], and so on...
Method 2
Use
document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection
For example
document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.
Method 3
Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection
For example
document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.
Method 4
document.getElementsByName('name')[whole_number].value which also >returns a live NodeList
For example
document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.
Method 5
Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element
For example
document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name
Method 6
document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.
For example
document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name
Support
Browser
Method1
Method2
Method3
Method4
Method5/6
IE6
Y(Buggy)
N
Y
Y(Buggy)
N
IE7
Y(Buggy)
N
Y
Y(Buggy)
N
IE8
Y
N
Y
Y(Buggy)
Y
IE9
Y
Y
Y
Y(Buggy)
Y
IE10
Y
Y
Y
Y
Y
FF3.0
Y
Y
Y
Y
N IE=Internet Explorer
FF3.5/FF3.6
Y
Y
Y
Y
Y FF=Mozilla Firefox
FF4b1
Y
Y
Y
Y
Y GC=Google Chrome
GC4/GC5
Y
Y
Y
Y
Y Y=YES,N=NO
Safari4/Safari5
Y
Y
Y
Y
Y
Opera10.10/
Opera10.53/
Y
Y
Y
Y(Buggy)
Y
Opera10.60
Opera 12
Y
Y
Y
Y
Y
Useful links
To see the support of these methods with all the bugs including more details click here
Difference Between Static collections and Live collections click Here
Difference Between NodeList and HTMLCollection click Here
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
See this functioning in codepen.
I would create a variable to store the input like this:
var input = document.getElementById("input_id").value;
And then I would just use the variable to add the input value to the string.
= "Your string" + input;
You should be able to type:
var input = document.getElementById("searchTxt");
function searchURL() {
window.location = "http://www.myurl.com/search/" + input.value;
}
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
I'm sure there are better ways to do this, but this one seems to work across all browsers, and it requires minimal understanding of JavaScript to make, improve, and edit.
Also you can, call by tags names, like this: form_name.input_name.value;
So you will have the specific value of determined input in a specific form.
Short
You can read value by searchTxt.value
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
<script type="text/javascript">
function searchURL(){
console.log(searchTxt.value);
// window.location = "http://www.myurl.com/search/" + searchTxt.value;
}
</script>
<!-- SHORT ugly test code -->
<button class="search" onclick="searchURL()">Search</button>
<input type="text" onkeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value) {
window.open("http://www.google.com/search?output=search&q=" + value)
}
</script>
Tested in Chrome and Firefox:
Get value by element id:
<input type="text" maxlength="512" id="searchTxt" class="searchField"/>
<input type="button" value="Get Value" onclick="alert(searchTxt.value)">
Set value in form element:
<form name="calc" id="calculator">
<input type="text" name="input">
<input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>
https://jsfiddle.net/tuq79821/
Also have a look at a JavaScript calculator implementation.
From #bugwheels94: when using this method, be aware of this issue.
If your input is in a form and you want to get the value after submit you can do like:
<form onsubmit="submitLoginForm(event)">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<script type="text/javascript">
function submitLoginForm(event){
event.preventDefault();
console.log(event.target['name'].value);
console.log(event.target['password'].value);
}
</script>
Benefit of this way: Example your page have 2 form for input sender and receiver information.
If you don't use form for get value then
You can set two different id (or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
If you set the same value for two inputs, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later, if you change the order of 2 form in HTML, you need to check this code again
If you use form, then you can use name, address, ...
You can use onkeyup when you have more than one input field. Suppose you have four or input. Then
document.getElementById('something').value is annoying. We need to write four lines to fetch the value of an input field.
So, you can create a function that store value in object on keyup or keydown event.
Example:
<div class="container">
<div>
<label for="">Name</label>
<input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Age</label>
<input type="number" name="age" id="age" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Email</label>
<input type="text" name="email" id="email" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Mobile</label>
<input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
</div>
<div>
<button onclick=submitData()>Submit</button>
</div>
</div>
JavaScript:
<script>
const data = { };
function handleInput(e){
data[e.name] = e.value;
}
function submitData(){
console.log(data.fname); // Get the first name from the object
console.log(data); // return object
}
</script>
function handleValueChange() {
var y = document.getElementById('textbox_id').value;
var x = document.getElementById('result');
x.innerHTML = y;
}
function changeTextarea() {
var a = document.getElementById('text-area').value;
var b = document.getElementById('text-area-result');
b.innerHTML = a;
}
input {
padding: 5px;
}
p {
white-space: pre;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
<input id="new" >
<button onselect="myFunction()">it</button>
<script>
function myFunction() {
document.getElementById("new").value = "a";
}
</script>
One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:
var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;
Source: w3schools
function searchURL() {
window.location = 'http://www.myurl.com/search/' + searchTxt.value
}
So basically searchTxt.value will return the value of the input field with id='searchTxt'.
Short Answer
You can get the value of text input field using JavaScript with this code: input_text_value = console.log(document.getElementById("searchTxt").value)
More info
textObject has a property of value you can set and get this property.
To set you can assign a new value:
document.getElementById("searchTxt").value = "new value"
Simple JavaScript:
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
}

Outputs not showing in simple odd/even code

I've just started beginning to code in JavaScript (my first attempt at any so please be patient!), so have just set myself a simple project just to create a input box, and was hoping upon clicking the calculate button to generate a "Even" or "Odd" output that shows up below the box. But somehow I can't get anything to show up. Any ideas what I'm doing wrong?
function myFunction() {
// define var num
var num = document.getElementById("number").value;
//use of if function as number is odd or even (modulo = 0 or 1)
if (num % 2 === 0) {
document.writeIn("Even");
} else {
document.writeIn("Odd");
}
}
<table id="number">
Number: <input type="number" name="name">
<input type="button" onclick="myFunction()" value="Calculate"></table>
You need to take an input with type 'text' and an id of 'number'.
Then get this value of the input and assign to another element the result, because document.writeln does not work after the page is rendered by the user agent.
function myFunction() {
var num = document.getElementById("number").value;
document.getElementById("type").innerHTML = num % 2 ? "Odd": "Even";
}
Number: <input type="text" id="number">
<input type="button" onclick="myFunction()" value="Calculate">
<div id="type"></div>

Append number in textbox on submit

I want to add two zeros to any number entered in a textbox when submitted.
For instance, if i enter 34 in a textbox and click on submit, it should be saved as 3400.
Could this be done on the fly too?
Depends on what you want to do after the submit. Especially: Do you want to interpret this as a number and simply multiply by 100 (34 * 100) or do you want to simply append something to the value? ("34" + "00")?
In the first case you would do this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = parseInt(input.value) * 100;
}
</script>
In the second case this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = input.value.toString() + '00';
}
</script>
A bit vague, but it sounds like you're looking for something like the following.
// Gather each element from the HTML, so you can access its input or update its display:
const input = document.getElementById('numberInput');
const button = document.getElementById('submit');
const display1 = document.getElementById('display1');
const display2 = document.getElementById('display2');
// Add a click event to the button, which gathers the text field value, ensures it's a number, and updates the display as requested:
button.addEventListener('click',() => {
const value = input.value;
// This if statement ensures that only numbers will be suffixed with be suffixed with two zeros:
if (isNaN(value)) {
alert('Please enter a valid number');
return;
}
// Update the display span's contents as requested. There are many ways of doing this. Here are a few;
// Here I'm taking the submitted value, and nesting it inside a string, alongside the two zeros. In cases of Infinity or .100, the result will still be the input suffixed with two zeros:
display1.innerHTML = `${value}00`;
// This method, on the other hand, will simply move the decimal to columns:
display2.innerHTML = value * 100;
});
<p>
Display 1: <span id="display1"></span>
</p>
<p>
Display 2: <span id="display2"></span>
</p>
<input type="text" id="numberInput">
<button id="submit">Submit</button>
You could always set an event listener that changes the number on exit of the form element, so something like this:
document.addEventListener('DOMContentLoaded', watchNums);
function watchNums() {
document.removeEventListener('DOMContentLoaded', watchNums);
Array.from(document.getElementsByClassName('number')).map(
number => {
number.addEventListener('blur', _ => {
number.value = parseInt(number.value) * 100;
})
}
)
}
<body>
<form action="/endpoint.htm" method="POST">
<input type="number" name="number-input" class="number">
<input type="number" name="other-number-input" class="number">
<button type="submit">Submit Numbers</button>
</form>
</body>

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>

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

Categories