innerHTML property is not changing after JS function - javascript

I'm a fresher in JS, so I have the following task: Some text is given on a page and when a user wants to find a set of characters or string by adding this string in a window and then clicking "search", this string should be marked as bold in our text each time it is met.
Looking through my code I'm almost sure that the function is working, but after the function has finished, the bold strings just blink for a moment and the text returns to its initial status.
Please help me to find out my mistake.
Here's the code.
function look(a) {
var str = document.getElementById("original").innerHTML;
var len = a.text.value.length;
var begin = str.indexOf(a.text.value);
var final = str;
if (begin == -1) {
alert("No matches");
return false;
}
if (begin > -1) {
var count = 0;
final = str.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
while (begin != -1) {
begin = str.indexOf(a.text.value, begin + len);
if (begin == -1) break;
final = final.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
}
document.getElementById("original").innerHTML = final;
return true;
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<span id="original" type="text">Some given text</span>
<br/>
<form name="search" onsubmit="return look(this)">
<p>Enter text to search<input type="text" name="text"></p>
<p><input type="submit" value="search"></p>
</form>
</body>

Returning true on successfully finding the text span makes the form to be submitted. You need to return false to make the form invalidate the submission. This is the updated code, I have changed the return statement out of the if-else block and returned false either way. Another way is to make submit button as input[type='button'] and register an onclick event listener to it.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
}
return false;
}

The page is refreshing! By default, forms refresh the page. You can use the return value of the on submit function to stop this default behavior: just return false.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
return false;
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
return false;
}
}
<body>
<span id="original" type="text">
Some given text
</span>
<br/>
<form name="search" onsubmit="look(this); return false;">
<p>
Enter text to search<input type="text" name="text">
</p>
<p>
<input type="submit" value="search">
</p>
</form>
</body>
</html>

Related

onclick returns input from form instead of redirecting

I am just learning JS and I am trying to navigate to a different page based on the input from the user. /MenuDemo1/src/home.jsp
In the above the two text boxes are coming and after I enter the values and click on the button, I am successful in getting the uid and pwd but on click instead of the url in location.href, it is going to MenuDemo1/src/home.jsp?username=admin&password=admin.
<form name="form1" id="form1" >
First name: <input type="text" name="username"> <br> Last
name: <input type="password" name="password"> <br>
<button id="submit" onclick="validateform()">Submit</button>
</form>
<script>
var linkHome;
function validateform() {
var uid = document.getElementById("form1").elements[0].value;
var pwd = document.getElementById("form1").elements[1].value;
if (uid === "admin" && pwd === "admin") {
document.getElementById("demo1").innerHTML = "Found elements in the form.";
linkHome = "/MenuDemo1/src/adminHome.jsp";
} else {
linkHome = "/MenuDemo1/src/userHome.jsp";
}
location.href = linkHome;
}
</script>
Can someone please point it out what I am missing? TIA.
You have to attach the function to your submit for event :
because onclick will not trigger the reirection :
so first remove the onclick="validateform()"
and then assign the function to the submit event and put return false; to prevent send form to the post url ;
js should look like belllow :
var linkHome;
document.getElementById("form1").onsubmit = function validateform() {
var uid = document.getElementById("form1").elements[0].value;
var pwd = document.getElementById("form1").elements[1].value;
if (uid === "admin" && pwd === "admin") {
document.getElementById("demo1").innerHTML = "Found elements in the form.";
linkHome = "/MenuDemo1/src/adminHome.jsp";
} else {
linkHome = "/MenuDemo1/src/userHome.jsp";
}
location.href = linkHome;
return false;
}
My answer may not be correct, I am 11 and started programming about 9 months ago, so I am a noob. But I believe it is not working because you have no paragraph to where the data can be sent to, so when I ran the program and did this edit it worked.`'
Also i believe there is no page such as "/MenuDemo1/src/adminHome.jsp" to go to
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<form name="form1" id="form1" >
First name: <input type="text" name="username"> <br> Last
name: <input type="password" name="password"> <br>
<button id="submit" onclick="validateform()">Submit</button>
</form>
<p id="demo1"></p>
<script>
var linkHome;
function validateform() {
var uid = document.getElementById("form1").elements[0].value;
var pwd = document.getElementById("form1").elements[1].value;
if (uid === "admin" && pwd === "admin") {
document.getElementById("demo1").innerHTML = "Found elements in the form.";
linkHome = "/MenuDemo1/src/adminHome.jsp";
} else {
linkHome = "/MenuDemo1/src/userHome.jsp";
}
location.href = linkHome;
}
</script>
<link rel="stylesheet" href="style.css">
</head>
<body >
</body>
</html>`
You should try this :-
linkHome = window.location.protocol + "//" + window.location.host + "MenuDemo1/src/adminHome.jsp";
and
linkHome = window.location.protocol + "//" + window.location.host + "MenuDemo1/src/userHome.jsp";
Hope this helps!

javascript substring like backspace

HI in the code down below i have a html setup with buttons for a password input form:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Log in form</title>
<link href="style.css" rel="stylesheet">
<script src="ui.js"></script>
</head>
<body>
<div id="main">
<div id="top_bar"><tx id="tx">Bildschirmsperre</tx></div>
<div id="infotext">Wählen sie Ihre PIN aus</div><br />
<div id="pin"></div><button id="btnback" onclick="changepin(10)">←</button><br />
<div id="tasten">
<button class="button" onclick="changepin(1)">1</button>
<button class="button" onclick="changepin(2)">2</button>
<button class="button" onclick="changepin(3)">3</button><br />
<button class="button" onclick="changepin(4)">4</button>
<button class="button" onclick="changepin(5)">5</button>
<button class="button" onclick="changepin(6)">6</button><br />
<button class="button" onclick="changepin(7)">7</button>
<button class="button" onclick="changepin(8)">8</button>
<button class="button" onclick="changepin(9)">9</button><br />
<button class="button" onclick="changepin(0)">0</button>
</div>
<div id="bottom_bar"> <text id="text_left">ABBRECHEN</text> <zeichen id="zeichen">|</zeichen> <text id="text_right">WEITER</text> </div>
</div>
</body>
</html>
There is no css so it looks awful right now and it contains words in germany so please ignore them.
so far i have this javascript:
var count = 0;
function changepin(value) {
var pin = document.getElementById("pin");
if(value != 10 && count < 4){
pin.innerHTML += value;
count++;
}else if(value == 10){
count--;
pin.innerHTML = pin.value.substr(0, count);
}
}
the typing in (max 4 letters) works fine but i have no idea how to make the backspace i tried a little bit but it isnt working.
Could anyone pls help?
Thanks!
You almost had it, but the use of the count variable is both unnecessary and potentially confusing. This does what you need, without it...
// only do this once - no need to find the element every time
var pin = document.getElementById("pin");
function changepin(value) {
var currentPin = pin.innerText;
// if user pressed the back button then remove the last character
if (value == 10) {
pin.innerText = currentPin.substr(0, currentPin.length - 1);
}
// else if the current pin is long enough then just exit without doing anything else
else if (currentPin.length > 3) {
return;
}
// else add the new character to the pin
else {
pin.innerText = currentPin + value;
}
}
As you can see I also changed innerHTML to innerText. In this case it makes no difference, but it's good habit to always refer to the correct property, so you want to set the text, not the HTML.
The problem is that you are trying to get the value of <div id="pin">. A div has no value. Exchange the following line:
pin.innerHTML = pin.value.substr(0, count);
With this one:
pin.innerHTML = pin.innerHTML.substr(0, count);
Also, there are some things you should clean up. For example, only use valid html tags. <text> and <zeichen> are not.
You need to change your js function like that
function changepin(value) {
var pin = document.getElementById("pin");
if (value != 10 && count < 4) {
pin.innerHTML += value;
count++;
} else if (value == 10) {
count--;
pin.innerHTML = pin.innerHTML.substring(0, pin.innerHTML.length - 1);
}
}

How to delete an appended message in jquery after you have already appended once clicking the same button?

I have looked through a lot of the already asked questions and cannot find it. I need the previous appended message to be deleted once you hit the submit button again. So this will let you choose your character that you type into the input field and then it will append a message bellow telling you that you choose x character. After that you can resubmit another character which I want, but I do not want the previous append to be there.
I tried to do a search function in javascript and if it was not equal to -1 then delete the first p in the div, but that did not work=/
Thanks for your help in advance.
html:
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
<link rel='stylesheet' type='text/css' href='styles/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='jquery/script.js'></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) : <br><br><input id='text' type="text" name="mess" value="">
<button id='button1' type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br>
<div id="box_holder"></div>
<br><br>
<button id='button2' type='button' name='button2' onclick="redirect()">Start Your Adventure</button>
</body>
</html>
JS:
$(document).ready(function() {
$('#button1').click(function(){
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
chooseChar = function () {
var text = document.getElementById('text').value;
var text = text.toLowerCase();
if(text == 'human') {
$(document).ready(function() {
$('#button1').click(function(){
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function(){
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text+".html";
window.location.href = url;
}
So your variable send gets sent and then it clears out the input field with either of those functions
$(document).ready(function() {
$('#button1').click(function(){
$('#box_holder').children('p').remove(); <===========
or Either of these should work
$('#box_holder').empty(); <===========================
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
Instead of using append, try using html as follows
$('#box_holder').html('<p>'+ 'You have chosen your character to be: '+send+'</p>');
Here is a Plunkr to explain it a little better
$(document).ready(function() {
$('#button1').click(function() {
var send = $("input[name=mess]").val();
$('#box_holder').html('<p>' + 'You have chosen your character to be: ' + send + '</p>');
});
$('input').css("color", "blue");
});
chooseChar = function() {
var text = document.getElementById('text').value;
text = text.toLowerCase();
if (text == 'human') {
$(document).ready(function() {
$('#button1').click(function() {
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function() {
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text + ".html";
window.location.href = url;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) :
<br />
<br />
<input id="text" type="text" name="mess" value="" />
<button id="button1" type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br />
<div id="box_holder"></div>
<br />
<br />
<button id="button2" type="button" name="button2" onclick="redirect()">Start Your Adventure</button>
</body>
</html>
You have to remember, the append() function appends the content on the selected component. The html() function replaces all content inside of it.
Hope it helps

HTML forms auto caps lock

Is there a way to make it so that in an html form, someone types something, and it automatically makes it a capitol letter, like in a software key code input, I would like there to automatically be a dash inserted after every five characters, but not after the last one, meaning that when someone types:
xxxxxxxxxxxxxxxxxxxx
it will automatically be entered in to the form in real time as:
XXXXX-XXXXX-XXXXX-XXXXX
Is there a way to achieve this in real time? Here is my current code for the form:
<form name="key" autocomplete="off">
Key: <input type="text" name="key" maxlength="23"/>
<input type="submit" onclick="check(this.form)" value=" Submit "/>
</form>
<script language="javascript">
function check(form)
{
if (form.key.value == "XXXXX-XXXXX-XXXXX-XXXXX")
{
window.open('URL')
}
else
{
alert ("Invalid Key")
}
}
</script>
This is not optimal at all, but it works !
<script language="javascript">
$(function(){
var isCorrect = false;
$('#key_id').on('keyup',function() {
$(this).val(function(i, text) {
text = text.toUpperCase();
if (text.length < 5) {
isCorrect = false;
return text;
} else if (text.length >= 5 && text.length < 11 && (text.split("-").length - 1) < 1) {
isCorrect = false;
return text.substr(0,5) + '-' + text.substr(5,5);
} else if (text.length >= 11 && text.length < 17 && (text.split("-").length - 1) < 2) {
isCorrect = false;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5);
} else if (text.length >= 17 && text.length < 23 && (text.split("-").length - 1) < 3) {
isCorrect = false;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5) + '-' + text.substr(15,5);
} else if (text.length >= 23) {
isCorrect = true;
text = text.replace(/-/g, '');
return text.substr(0,5) + '-' + text.substr(5,5) + '-' + text.substr(10,5) + '-' + text.substr(15,5);
} else {
isCorrect = false;
return text;
}
});
});
$("#my_form").submit(function(){
if(isCorrect) {
window.open('URL');
} else {
alert('invalid');
}
});
});
</script>
On the event keyup (releasing a key = letter/number), I do :
UpperCase
Return the text normally if less than 5 char
Return the text with '-' if more than 5 char but less than 10+1 char (the +1 is because we added '-'). Else return the text normally if already added the '-'
Return the text with 2 '-' if more than 10+1 char but less than 15+2 char (because 2 '-'). Else return the text normally if already added the 2 '-'.
And so on...
EDIT :
Updated code, you will need to use jQuery and put an id to your input id="key_id"
EDIT :
New code, easier for you to use it. Still needs jQuery (you can do it without, search on StackOverflow how to convert $(id).val() in pure javascript).
http://jsfiddle.net/f8BzW/1/
You could use css for the capitalization: text-transform: uppercase;
And with jquery + this plugin: http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("xxxxx-xxxxx-xxxxx-xxxxx-xxxxx");
});
check out the demo
So after reading the comments I decided to code it all out in a demo for you.
Here is the fiddle: http://jsfiddle.net/doppel/v3eLX/#&togetherjs=KgqxizB1Fc
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="./css/style.css">
<title></title>
</head>
<body>
<form name="key" autocomplete="off">
<label for="key">Key:</label><input type="text" name="key" id="key" style="text-transform:uppercase;" maxlength="23"/>
<input type="submit" onclick="check(this.form)" id="btn" value="Submit"/>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="jquery.maskedinput.js"></script>
<script language="javascript">
function check(form)
{
if (form.key.value == "XXXXX-XXXXX-XXXXX-XXXXX")
window.open('URL')
else
alert ("Invalid Key")
}
$("document").ready(function() {
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
});
</script>
</body>
Note you will have to download the plugin and include it like I have or copy the fiddle code.
So as you see I added a label because its proper,
I added an Id to the input to make it easier to select, Note I also added an in-line style to force Uppercase as stated above ^^^^.
Now the script $("document").ready(function() {gets jquery ready to be used.
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "}); This statement selects id key as the target of the function Mask which is the plugin to be called stating that we want a format aaaaa-aaaaa-aaaaa-aaaaa where a is equal to "letter". Note only "a" and "9" denote alpha and numeric data. And "{placeholder:" "})" the plugin by default puts underscores as placeholders but I changed it to a space to look more what you want I think.

Javascript function stops being recognized

I'm having a problem with the following code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
<!--
gallows = new Array("--------\n| |\n|\n|\n|\n|\n=====",
"--------\n| O\n|\n|\n|\n|\n=====",
"--------\n| O\n| |\n|\n|\n|\n=====",
"--------\n| O\n| \\|\n|\n|\n|\n=====",
"--------\n| O\n| \\|/\n|\n|\n|\n=====",
"--------\n| O\n| \\|/\n| |\n|\n|\n=====",
"--------\n| O\n| \\|/\n| |\n| /\n|\n=====",
"--------\n| O\n| \\|/\n| |\n| / \\\n|\n=====");
guessChoices = new Array("JavaScript", "Navigator", "LiveConnect", "LiveWire");
guessed = [];
function startAgain()
{
guesses = 0;
max = gallows.length - 1;
//guessed = " ";
len = guessChoices.length - 1;
toGuess = guessChoices[Math.round(len*Math.random())].toUpperCase();
displayHangman();
displayToGuess();
displayGuessed();
}
function stayAway()
{
document.game.elements[3].focus();
alert("Don't mess with this form element!");
}
function displayHangman()
{
document.game.status.value=gallows[guesses];
}
function displayToGuess()
{
pattern = "";
for(i=0;i<toGuess.length;++i)
{
if(guessed.indexOf(toGuess.charAt(i)) != -1)
pattern += (toGuess.charAt(i)+" ");
else pattern += "_ ";
}
document.game.toGuess.value=pattern;
}
function displayGuessed(s)
{
result="";
for(i in s)
{
guess=s[i];
result += guess;
}
document.game.guessed.value=result;
//document.game.guessed.value=guessed;
}
function badGuess(s)
{
if(toGuess.indexOf(s) == -1) return true;
return false;
}
function winner()
{
for(i=0;i<toGuess.length;++i)
{
if(guessed.indexOf(toGuess.charAt(i)) == -1) return false;
}
return true;
}
function guess(s)
{
if(guessed.indexOf(s) == -1) guessed.push(s);
if(badGuess(s)) ++guesses;
displayHangman();
displayToGuess();
displayGuessed(guessed);
if(guesses >= max)
{
alert("You're dead. The word you missed was "+toGuess+".");
startAgain();
}
if(winner())
{
alert("You won!");
startAgain();
}
}
// -->
</script>
</head>
<body>
<h1>Hangman</h1>
<form name="game">
<pre>
<textarea name="status" rows="7" cols="16" onfocus="stayAway();"></textarea>
</pre>
<p>
<input type="text" name="toGuess" onfocus="stayAway();"> Word to guess<br>
<input type="text" name="guessed" onfocus="stayAway();"> Letters guessed so far<br>
</p>
<p>Enter your next guess.</p>
<p>
<input type="text" name="input" size=1 value="">
<input type = "button" value = "guess" onclick = "guess(game.input.value); game.input.value = '';">
</p>
<input type="button" name="restart" value="---- Start Again ----" onclick="startAgain();">
<script type="text/javascript">
<!--
startAgain();
// -->
</script>
</form>
</body>
</html>
After I click the game.guess button, the first time around, I get the expected output... game.input clears and guessed is displayed. However, the second time I click the guess button with a different value, I receive the error:
guess is not a function
| onclick()
| event = click clientX=77, clientY=33
guess(game.input.value) onclick(line 2)
And I honestly can't figure out why. What am I doing wrong?
(I got the bulk of this code from Mastering JavaScript, Premium Edition, by James Jaworski)
The problem is on these lines:
guess=s[i];
result += guess;
This way you are changing the context of guess. If you change this line to
result += s[i];
Your error will go away.
You are conflicting your function with using same name for a variable.
Remember to define your variables using var keyword and avoid such confusion.
1 - use anonymous functions where possible
2 - declare and use local variables
To avoid conflicts.
In your function displayGuessed(), you are setting the variable guess (which is a function) to the the guessed letters.
You can fix this by defining your function's guess variable (making it distinct from the function) using the "var" keyword:
function displayGuessed(s)
{
var guess;
result="";
for(i in s)
{
guess=s[i];
result += guess;
}
document.game.guessed.value=result;
}
Tip: I found this bug easily by using the Firebug plugin for firefox, which lets you step through javascript code line by line, to see where things are going wrong.

Categories