Javascript check if input is a specific string - javascript

I have an HTML Input field and I need javascript to check if the input entered into this box is a certain string. Specifically, it has to be a specific Zip code, there are a total of 9 different zip codes, all which are different and in no numerical order. Once the code checks if it is that specific zip code, it returns "Yes", if not, simply no.
I know how to do this with ints, as shown in the code below, but not sure to how to do this with strings. This is my current code, which works with validating an integer between 1-10:
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

I think you are over-thinking this. You can just use the indexOf function to test your zip code array.
var btn= document.getElementById("btn");
var input = document.getElementById("numb");
var output = document.getElementById("demo");
var formArea = document.getElementById("formArea");
var zips = ["11111","22222","33333","44444","55555", "e1", "e2"];
btn.addEventListener("click", function() {
var result = null;
// indexOf() returns -1 when the supplied value isn't present
if(zips.indexOf(numb.value.toLowerCase()) > -1){
result = "yes";
// Show the form by removing the hidden class
formArea.classList.remove("hidden");
} else {
result = "no";
// Hide the form by adding the hidden class
formArea.classList.add("hidden");
}
output.textContent = result;
});
#formArea{
border:2px double grey;
width:50%;
box-shadow:2px 2px 0 #303030;
height:100px;
padding:5px;
}
.hidden {
display:none;
}
<input id="numb">
<button type="button" id="btn">Submit</button>
<p id="demo"></p>
<div id="formArea" class="hidden ">
Your form goes here
</div>

Can you use a regular expression for postal codes? Note this accounts for a set of zip codes that are in string format, but you are welcome to create a zip-code regex that can satisfy the set of zip codes you are interested in. And furthermore, if the set is small enough you can probably just enumerate them in a list/set and check if the set contains the input.
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (!isValidZip.test(x)) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

convert it to a number
x = Number(document.getElementById("numb").value);

Related

How to check for a number in a textbox using javascript HTML?

I need to check if the value input in a HTML textbox contains a number, this is what I'm using so far, but it's not working, can anyone help? The text box would be a mix of letters and numbers, but I want to check if there are any numbers at all.
<input id="input" type="text">
<button onclick="myFunction()">Submit</button>
<p id="HasNumber"></p>
<script>
function myFunction() {
if (document.getElementById("input").value >= '0' && value <= '9' {
HasNumber.innerText = "Has Numbers" ; }
else {
HasNumber.innerText = "No Numbers" ; }
}
</script>
You can check if input contain number by using Regex like Below Example:
<input id="input" type="text">
<button onclick="myFunction()">Submit</button>
<p id="HasNumber"></p>
<script>
function myFunction() {
const inputVal = document.getElementById("input").value;
let matchPattern = inputVal.match(/\d+/g);
if (matchPattern != null) {
HasNumber.innerText = "Has Numbers" ;
} else {
HasNumber.innerText = "No Numbers" ;
}
}
</script>

how to update value in textarea after clicking a button?

I'm practicing JavaScript creating a convert case where I have a textarea where the initial text is informed and the second where the converted result should be output, I created a function to invert the text but when I click on the button that calls this function it doesn't convert if there is already a typed text.
How do I get it to update the values ​​when I click on the button?
function reverseText(){
function reverse(s){
var word = '';
for (var i = s.length - 1; i >= 0; i--)
word += s[i];
return word;
}
$('#input1').keyup(function(){
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="convert-case">
<textarea id='input1'></textarea>
<textarea id='input2' readonly></textarea>
</div>
<div class="function-button">
<button onclick="reverseText()">reverse text</button>
</div>
I want to create other conversion functions so I want the value the user has already typed to be converted as soon as he clicks on one of the conversion options.
If I understand your question you want the button to directly convert the text. Right now you code is doing the reverse, but update the input only after user type a key.
You want to revert instantly on button click, and keep the update going
function reverseText(){
function reverse(s){
var word = '';
for (var i = s.length - 1; i >= 0; i--)
word += s[i];
return word;
}
function updateInput() {
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
}
$('#input1').keyup(updateInput);
updateInput();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="convert-case">
<textarea id='input1'></textarea>
<textarea id='input2' readonly></textarea>
</div>
<div class="function-button">
<button onclick="reverseText()">reverse text</button>
</div>
I don't really get what you want. If you want to get the value from input1, reverse the text and put it into input2 then just remove the first and last line of the code below
$('#input1').keyup(function(){
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
});

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

User input to make substring

In my program, I have three text fields. In one of them, you are supposed to fill in some text, and in the other two, you fill in two numbers. The text field with the words large number has to have a greater value than the text field with the words smaller number. However, the number has to be less than the length of the user-inputted text.
Whenever I run the program, the javascript console says it cannot read property of sub-string null.
Here are the relevant bits of my code.
<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!
<script type = "text/javascript">
var t = document.getElementById("t");
var s = document.getElementById("small");
var l = document.getElementById("large");
function sub_str() {
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((regex_num.test(s)) || (regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
</script>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>
Move DOM element selection into the function, and read its value.
Try this:
<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!
<script type = "text/javascript">
function sub_str() {
var t = document.getElementById("t").value;
var s = document.getElementById("small").value;
var l = document.getElementById("large").value;
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((!regex_num.test(s)) || (!regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
</script>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>
There are multiple issues. You are not using .value on your elements to get value and then there is always the chance that your code gets executed before the DOM is loaded. So put your processing inside process() and then use
<body onload="process()">
to invoke this function after the document is loaded.
<script type = "text/javascript">
function process() {
function sub_str() {
var t = document.getElementById("t").value;
var s = document.getElementById("small").value;
var l = document.getElementById("large").value;
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((regex_num.test(s)) || (regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
substr(); // Call the function here
}
</script>
Use the inputs' values, not the inputs themselves
You are interested in what the user typed in your input (that is the input's value), not the input it self. You can get the value of an input by using the input.value property.
Make sure the DOM is loaded when your script is executed
Make sure your DOM is loaded before doing any operation on it (such as getElementById). You should put your script tag at the end of the <body> or wrap your code in an onload handler.
Compare numbers, not strings
Also, when you are doing number comparison, make sure you are actually comparing number and not strings. In JavaScript, "5" > "30" is true (yep...). An input's value is a string. If you want proper number comparison, you must parse the values first (e.g. using parseInt).
console.log('"5" > "30":', "5" > "30");
console.log('5 > 30:', 5 > 30);
console.log('parseInt("5") > parseInt("30"):', parseInt("5") > parseInt("30"));
Fix your tests
The regexp test is wrong (you show an alert when the values are a number instead of when they are not). Moreover, you could just check the result of parseInt instead of regular expression.
Look after your users
Finally, you may also consider using inputs of of type type="number" instead of type="text" for the "small number" and "large number" inputs. type="number" will restrict what can be entered directly in the input itself. It will avoid user errors and the frustration of an alert.
By default, type="number" also add some controls (i.e. 2 arrows to increment or decrement the entry).
Note that even if you set the type to "number", input.value will still be a string that needs to be parsed, but this time, this string will always represent a number.
Similarly, you may programatically and automatically update the "large number" when a user enters a "small number" that is bigger and vice-versa. One less possible error, one less annoying alert.
Your code fixed (without the UI suggestions):
var t = document.getElementById("t");
var s = document.getElementById("small");
var l = document.getElementById("large");
function sub_str() {
var tVal = t.value;
var sVal = parseInt(s.value, 10); // paseInt will return NaN if the string is not a number.
var lVal = parseInt(l.value, 10);
var short_str = tVal.substr(sVal,lVal);
if (lVal<sVal) {
window.alert("Please enter a number larger than the smaller number!");
}
// Typo here, you want to test if the values are *not* a number.
else if (isNaN(sVal) || isNaN(lVal)){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!</p>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>

Character Counter for multiple text areas

I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>

Categories

Resources