Javascript .innerHTML fuction output only flashes - javascript

I have written a JS code to find if a string is palindrome or not. But the output only stays on for less than a second then disappears.
I know this type of question has been asked before and I tried the solution which said to add "return false" but its not working for me.
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<form>
Please enter a string:<br>
<input type="text" name="str" id="pform" onchange="return checkpalin()"><br>
</form>
<p id="demo"></p>

It's because you have it in a form. Try this
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<!DOCTYPE html>
<html>
<body>
Please enter a string:<br>
<input type="text" name="str" id="pform" onchange="return checkpalin()"><br>
<p id="demo"></p>
</body>
</html>
You can also use oninput instead of onchange to make it update while you are typing in the textbox.
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<!DOCTYPE html>
<html>
<body>
Please enter a string:<br>
<input type="text" name="str" id="pform" oninput="return checkpalin()"><br>
<p id="demo"></p>
</body>
</html>

The default event when hitting enter in a single field in a form is to submit the form.
In your code the return is only interesting on the submit event.
Just preventDefault on the submit or remove the form tags
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
document.getElementById("myForm").onsubmit = function(e) {
e.preventDefault();
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
document.getElementById('demo').innerHTML = flag ? "Not palindrome" : "Given string is a palindrome";
}
<form id="myForm">
Please enter a string and hit enter:<br>
<input type="text" name="str" id="pform"><br>
</form>
<p id="demo"></p>

Related

How can I take text from <input> tag to javascript

I have made a program and it prompts the user to input text. Is there a way I can just take user input from the text box and then have the program take and use that text from there? Here's the code so far:
None of your corrections were working because I didn't tell you the what this program does. This program is supposed to take in a letter and then replace it with another letter encrypting the text, so I think that you need to see the entire code to figure this out;
function encodeFunction() {
var text = prompt("Enter Text");
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = prompt("Enter Text");
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode = true) {
let adjust = 1;
if (!encode) {
adjust = -1;
}
}
}
str = str.toLowerCase();
let strArray = str.split("");
let letterChange = strArray.map(function(value, index, array){
if(str.charCodeAt(index) < 97 || str.charCodeAt(index) > 122){
return value
}else{
return String.fromCharCode(str.charCodeAt(index)+adjust)
}
});
return letterChange.join("");
}
<form>
<input type="text" id="EString" name="EString"> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
In your encode and decode functions, you can change:
var text = prompt("Enter Text");
to
var text = document.getElementById("EString").value;
If you'd like to get the value of the text input(id='EString') you can use
document.getElementById('EString').value
You could simply get the value of document.getElementById("EString"), e.g.
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode = true) {
let adjust = 1;
if (!encode) {
adjust = -1;
}
return str;
}
<form>
<input type="text" id="EString" name="EString"> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
function myChange(){
console.log(document.getElementById("EString").value);
}
<form>
<input type="text" onchange="myChange()" id="EString" name="EString" style=" width:1000px; height:500px;"></input>
</form>
Check the below code for your desired result:
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode=true) {
let adjust = 1;
if(!encode){
adjust = -1;
}
return adjust;
}
<form>
<input type="text" id="EString" name="EString" style=" width:1000px; height:500px;" /> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
I made some changes in your code.
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
<script>
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode=true) {
let adjust = 1;
if(!encode){
adjust = -1;
}
return "Text recieved in JavaScript: " + str;
}
</script>
Use oninput and onchange attributes in input tag to call javascript function, because oninput is not working in some browsers.

Javascript form validation oninput

I'm trying to improve my javascript skills with some form validation. Why is my code not working?
<input type="password" id="psw" />
<p id="demo" ></p>
<script type="text/javascript" >
psw.oninput = function(event) {
myArray = ["1", "2","3","4","5","6","7","8","9"];
for(x=0; x<myArray.length; x++){
if(this.value.includes(myArray[x]){
demo.innerHTML = "password cannot include
a number";
} else{
demo.innerHTML = "";
}
</script>
There are some issues with your code
You're trying to bind the input event incorrectly
psw.oninput = function(event)
^
Get your element psw using the function getElementById
document.getElementById('psw')
^
You're assigning a String incorrectly
demo.innerHTML = "password cannot include
a number"; ^
^
Missing enclosing parenthesis
if(this.value.includes(myArray[x])
^
You need to break the loop when this this.value.includes(myArray[x]) is true.
Snippet with those fixes
document.getElementById('psw').addEventListener('input', function(event) {
var myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (var x = 0; x < myArray.length; x++) {
if (this.value.includes(myArray[x])) {
demo.innerHTML = "password cannot include a number ";
break; // you need to break your loop
} else {
demo.innerHTML = "";
}
}
});
<input type="password" id="psw" />
<p id='demo'></p>
This will work.
Only when the number nine is entered does the text show up, if you type any other number it doesn't show up. Why?
If you enter 5, it inserts password cannot include a number, since it goes through the loop, and since 6 is not present in the string, it clears the alert.
<input type="password" id="psw" />
<p id="demo"></p>
<script type="text/javascript" >
var psw = document.getElementById("psw");
var demo = document.getElementById("demo");
psw.oninput = function(event) {
var isnumberpresent = false;
myArray = ["1", "2","3","4","5","6","7","8","9"];
for(var x=0; x<myArray.length; x++)
{
if(this.value.includes(myArray[x]))
{
isnumberpresent = true;
}
}
demo.innerHTML = isnumberpresent ? "password cannot include a number":"";
};
</script>
Here is a very basic improvement that works. But if you trying to improve your Javascript skills, consider using regular expressions as someone suggested.
<input type="password" id="psw" oninput="validate(this.value)" />
<p id="demo" ></p>
<script type="text/javascript" >
function validate(password) {
var demo = document.getElementById('demo');
var myArray = ["1", "2","3","4","5","6","7","8","9"];
for(x=0; x<myArray.length; x++){
if(password.includes(myArray[x])){
demo.innerHTML = "password cannot include a number";
break;
} else{
demo.innerHTML = "";
}
}
}
</script>
This code is working. Close the if bracket. Use a proper editor for writing code like notepad++.
<!DOCTYPE html>
<html>
<body>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="psw"/>
<p id="demo"></p>
<script>
var x;
psw.oninput = function myfunc(){
var myArray = ["1", "2","3","4","5","6","7","8","9"];
var ele=document.getElementById("psw").value;
for(x=0; x<myArray.length; x++){
if(myArray.includes(ele)){
demo.innerHTML = "password cannot include a number";
}
else { demo.innerHTML = ""; }
}
}
</script>
</body>
</html>

How to skip converting element text

i want output text oldnames not changes if user insert text 'false'
for example:
user input text "false toni" in textbox.
and i want output still "false toni"
why my code still changes text "toni" with "rina"?
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (oldNames== 'false ' + oldNames){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
UPDATE:
Improve the question:
Trying enter text "My name is rian and my name is false toni" .
Posible to make output "rian" still change to "susi"?
use includes x.includes(value) to check whether the text area value contains a word that you want to replace . if it contains false then your oldnames not get changed.
If you are using IE then use x.indexOf(value)>0 instead of x.includes(value)
http://www.w3schools.com/jsref/jsref_includes.asp
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'rian'];
var newNames = ['rina', 'susi'];
oldNames.forEach(function(value, index) {
/*if (x.includes('false '+value)){
var oldNames1=['false '+value];
x = x.replaceArr(oldNames1, oldNames1);
}*/
if (x.includes(value)) {
var oldNames1 = [value];
x = x.replaceArr(oldNames1, newNames[index]);
newNames1 = ['false ' + newNames[index]];
oldNames1 = ['false ' + value];
x = x.replaceArr(newNames1, oldNames1);
}
});
document.getElementById("check").innerHTML = x;
}
</script>
<body>
ENTER TEXT:
<br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
You false checking condition is wrong, you can do it using substr:
if (x.substr(0, 6) === 'false ') {
// The string starts with false
} else {
}
You can find more details on the substr from MDN.
UPDATE: As mentioned in the comment same can be done via startsWith and this is a better approach.
if (x.startsWith('false ')) {
// The string starts with false
} else {
}
try this. Compare array values instead of array.
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (x.indexOf('false') > -1 ){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>

Basic Javascript onclick

here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.

result output disappears too quickly

the correct or wrong answer outputs and quickly disappears. How do I get the answer to remain on the screen. I want to keep the html and js files separate. What I want to do later is add other phrases to the program.
INDEX.HTML
<head> </head>
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>
PHRASESCRAMBLER.JS
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}
function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}
First of all don't bind click event if you want to handle form submission, forms have dedicated event called onsubmit. When form is submitted default browser behavior is to navigate to form action (in your case reload the page). You need to prevent this by returning false from the onsubmit handler.
Corrected HTML will be (I gave an id to the form):
<form name="myForm" id="myForm"> ... </form>
And then event handling will look like (note return false; in checkAnswer function):
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}
function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>

Categories