Match string case sensitive value with array - javascript

Here is my code!!!
I have one input field And
One of the array
I'm matching Input field entered value with arrray's list.
Prob : Unable to match capital value with array's list.
e.g if user enter one10 value so this one should be match or if user enter ONE10 in capital letter then this value should be match too.
function myFunctiontwo(){
var good = [
"one10",
"two10",
"three10"
];
var a = document.getElementById("code").value.split(' ');
var foundPresent = a.some(elem => good.indexOf(elem) > -1);
if(foundPresent === true){
alert("correct");
}else {
alert("wrong");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="code" id="code" placeholder="code" required>
<button id="submit" id="sumbit" onclick="myFunctiontwo()">GO</button>
</body>
</html>

You can use the toLowerCase() method here. Assuming all your elements in good are lowercase you can just do elem.toLowerCase()
var foundPresent = a.some(elem => good.indexOf(elem.toLowerCase()) > -1);
When not you also should convert the array elements toLowerCase()
good = good.map(x => x.toLowerCase());
In the snippet below I added the element "FOur20" to the array.
As you can see four20 will give you the message correct
function myFunctiontwo(){
var good = [
"one10",
"two10",
"three10",
"FOur20"
];
good = good.map(x => x.toLowerCase());
console.log(good);
var a = document.getElementById("code").value.split(' ');
var foundPresent = a.some(elem => good.indexOf(elem.toLowerCase()) > -1);
if(foundPresent === true){
alert("correct");
}else {
alert("wrong");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="code" id="code" placeholder="code" required>
<button id="submit" id="sumbit" onclick="myFunctiontwo()">GO</button>
</body>
</html>

Let's first make sure the good array is all lowercase:
good = good.map(word => word.toLowerCase());
Then, you can always convert to lowercase and check if it exists in the good array
var foundPresent = a.some(elem => good.contains(elem.toLowerCase()));
if(foundPresent === true) {
alert("correct");
}
else {
alert("wrong");
}

Related

How can i call a different functions seperately using a single button

I have to create a calculator but i have to use separate functions for add , subtract , division and multiply
there should be an equal to (=) button which upon clicking should display the result
operators should be selected using the dropdown box
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>calculator</title>
</head>
<body>
<h1 align="center">calculator</h1>
<script type="text/javascript">
function add()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a+b
document.getElementById("answer").innerHTML=c;
}
function sub()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a-b;
document.getElementById("answer").innerHTML=c;
}
function mul()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a*b;
document.getElementById("answer").innerHTML=c;
}
function div()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a/b;
document.getElementById("answer").innerHTML=c;
}
</script>
<p>First Number: <input id="firstnumber"></p>
<p>Second Number: <input id="secondnumber"></p>
<select id="operators">
<option value="add" onclick="add()">+</option>
<option value="sub" onclick="sub()">-</option>
<option value="mul" onclick="mul()">*</option>
<option value="div" onclick="div()">/</option>
</select>
<button onclick="add.call(this);sub.call(this);mul.call(this);div.call(this);">=</button>
<p id="answer"></p>
</body>
</html>
i think thats what you were looking for.
make sure to read what i wrote under the code
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>calculator</title>
</head>
<body>
<h1 align="center">calculator</h1>
<p>First Number: <input id="firstnumber" /></p>
<p>Second Number: <input id="secondnumber" /></p>
<select id="operators">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
<button id="calcBtn">=</button>
<p id="answer"></p>
<script src="script.js"></script>
</body>
</html>
script.js:
document.getElementById("calcBtn").addEventListener("click", () => {
let operator = document.getElementById("operators").value;
let a = parseInt(document.getElementById("firstnumber").value);
let b = parseInt(document.getElementById("secondnumber").value);
switch (operator) {
case "add":
add();
break;
case "sub":
sub();
break;
case "mul":
mul();
break;
case "div":
div();
break;
default:
break;
}
function add() {
let c = a + b;
document.getElementById("answer").innerHTML = c;
}
function sub() {
let c = a - b;
document.getElementById("answer").innerHTML = c;
}
function mul() {
let c = a * b;
document.getElementById("answer").innerHTML = c;
}
function div() {
let c = a / b;
document.getElementById("answer").innerHTML = c;
}
});
dont use onclick, give element an id and then add event listenner to it works the same but addeventlistenner is better you can replace .addEventListener("click", () => { with .addEventListener("click", function() {
its up to you
always place your script tag directly above the body tag
use script src instead of script > code, it makes the html more clean
use let instead of var
switch case its like if, but in situations like that better, because its easier to write what to do depending on the value
usage:
switch(variable){
case "variable value":
code
break;
}
i think thats all

How to create multiple inputs from single input and get their values in javascript?

I have an idea to create multiple inputs from single input and get their all values. But I can only get the first input value but not the rest. Can someone tell me how to do it?
const singleInput = document.getElementById('singleInput')
const demo = document.getElementById('demo')
const demo2 = document.getElementById('demo2')
const multipleInputValue = []
singleInput.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
demo2.innerHTML += singleInput.value + '<input
type="number"
class="multipleInput" onkeyup="getValue(event)">' +
'<br>'
multipleInput =
document.getElementsByClassName('multipleInput')
}
})
function getValue(event) {
if (event.key == 'Enter') {
multipleInputValue.push(multipleInput[0].value)
}
}
And here's the HTML Code for this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Coding</title>
</head>
<body>
<input type="text" id="singleInput">
<div id="demo">
<p id="demo2"></p>
</div>
<script src="script.js"></script>
</body>
</html>
Your getValue function (bound to onkeyup event of the input appended at runtime) was trying to get the value of the input with multipleInput[0].value but no piece of code was pushing values to that array.
A better approach was to just using event.target to retrieve the object firing the event from the event handler itself.
I showed here a simplified demo of your code showing that concept.
When you press enter on the first input, the second one will appear.. after then if you press keys inside that new input, a console.log will show the activity, including when you'll press enter (and the value will be pushed to the array).
But the overall logic wasn't pretty clear so I couldn't go any further
const multipleInput = [];
const singleInput = document.getElementById('singleInput');
singleInput.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
console.log('singleInput: pressed ENTER');
const inputElement = event.target;
const target = document.getElementById('target');
target.innerHTML +=
inputElement.value +
'<input type="number" class="multipleInput" onkeyup="getValue(event)"><br>';
}
});
function getValue(event) {
console.log(`Key was pressed for the new created input: ${event.key}`);
if (event.key == 'Enter') {
console.log(`The value pushed to the array is: ${event.target.value}`);
multipleInput.push(event.target.value)
}
}
.multipleInput{
margin-bottom: 1rem;
margin-left: 1rem;
}
#singleInput{
margin-bottom: 2rem;
}
<input type="text" id="singleInput">
<div id="target">
</div>

How to get latest inputs by pressing the up arrow (Javascript)

How can i get the latest inputs I entered in order. For example:
I declared an array with 20 elements and when I input something I delete the first element of the array and add at the end the input I just entered.
So when I press the upArrow button the last element of the array will appear as the new input. If I press one more time the upArrow I want my input to change to my second last element and so on.
It doesn't work in my jsfiddle link. It outputs another element from the array.
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20);
latestInputs.fill("Latest");
function clickMe(){
singleValues = $( "#input" ).val();
var c = latestInputs.shift();
latestInputs.push(singleValues);
$( "#output" ).append( singleValues);
$("#input").prop('value', '');
}
$(document).on('keypress',function(e) {
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', latestInputs[theInputsNumber]);
theInputsNumber--;
}
});
if(e.which == 13) {
theInputsNumber=19;
clickMe();
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>
You've missed the idea that you must determine (logic test) the value of the counter (theInputsNumber) in order to reset at the top (and the bottom) of the stack.
I renamed theInputsNumber counter and provided the UP key and DOWN key feature. I also did not limit the array size to 20 as that won't make a difference anyway (array size is not restricted in size as it is in other languages).
EDIT (based on comment): I've placed everything within the HTML so you can save this content into an HTML file and open with your browser. It will work just fine with no server.
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
<script>
var counter = 0;
var latestInputs = [];
function clickMe() {
let input = $("#input").val();
latestInputs.push(input);
$("#input").prop('value', '');
}
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', previous());
} else if (e.which == 40) {
$("#input").prop('value', next());
} else if (e.which == 13) {
clickMe();
}
});
function previous() {
counter = (counter === 0) ? latestInputs.length - 1 : --counter;
return latestInputs[counter];
}
function next() {
counter = (counter === latestInputs.length - 1) ? 0 : ++counter ;
return latestInputs[counter];
}
</script>
</body>
</html>
it looks like your function on upArrow was triggered multiple times (3) every time you pressed that key, I moved it outside of the "keypress" binding and it stays on its own, and the problem no longer exists when i run the code
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20).fill("Latest");
function clickMe() {
singleValues = $("#input").val();
latestInputs.shift();
latestInputs.push(singleValues);
theInputsNumber = 19;
$("#output").append(singleValues);
$("#input").prop("value", "");
}
$(document).on("keypress", function (e) {
if (e.which === 13) {
clickMe();
}
});
$("#input").bind("keydown", function (e) {
var x = e.which || e.keyCode;
if (x === 38) {
$("#input").prop("value", latestInputs[theInputsNumber--]);
if (theInputsNumber === -1) {
theInputsNumber = 19;
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>

how to capitalize the 1st letter of input field text while typing by javasccript?

i want to know that when we type the name in input field type text. i want to get the input by user but while typing i want to capitalize the 1st letter that user enter. please help me
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form name="inputform">
Name: <input name="name" type="text" id="n" onKeyPress="check()">
</form>
<script>
function check()
{
var name=document.getElementById("n");
var uppercase=name.value.charAt(0);
}
</script>
</body>
</html>
As simple as it gets:
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}; // ^ First letter + The rest of the string.
Use it like this:
function check() {
var name = document.getElementById("n");
var uppercase = capitalizeFirstLetter(name.value);
name.value = uppercase;
}
Or, shorter:
<input name="name" type="text" id="n" onKeyUp="check(this)">
function check(element) {
element.value = capitalizeFirstLetter(element.value);
}
use this function in check method
like this
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
function check()
{
var name=document.getElementById("n");
var uppercase = capitalize(name)
}
You can use the Javascript function toUpperCase().
Here you have the code:
document.getElementById("n").addEventListener("keyup",checkinput);
function checkinput(){
var name=document.getElementById("n");
if(name.value.length==1){
var uppercase=name.value.charAt(0).toUpperCase();
name.value=uppercase;
}
}

I want to validate textarea,so that user canot enter words like phone number, email address or any url

I want to validate textarea,so that user cannot enter words like phone number, email address or any url .
If the user entered those values means how to identify those values by JavaScript
(or)
How can I stop the user from entering these words using JavaScript?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function validate()
{
var message=document.myForm.Name.value;
var phoneno = /^\d{10}$/;
if((message.value.match(phoneno))
{
alert("it has phone number");
return false;
}
else
{
return true;
}
}
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var EmailmatchArray = message.match(emailPat);
if (EmailmatchArray != null) {
alert("Text contains an email!");
return false;
}else{
return true;
}
var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
var isURL = message.match(Url);
if (isURL != null) {
alert("Contains a URL.");
return false;
}else{
return true;
}
</script>
</head>
<body>
<form name="myForm"
onsubmit="return(validate());">
<textarea rows="4" cols="50" name="send" id="send">
</textarea>
<input type="button" value="submit" />
</form>
</body>
</html>
this code not working
it's new code --here am not getting any error here but here no alert working
new code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function validate()
{
alert("ok");
var message=document.myForm.send.value;
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var phoneno = /^\d{10}$/;
var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
var EmailmatchArray = message.match(emailPat);
var isURL = message.match(Url);
if((message.value.match(phoneno)) && (EmailmatchArray != null)&& (isURL != null))
{
alert("it has phone number");
document.myForm.message.focus();
return false;
}
else{
return (true);
}
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return(validate());">
<textarea rows="4" cols="50" name="send" id="send">
</textarea>
<input type="button" value="submit" />
</form>
</body>
</html>
Looks like you are returning too early. In the first block you check if there's a phone number, and if there is not - you return that the form is valid - before you go on to check for email and URL.
In both new and old code the main error is in your HTML - you need input with type="submit", not type="button" to submit the form. Without that function pointed in onsubmit attribute of form is not called. And check syntax for pointing the function to be called in onsubmit attribute.
Fix this one and then debug the rest of code. You have to check all your brackets - both { } and ( ), as I see that you have some not-matching brackets in your old code. And you should not have return true; if the condition is not met, because the function will end in that place and another validations will never be checked.
If you'll still have problems post you can post your code on http://jsfiddle.net/ and update your question with link. It will make it easier for us to debug it online.

Categories