Converting input to lowercase - javascript

not a coder at all, making a little project. Does anyone know how I can make my input here case insensitive? I have tried to add a line similar to
name = name.map(function(x){ return x.toLowerCase() })
but this didn't work and with no coding background I'm finding it hard to troubleshoot what is going wrong.
Thank you :)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
return x.toLowerCase()
})
$('#check').click(function() {
var name = $('#name').val();
if (jQuery.inArray(name, names) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
</script>
</body>
</html>

To have case insensitivity you need to have both the values in same case, whereas you're just changing value of names to lowerCase but not the value of name toLowerCase.
So just change both the values to same case and than match
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
return x.toLowerCase()
})
$('#check').click(function() {
var name = $('#name').val().toLowerCase(); // notice to lowercase here
if (jQuery.inArray(name, names) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
</script>
</body>
</html>

You can convert the input to lowercase using toLowerCase() and then check if is present in array or not . i.e :
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
var a= x.toLowerCase()
console.log(a);
$('#check').click(function() {
var name = $('#name').val().toLowerCase();
if (jQuery.inArray(name, a) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>

Take the text in variable, then pass it with toLowerCase() function.
var str = "Hello World!";
var res = str.toLowerCase();

var strring = "Convert String to Lower";
var result = str.toLowerCase();

Related

I have an if else statement that I dont know how to make the else part relevent

const newInput = document.querySelector('input');
const h1 = document.querySelector('h1');
newInput.addEventListener('change', function(){
if (newInput != ''){
h1.innerText = 'Welcome ' + newInput.value
} else {
h1.innerText = 'Enter Your Username';
}
});
<head>
<title>Input Event</title>
<!--LEAVE THESE LINES ALONE, PLEASE! THEY MAKE THE LIVE PREVIEW WORK!-->
<!-- <script src="node_modules/babel-polyfill/dist/polyfill.js" type="text/javascript"> </script> -->
<!-- <script src="https://unpkg.com/#babel/standalone/babel.min.js"></script> -->
</head>
<body>
<h1>Enter Your Username</h1>
<input type="text" id="username">
<script src="InputEvent.js"></script>
</body>
</html>
My if else statement appears to be ignored unless I change it to (if (newInput === 'a value' ) at which point it stops the function.
I don't understand why I can make the if statement relevant but it wont continue to the else part of the code.
Can anyone shed some light?
You need to use the .value property for newInput.value. newInput is a DOM node and you need to check if the value is empty.
const newInput = document.querySelector('input');
const h1 = document.querySelector('h1');
newInput.addEventListener('change', function() {
if (newInput.value !== '') {
h1.innerText = 'Welcome ' + newInput.value
} else {
h1.innerText = 'Enter Your Username';
}
});
<head>
<title>Input Event</title>
</head>
<body>
<h1>Enter Your Username</h1>
<input type="text" id="username">
<script src="InputEvent.js"></script>
</body>
</html>
The problem is that you are not accessing the value correctly. You either need newInput.value or event.target.value to get the value of the input. Working example of the specified problem https://codesandbox.io/s/clever-forest-18vme?file=/InputEvent.js:287-328

Page refreshes after I hit the button

It's a simple counting vowels page. When I insert a word WITH vowels, the result shows up for a second and then page refreshes. When there are no vowels, the output is not as expected and then the page refreshes again. Could anyone help me out please?
function findVow(event) {
event.preventDefault();
var input, result;
// Get value of the input
input = document.getElementById('text').value;
var regex = /[aeiou]/gi;
//unify the case and get the length
var count = input.match(regex).length;
if (count > 0) {
result = "Vowels found : " + count;
} else {
result = "No vowels found";
}
//print the number of vowels if any
document.getElementById("demo").innerHTML = result;
};
<!DOCTYPE html>
<html>
<head>
<title>challenge1</title>
</head>
<body>
<form>
<input id="text" placeholder="Enter a word" type="text" />
<br><br>
<button onclick="findVow()">Count vowels</button>
<br>
<p id="demo"></p>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
You are submitting the form when using default buttons.
The event you wanted is not passed as you expect - it is the button that is passed.
EITHER use type=button OR better: use event.preventDefault as now, but on the submit event
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
var input, result;
// Get value of the input
input = document.getElementById('text').value;
var regex = /[aeiou]/gi;
//unify the case and get the length
var count = input.match(regex).length;
if (count > 0) {
result = "Vowels found : " + count;
} else {
result = "No vowels found";
}
//print the number of vowels if any
document.getElementById("demo").innerHTML = result;
});
<form id="myForm">
<input id="text" placeholder="Enter a word" type="text" />
<br><br>
<button>Count vowels</button>
<br>
</form>
<p id="demo"></p>
add type='button' to the button in the form
<button onclick="findVow()" type='button'>Count vowels</button>
Add type="button" to the button and if you want to capture button event you can do it like this:
$('btnClick').on('click',function(event){
event.preventDefault();
var input, result;
// Get value of the input
input = document.getElementById('text').value;
var regex = /[aeiou]/gi;
//unify the case and get the length
var count = input.match(regex).length;
if (count > 0) {
result = "Vowels found : " + count;
} else {
result = "No vowels found";
}
//print the number of vowels if any
document.getElementById("demo").innerHTML = result;
});
<!DOCTYPE html>
<html>
<head>
<title>challenge1</title>
</head>
<body>
<form>
<input id="text" placeholder="Enter a word" type="text" />
<br><br>
<button class="btnClick" type="button" >Count vowels</button>
<br>
<p id="demo"></p>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Displaying an invalid output in JavaScript [duplicate]

This question already has answers here:
Switch Statement, it does not work with prompt
(3 answers)
Closed 2 years ago.
I did the below code. But the final answer doesn't come. it always shows up as "invalid input". Can i know the reason for it ? :) is it something wrong with my switch statement? Thank you so much. Have a nice day and stay safe!
<html>
<head>
<script language="JavaScript" type="text/javascript">
function link()
{
var r=prompt("Enter the operation:"+'\n'+"1-addition 2-sub 3-div 4- mul");
if(r>4)
{
alert("invalid input");
}
else {
var n1=prompt("1st number:");
var n2=prompt("2nd number:");
a=n1+n2;
s=n1-n2;
d=n1/n2;
m=n1*n2;
switch(r)
{
case 1:document.write("Addition answer = "+a);break;
case 2:document.write("Substraction answer = "+s);break;
case 3:document.write("Division answer = "+d);break;
case 4:document.write("Multiplication answer = "+m);break;
default:document.write("invalid Input");
}
} }
</script>
</head>
<body>
<script language="JavaScript" type="text/JavaScript" >
</script>
<input type="button" value="maths" onclick=link()>
<script src="java.js"></script>
</body>
</html>
Prompt gives you a string back you should use parseInt
<html>
<head>
<script language="JavaScript" type="text/javascript">
function link()
{
var r=prompt("Enter the operation:"+'\n'+"1-addition 2-sub 3-div 4- mul");
r = parseInt(r);
if(r>4)
{
alert("invalid input");
}
else {
var n1=prompt("1st number:");
var n2=prompt("2nd number:");
let x = parseInt(n1)
let y = parseInt(n2)
a=x+y;
s=x-y;
d=x/y;
m=x*y;
switch(r)
{
case 1:document.write("Addition answer = "+a);break;
case 2:document.write("Substraction answer = "+s);break;
case 3:document.write("Division answer = "+d);break;
case 4:document.write("Multiplication answer = "+m);break;
default:document.write("invalid Input");
}
} }
</script>
</head>
<body>
<script language="JavaScript" type="text/JavaScript" >
</script>
<input type="button" value="maths" onclick=link()>
<script src="java.js"></script>
</body>
</html>
Convert string to integer. Try with the below code.
function link()
{
var r=parseInt(prompt("Enter the operation:"+'\n'+"1-addition 2-sub 3-div 4- mul"));
if(r>4)
{
alert("invalid input");
}
else {
var n1=parseInt(prompt("1st number:"));
var n2=parseInt(prompt("2nd number:"));
a=n1+n2;
s=n1-n2;
d=n1/n2;
m=n1*n2;
switch(r)
{
case 1:document.write("Addition answer = "+a);break;
case 2:document.write("Substraction answer = "+s);break;
case 3:document.write("Division answer = "+d);break;
case 4:document.write("Multiplication answer = "+m);break;
default:document.write("invalid Input22");
}
} }
<input type="button" value="maths" onclick=link()>

Censoring / Highlighting using JavaScript

I'm trying to create a small sample application for highlighting / censoring of a textarea using JavaScript. To start with I'm just trying to replace the letters, though once that is solved my plan was to use mark.js to mark censored words. Right now when I run my application I'm getting Uncaught TypeError: Cannot Read property 'value' of null on line 21.
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('comments');
var badWords = ["x", "y", "z"];
var censored = censore(commentContent.value, badWords);
}
function censore(string, filters) {
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea id="pesho" name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('pesho');
var badWords = ["crap", "fuck", "cunt"];
console.log(commentContent.value)
commentContent.value =censore(commentContent.value, badWords);
}
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
As some of the other guys before me mentioned, you were not targeting the id of the text area but the name attribute, beside that for the function to make actual changes on the view you must change the targeted element value (see the modified example)

How to report length of string entered by user

Ok, so here's my script...I can't get it to output the length of the string though! Please help, I'm a complete noob when it comes to Javascript, this is for a college class. Thanks!
<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
/*
Purpose of script: report length of string given by user
*/
"use strict";
function stringLength()
{
var str=(document.StringLength.string);
var n=str.length;
document.StringLength.answerBox.value=length;
}
//Get string from user
//Output to user
</script>
</HEAD>
<BODY>
<form name = StringLength>
Enter Your String <input type = "text" name = "string">
<br>
Length <input type = "text" name = "answerBox">
<input type = "button" onclick = "stringLength()" value = "Run">
</BODY>
</HTML>
You need to check the length of the value of the string input box
function stringLength(){
var str=document.StringLength.string.value;
var len=str.length;
document.StringLength.answerBox.value=len;
}
See this JSFiddle for a demo.
You may try like this:
var x = document.getElementById('yourinput');
var y = document.getElementById('characters');
x.onkeyup = function() {
y.innerHTML = x.value.length;
}
JSFIDDLE
function stringLength()
{
var str=(document.StringLength.string);
var n=str.length;
document.StringLength.answerBox.value = n ;
}
Can you try this one, you have not ended form tag properly
<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
/*
Purpose of script: report length of string given by user
*/
function stringLength()
{
document.StringLength.answerBox.value=document.StringLength.string.value.length;
}
//Get string from user
//Output to user
</script>
</HEAD>
<BODY>
<form name ="StringLength" >
Enter Your String <input type = "text" name = "string">
<br> Length <input type = "text" name = "answerBox">
<input type = "button" onclick = "stringLength()" value = "Run">
</form>/*encloded form tag here*/
</BODY>
</HTML>

Categories

Resources