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>
Related
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>
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)
Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>
I am having trouble getting my JS to return the longest word when I click on the button. I am not sure what in my JS code I am missing or have put incorrectly, but when I type in three words nothing is given back to me. I have pasted below both my JS and html codes.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Longest Word</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-longest.js"></script>
</head>
<body>
<header>
<h1>Longest Word</h1>
</header>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="Longest Word">
</form>
</body>
</html>
JS:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length ; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
function init() {
alert('count words');
var countTag = document.getElementById('btn1');
countTag.onclick = longestWord(string);
}
window.onload = init;
try this:
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="get Longest Word">
<br/>
Longest Word: <span id='sp1'></span>
<script>
var btn = document.getElementById("btn1");
var in1 = document.getElementById("input1");
var sp1 = document.getElementById("sp1");
btn.onclick = function(){
var vals = in1.value.split(' ');
var val = vals[0];
vals.forEach(function(v){ if(v.length>val.length) val = v;});
sp1.textContent = val;
}
</script>
Fiddle Demo
Add this to your button:
onClick="alert(longestWord(document.getElementById('input1').value))"
It will take the value of input1 and send it to your longestWord-function. Then put up an alert-box with the return value from your function.
I don't see anything particularly wrong with your code ... except for the fact that "I don't see any code here that will ever 'give anything back to you!'" :-)
Presumably, "onload", the init() function dutifully runs ... and setting countTag.onclick to whatever integer value longestWord() might return when given the undefined value of the non-declared non-variable length. (Which is of no good use at all to onclick, which expects a function, not an integer...)
None of which, even if it did work (which it doesn't ...), ever asks the digital computer to, by any means at all, "give anything back to you!"
I want a webpage that has a text box. There are two buttons underneath the text box that says "Sort Alphabetically" and "Sort numerically." I want it so that whatever the user types in the box, it sorts. If the user types in numbers and letters, it will cancel the sorting and an alert will pop up saying "Cannot be letters and numbers." When the "Sort Alphabetically" button is clicked, the JavaScript code will activate and sort the words alphabetically. Same goes with the "Sort Numerically" button. I can't seem to get the words/numbers to sort.
HTML:
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>
JavaScript:
function sortAbc() {
var captureText = document.getElementById('textbox');
captureText.sort();
//Help! How to make alert pop up when numbers and letters are typed?
}
function sortNumber() {
var captureNumb = document.getElementByid('textbox');
captureNumb.sort(function(a, b){return a-b});
//Same problem here! How to make alert pop up when numbers and letters are typed?
}
Here a complet live sample.
check for number or words using regular expression (.match)
use the array function sort
function sortAbc() {
var captureText = document.getElementById('textbox');
if (captureText.value.match(/(?:^| )[\d]+(?: |$)/)) {
alert("no digits");
return;
}
var words = captureText.value.split(" ");
captureText.value = words.sort().join(" ");
}
function sortNumber() {
var captureNumb = document.getElementById('textbox');
if (captureNumb.value.match(/[^\s\d]/)) {
alert("no letters");
return;
}
var numbers = captureNumb.value.split(" ");
captureNumb.value = numbers.sort(function (a, b) { return a - b }).join(" ");
}
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>