Not working, Javascript validating text input before button click - javascript

The code is suppose to validate an input and then execute a function when a button is clicked, but it is not working and the console does not suggest why. The only difference is that when you take away toString() on input it says it is not a function.
This is my first big project at university and not really sure which part is wrong?
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
const trimmed = input.toString().trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}
Function to be executed
function addRow() {
something...
}
validating if this function is true then execute this function.
function validate(){
if(check()){
addRow();
}
}
document.getElementById('input').addEventListener('input', check);
document.getElementById('btn').addEventListener('click', validate);
Html
<input type="text" id="input" class="input" autofocus autocomplete="off" placeholder="Add items in your list..">
<button id='btn' class="add">+</button>

Although the input variable is not declared in your code, I assume that it is supposed to represent the <input type="text"> element.
With the validation step you should validate the value of the input, not the input itself.
But your logic is still missing something. The else statement will never be reached. If the value is empty then the state will be set to '' and the function is stopped. If there is a value, and it has been trimmed, then you're always left with a string with a value in it and there for your value is truthy. So the else would not make without an if statement which would allow the value to be false when the validation is incorrect.
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
// Trim the value.
const trimmed = value.trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

How can I tell if an <input type=number> is blank vs. has an invalid value?

If a user types an invalid value (ex: "1.2.3") into an <input type=number>, then Chrome and Firefox report the <input>'s value property as "" rather than "1.2.3".
So, how do I tell if the user typed in an invalid number into the <input> or just left it blank?
I tried using the valueAsNumber property but it's NaN in both cases.
function showInputValue() {
const inputValue = document.getElementById("numberInput").value;
const inputValueAsNumber = document.getElementById("numberInput").valueAsNumber;
console.log(`value is: "${inputValue}"\nvalueAsNumber is: "${inputValueAsNumber}"`);
}
document.getElementById("btn").addEventListener("click", showInputValue)
<input type="number" id="numberInput" placeholder="try entering text"/>
<button id="btn">Show value</button>
Your input element has the validity property implementing the ValidityState interface:
ValidityState {
badInput: true,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: false,
valueMissing: false
}
From here you can study all validity states (valueMissing, badInput, etc...)
You can get a reference to your input using document.querySelector.
In your case the empty input will set the valueMissing flag, and the "1.2.3" input will set the badInput flag.
According to the answer to this question, you won't be able to get the value of an input field of type number unless it's a valid numeric input.
On the other hand, you can make the input field of type text instead and validate it with the help of regex like this:
window.onload = ()=>{
let numBox = document.getElementById('number-box');
let button = document.getElementById('show-value');
let pattern = /^\d*(\.\d+)?$/;
numBox.addEventListener('input', function(){
if(pattern.test(this.value) && this.value !== ''){
console.log('valid');
}
else {
console.log('invalid!');
}
});
button.addEventListener('click', ()=>{
alert(`The current value in the input field is ${numBox.value}`);
});
};
<input type="text" id="number-box">
<input type="button" id="show-value" value="Show Value">
Also, here's a working example :)
You can use jquery $.isNumeric() function for numeric validation like the following.
function showInputValue() {
const inputValue = document.getElementById("numberInput").value;
//const inputValueAsNumber =
//document.getElementById("numberInput").valueAsNumber;
if(inputValue !== '' && $.isNumeric(inputValue))
{
alert("number is ok");
}
else if(inputValue == '')
{
alert("input is empty");
}
else {
alert("Number is invalid");
}
}

AngularJS: Return function based on input type

I have an input box in my HTML file. If the user inputs a number I would like to return getZip() and if the user inputs a string I would like to return getCity(). Is this possible to do with a single input box or would I need to have one designated for type="text" and one designated for type="number"?
view.html:
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="getData()">
<input type="search" ng-model="location">
<button>Get Weather</button>
</form>
myApp.js:
1st attempt:
$scope.getData = function() {
switch (angular.isString($scope.location)) {
case true:
return $scope.getCity();
break;
case false:
return $scope.getZip();
break;
default:
return "Location not recognized";
};
};
2nd attempt:
$scope.getData = function () {
if (angular.isString($scope.location)) {
return $scope.getCity()
} else {
return $scope.getZip()
};
It seems like even if the input is a number, once it is passed through the scope, it is a string no matter what. Is there a way around this? Thanks in advance!
You should check whether or not your input is a number, since all input would be of type string initially:
if (!isNaN($scope.location)) {
return $scope.getZip()
}
else {
return $scope.getCity()
}
If you're trying to compare the input to a numeric value, you should parse it to int:
if( !isNaN($scope.location) && parseInt($scope.location) == 1123) {
alert('yes');
}
isNaN() return true if the input is NOT a number, that's why I added ! to the condition
try the other way, start with angular.isNumber a string number should return true but a string with letters should return false

Passing an id through a function parameter

Trying to get a value of a textbox by passing the ID into a function parameter. Should be easy but can't wrap my head around it.
JavaScript:
function checkfield(id)
{
var field = document.getElementById(id);
if (isNaN(field) == true)
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(textbox);
field.select(textbox);
return false;
}
return true;
}
HTML:
<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>
Error Message
Error: Unable to get property 'value' of undefined or null reference
Your ID is 19, but you're passing numberbox19 to the Javascript function. There are also several syntax errors.
Try:
<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>
And Javascript:
function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
alert(field.value);
if (isNaN(field.value)) // check the value, not the field itself!
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(); // not "field.focus(textbox);"
return false;
}
return true;
}
The good thing here is, if you ever decide to change the ID for any reason, you only have to change it in one place instead of two.
the id of your input is "19" not "numberbox19"

Checking the text input before triggering event in JavaScript

I am trying to create a text-based adventure game. I managed to figure out how to make text output in html's textarea through simple onclick button, but now I am trying to do something new. I am having trouble with doing same thing but with input text where users can write anything in the box and then click on the button. Right now, I am trying to make this program to check the user input against some flag (in this case, I set my flag equal to 'pizza') before it does something. Unfortunately, my code doesn't work at all. I think I don't completely understand how the input is being passed around in JavaScript's functions.
The JavaScript part:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
if (fileName == "pizza") {
var obj=document.getElementById(test);
obj.value="is this showing up in the textarea???";
}
else {obj.value="wrong password!"; }
}
The html part:
<input name="filename" id="filename" type="text">
<a id="record_button" onclick="record('textarea1');" href="javascript:void(0);" title="Record">Perform Action</a>
<textarea wrap="virtual" cols="73" rows="10" id="textarea1"></textarea>
The problem is this block with your else statement, obj isn't declared. Because you have obj defined in the if statement above it is exclusive to that scope. Just define obj right above the if block.
--
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj=document.getElementById(test);
if (fileName == "pizza") {
obj.value="is this showing up in the textarea???";
}
else {
obj.value="wrong password!";
}
}
Add an event listener using JS:
document.getElementById('record_button').onclick=function(){
record('textarea1');
}
Also, there were a couple things wrong with your function. Here it is with corrections:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj = document.getElementById(test);
if (fileName == "pizza") {
obj.value = "is this showing up in the textarea???";
}
else {
obj.value = "wrong password!";
}
}
You were using document.getElementByID on the second line, which is incorrect capitalisation
You were only defining obj conditionally, so the else clause always threw an exception.
Here is a demonstration: http://jsfiddle.net/uQpp7/1/

Categories

Resources