Send person to certain website depending on text box space count - javascript

I wanting to make an HTML app that sends you to a certain website depending on the number of spaces in a text box. Here is what I am thinking:
If there are no spaces, go to google.com.
Else, go to bing.com.
I found this for getting the word count:
Count = myText.trim().replace(/\s+/g, ' ').split(' ').length;
What should I do from here? I tried making an if statement but got a plethora of errors. All help is appreciated as I am new to HTML. Thank you in advance!

I see that im posting late...
Try the following, I hope this helps you out :)
function submit(){
// Get input contents
var content=document.getElementById("wierd").value;
// Get space count
var count=(content.match(/ /g) || []).length;
// Redirect the user
// In this example, we dont actually redirect the user since this is quite annoying.
if(count===0){// If theres no spaces
console.log("duckduckgo.com");
}else{
if(count===1){// If theres 1 space
console.log("yandex.com");
}else{
if(count===2){// If theres 2 spaces
console.log("yahoo.com");
}else{//If not a choice
console.log("unknown.com");
}
}
}
}
/*ALL SO related*/
body{
background:#121212;
font-family:Helvetica, sans-serif;
}
input,button{
padding:4px;
margin:5px;
background:#333333;
border:1px solid grey;
color:white;
outline:none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<input type="text" id="wierd">
<button onclick="submit();">Fire up useless function</button>
</body>
<script src="script.js"></script>
<html>

here is my solution and I didn't use your way of finding word count :
// select your text box
let text = document.getElementById('someId').value;
// if there is only 1 element in the array then there is no space and redirect to google if not go to bing
if( text.split(' ').length > 1 ){
window.location = 'https://www.google.com';
} else {
window.location = 'https://www.bing.com';
}
I am making an array from the text in the input by splitting it using the space
example :
text = 'aaaa aaaa aa' ====> going to be ['aaaa', 'aaaa', 'aa']
if there is more than 1 element then there is 1 space at least and we proceed to the if statement

A way to do it:
function redirect(str) {
var count = str.trim().replace(/\s+/g, ' ').split(' ').length - 1;
count == 0 ?
window.open('https://www.google.com/') :
window.open('https://www.bing.com/') // :
// you can add more conditions like count == 1 ? {direction} : {else direction}
}

Even though this is completely weird, and probably useless:
function getSite() {
var lookup = {"":"www.google.com", " ": "www.bing.com"};
var result = document.getElementById("weirdo").value;
// window.open(lookup[result]);
// For demo, commented out and logging instead
alert(lookup[result]);
}
<input id="weirdo" type="text"/>
<button type="button" click="getSite()">
Enter text and click me!
</button>

Related

At first it said its not a function, now its just not doing anything

Okay, I'm trying to make a cheesy accent generator to practice with RegEx. But I have a strange problem that seems unrelated to RegEx. The submit button doesn't do anything. At first the function "maccent" was just called "accent" and at that time the console said "accent" was not a function. With nothing better to go on, I assumed it was because the word "accent" was used so many other times, so I changed the function name to "maccent". Now, however, nothing happens. What's the deal? Here is my code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p>Choose an accent</p>
<input type = "text">
<form action="">
<input type="radio" name="accent" value="German"> German<br>
<input type="radio" name="accent" value="English"> English<br>
<input type="radio" name="accent" value="Indian"> Indian
</form>
<button type="submit" onclick = "maccent()">Submit</button>
<div id = "accented"></div>
<script>
var accent = $('input[name="accent"]:checked').val();
function maccent()
{
if (accent == "German")
{
germAcc();
}
}
function germAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word
var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what? It replaces t even if its not followed by h
var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);
}
function indAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word
//this words, but not on each indivual word
console.log(desire);
}
function itAcc()
{
}
function britAcc()
{
var sample = $("input").val();
var desire = sample.replace(/[a]/gi, "au")
var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one
console.log(desire2);
//not if it's at the end of a word
}
</script>
</body>
</html>
The problem is the assignment of the "variable" accent. You are doing it at global scope (the top level), so it gets assigned when the page is first loaded.
If you move that assignment into the function maccent() (and move the work "mark" back into the comment it belongs to), your page will work.
Incidentally, the old problem was that you had a function and a variable trying to share the name accent. The variable was "winning".

HTML 5 Validation Error

StackOverflow,
I'm a NOOB learning slowly. I got some errors when trying to validate the following code in HTML 5 validator and don't know where the errors are:
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
<function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</head>
<body>
</body>
</html>
Errors: Error: Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.
From line 5, column 2; to line 5, column 34
↩ ↩
Error: End of file seen when expecting text or an end tag.
At line 18, column 7
dy>↩
Error: Unclosed element script.
From line 5, column 2; to line 5, column 34
↩ ↩
Any feedback? Thanks guys and gals.
PreYvin
You are using typographical quotes - change these to regular quotes. (single and double)
Ok, you've got a whole lot of invalid code (HTML and JavaScript) here:
<!DoctypeHTML>
Should be (case doesn't matter):
<!DOCTYPE html>
This:
<script type = “text/javascript”>
contains typographically formatted quotes instead of non-formatted quotes, which is a problem, but you don't even need the type=text/javascript anyway, so you can just write:
<script>
function is not an HTML tag, so this:
<function substitute () {
should be:
function substitute() {
Next, you are using formatted quotes in your JavaScript:
var MyValue = document.getElementID (‘mytextbox’).value;
which should be unformatted, like this:
var MyValue = document.getElementID ('mytextbox').value;
HTML isn't case-sensitive, but JavaScript is, so this:
If (myValue ==0) {
needs to be this:
if (myValue == 0)
More quote problems here:
alert(‘please enter a real value in the box’);
Should be:
alert('please enter a real value in the box');
More case-sensitivity issues here:
Return;
Should be:
return;
More quote and case-sensitivity issues here:
Var myTitle = document.getElementbyID (‘title’)
Should be:
var myTitle = document.getElementbyID ('title');
Lastly, when your script is finished and it's time to return to HTML, you didn't close your script, so this:
}
</head>
Should be:
}
</script>
</head>
You can always validate your HTML at: http://validator.w3.org
And, you can validate your JavaScript at: http://www.jslint.com
You also have invalid JavaScript so this should be valid.
<!doctype html>
<HTML>
<head>
<title> Javascript Programming!</title>
<script>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
if (myValue ==0) {
alert(‘please enter a real value in the box’);
return;
}
var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
you have an extra < in your code. but you need to revisit your javascript as it has many problems the script tag is not closed.
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
Lots of basic syntax errors here.
<!DoctypeHTML> should be <!DOCTYPE html>
the first error you listed, (Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.) is due to a funky double quote character: “ It should be " This probably originated from your text editor. What are you using? I like Sublime, but there are lots of options. The important thing is that you use a text editor designed for coding.
the next two errors are due to your script tag not being closed. Just add </script> at the end of the script.
Like I said, these are just simple syntax errors though. What you really need to learn here is how to look at those error messages and tell what's going on. Notice how the error messages reference a line number and column number? That's to tell you where the problem is. (Sometimes it can be off depending on the error, but worry about that later). Take a look at the line it's complaining about, read the error message, and you should be able to figure out what's wrong.
Close your <script> tag.
Remove < from <function
Use regular quotes instead of typographical
space between Doctype and html ie. <!doctype html>
Lastly, keywords should be all smallcase ie. if, return, var
Updated
<!doctype html>
<html>
<head>
<title> Javascript Programming!</title>
<script type = 'text/javascript'>
function substitute () {
var MyValue = document.getElementID ('mytextbox').value;
if (myValue == 0) {
alert('please enter a real value in the box');
return;
}
var myTitle = document.getElementbyID ('title')
myTitle.innerHTML = myValue;
}
</script>
</head>
<body></body>
</html>

JavaScript textarea get numbers of lines (with linebreaks)

I have a textarea and I want to know how many lines there are. Now I have searched but I only see this solution:
mytextarea.value.split("\n").length
Well, that works but that's not what I want.
For example my textarea is like this:
When I type this:
123456789abcdefghijkl
sasasasakasasask;as
When I use split("\n").value I get 2 which is correct but if I put this in:
123456789abcdefghijklsasasasasasasasasas
I get the result 1 which isn't correct:
The result should be 2 because there are 2 lines however the line breaks are not created with \n.
Anyone an idea how you can calculate the number of lines INCLUDING the line breaks without \n?
The end of each line, hit Enter . when you hit Enter ,insert \n to line.
<html>
<head>
</head>
<body>
<textarea id="myTxt"></textarea>
<button id ="btn" onclick="myLine()">Try</button>
<p id="x"></p>
<script>
function myLine() {
var txt = document.getElementById("myTxt");
var x = document.getElementById("x");
x.innerHTML =txt.value.split("\n").length;
}
</script>
</body>
</html>
Got it!
static lineCaculator() {
let dummy = document.createElement('div');
dummy.style.font = AutoTextareaResizer.computedStyle.call(this, 'font');
dummy.style.width = AutoTextareaResizer.computedStyle.call(this, 'width');
dummy.style.wordWrap = 'break-word';
dummy.innerHTML = this.value;
document.body.appendChild(dummy);
let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) / this.realLineHeight;
document.body.removeChild(dummy);
return Math.max(1, lines);
}

document.getElementById() is undefined

I'm new to the forum and new to html. I've tried may of the answers in the forums but nothing is seaming to work. While like I said i'm new I've tried looking through w3shools and having a hard time figuring this out.
what I want is to when I click the button, I would like is for it to look at the <h1><h1> and are you = x, if you are = to x then please change to work. if you are = to work please change to x.
<!DOCTYPE html>
<html>
<Head>
<title>Heather I Love You!</title>
</head>
<body style= background-color:#A8A8A8>
<!========This is the header===========>
<div id="header" style= "background-color:#00FF33;" >
<h1><p id="hheader">Heather this is a series of Pitures, Videos, and Poems to
show you the love that I have for you!"</p></h1></div>
<!=============The side bar that will allow a list of where she Wants to
go==========>
<div id="Menu" Style="background-
color:#660033;height:300px;width:125px;float:left;">
<Talbe>
<b><h3{color:white}>Categories</h3></b><br>
<button type="button" onclick="ChangeHead()">click here!</button><br>
<!--Functions-->
<Script>
function ChangeHead()
{
var g=document.getElementById("hheader")
x="Heather this is a series of Pitures, Videos, and Poems to show you the
love that I have for you!"
work="Here are some pictures of us and the boys"
if (document.getElementById("hheader").innertext == x)
{
document.getElementById("hheader").innerHTML= =work;
}
else
{
document.getElementById("hheader").innerHTML== x
}
}
</Script>
</body>
</Html>
Assuming that you have an element with the id 'hheader':
<div id='hheader'>Heather this is a series of Pitures, Videos, and Poems to show you the love that I have for you!</div>
The following script should work:
<script>
function ChangeHead() {
var g = document.getElementById("hheader");
var x = "Heather this is a series of Pitures, Videos, and Poems to show you the love that I have for you!";
var work = "Here are some pictures of us and the boys";
if (document.getElementById("hheader").innerText == x) {
document.getElementById("hheader").innerHTML = work;
} else {
document.getElementById("hheader").innerHTML = x;
}
};
ChangeHead();
</script>
So that the script will change the text of the 'hheader' div to the value of the work variable
I've found a few syntax errors in your code and I corrected them accordingly.
Here you can see a working demo:
http://jsfiddle.net/robertp/LvcCe/
1- You have an unterminated string literal at line 34 :
x="Heather this is a series of Pitures, Videos, and Poems to show you the
love that I have for you!"
For your script to work, you have to replace the line breaks in your string with "\n" in between "to " and "show". Also, take out the line breaks.
2- innerText does not work with Firefox, just use innerHTML all the time instead at line 38 :
if (document.getElementById("hheader").innertext == x)
3- = = makes no sense if you want to assign a value. Use only 1 equal sign when you assign a value to a variable.
Use two only when you are making an if statement!
Watch it at :
line 40 :
document.getElementById("hheader").innerHTML= =work;
and at line 44 :
document.getElementById("hheader").innerHTML== x
4- Line 13 has an extra quote at the end that you want to take out :
show you the love that I have for you!"
If you replace all these mistakes, your script works.
Please look at a modified version of your script that works here:
http://lespointscom.com/a/misc/stackoverflow/2014_01_29/new.html
Or just copy paste this html as is:
<!DOCTYPE html>
<html>
<Head>
<title>Heather I Love You!</title>
</head>
<body style= background-color:#A8A8A8>
<!========This is the header===========>
<div id="header" style= "background-color:#00FF33;" >
<h1><p id="hheader">Heather this is a series of Pitures, Videos, and Poems to
show you the love that I have for you!</p></h1></div>
<!=============The side bar that will allow a list of where she Wants to
go==========>
<div id="Menu" Style="background-
color:#660033;height:300px;width:125px;float:left;">
<Talbe>
<b><h3{color:white}>Categories</h3></b><br>
<button type="button" onclick="ChangeHead()">click here!</button><br>
<!--Functions-->
<Script>
function ChangeHead()
{
var g=document.getElementById("hheader")
x="Heather this is a series of Pitures, Videos, and Poems to \n\nshow you the love that I have for you!"
work="Here are some pictures of us and the boys"
if (document.getElementById("hheader").innerHTML == x)
{
document.getElementById("hheader").innerHTML=work;
}
else
{
document.getElementById("hheader").innerHTML= x
}
}
</Script>
</body>
</Html>

deleting random words from html page

I created a javascript program that prints element from my array one by one when you click on the title "click here" , my problem here is that tried to implement a function that deletes a random word from the html page when you click on the words printed previously but it printing other words instead, how can i create a function that removes words printed previously ?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script >
var k = 0;
var ph = ["red ","blue","black","green","yellow"];
function text(){
if(k < ph.length ){
document.getElementById("test").innerText+=" "+ ph[k];
k++;
}
}
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
</script>
</head>
<body>
<h1 onclick="text();">Click here</h1>
<span id="test" onclick="deleteWord();"></span>
</body>
</html>
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
Your problem is that the += operator appends " "+ ph[number] after the current value of the string.
To replace instead, use the = operator to assign a new value. since you want to delete, just use an empty string.
document.getElementById("test").innerText = "";
As a side note it is unusual to store multiple spaces in your string. If you are trying to move the contents around, you should probably consider setting the padding-left CSS property instead.
edit: if you don't want to lose the entire contents of the element, you can replace the last part of the string:
document.getElementById("test").innerText.replace(/ .*$/,"");

Categories

Resources