Create a inputbox which writes to textarea(php) - javascript

Just for fun am I creating a chatroom for one of my school classes.
What I'm after is a JavaScript, with a inputbox which pops up, once a button (add url) is pushed, where the user can paste a url which then gets written in the textarea.
I want this feature just so "http://" gets placed in front of the added url.
Been trying with this script (which looks correct to me... but it doesn't work)
<input type="button" id="s_5" onclick="addUrl()">
<script>
function addUrl()
{
var x;
var nettside=prompt("Type in URL:","www.example.com");
if (nettside!=null)
{
x="http://" + nettside + ";
document.getElementById("area").innerHTML=x;
}
}
</script>
yeah, the textarea it's supposed to write to:
<textarea name="txt" id="area" class="typo_vind" placeholder="......" autofocus title="Type your message here, have a great day!"></textarea>
EDIT
HTML:
<input type="button" id="s_5" onclick="javascript:formatText(addUrl())">
JS:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her:","www.testtest.com");
if (nettside!="")
{
x="" + "BESKRIVELSE AV LENKEN" + "";
document.getElementById("area").value=x;
}
}
</script>
Two problems remains.
I don't want that script to clean out the textarea
I don't want the <undefined></undefined> to get added to the end
This is the result with the script as it is now:
<a href=http://www.eksempel.com>__BESKRIVELSE_AV_LENKEN__</a><undefined></undefined>
EDIT 2
Solved the problem where the script cleaned out the texarea with this:
<script>
function addUrl()
{
var x;
var nettside=prompt("Skriv inn lenkeadressen her (uten http://):","www.eksempel.com");
{
x="<a target =_blank href=http://" + nettside + ">" + "__BESKRIVELSE_AV_LENKEN__" + "</a>";
var Field = document.getElementById('area');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + x + after_txt;
}
}
</script>
So now all that's missing is removal of the <undefined></undefined>-tags.
HTML: <input type="button" id="s_5" onclick="javascript:addUrl()">
SOLVED!

You should check the console of your browser - it always notifies about what error has occurred.
You have a typo in this line:
x="http://" + nettside + ";
The ending + " should be deleted.
Also, here:
document.getElementById("area").innerHTML=x;
you should use value instead (normally you do this with for elements):
document.getElementById("area").value=x;
This might not cause problems in the browser you are using, but might lead to strange behaviour under certain circumstances :).

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

JavaScript returning null on a function for a simple guessing game

I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.

How do I get JavaScript to delay, and then refresh the page

I'd like my JavaScript to, at the end of the function I have created, wait seven seconds, and then refresh my page. If it is important, I have the vital parts of my JavaScript and HTML below...
Javascript:
var textfill = function () {
var node = document.createElement("P");
var x = document.getElementById('entertext').value;
var textnode = document.createTextNode("The search results for: '" + x + "' will show up here");
node.appendChild(textnode);
document.getElementById("123").appendChild(node);
}
HTML:
<input type="text" id="entertext">
<input type="button" onclick="textfill()" value="Search">
<p id="123">
</p>
function refreshPage() {
//ensure reloading from server instead of cache
location.reload(true);
}
function delayRefreshPage(mileSeconds) {
window.setTimeout(refreshPage, mileSeconds);
}
var textfill = function () {
var node = document.createElement("P");
var x = document.getElementById('entertext').value;
var textnode = document.createTextNode("The search results for: '" + x + "' will show up here");
node.appendChild(textnode);
document.getElementById("123").appendChild(node);
delayRefreshPage(2000);
}
Summarizing #ioseph and my personal experience.
To do something after a certain amount of time use setTimeout - https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
And to refresh the page, call
window.location.reload

Why do I get a type error when trying to access the value of an element stored in a variable?

I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.

How to stop an automatic refresh using JS

I'm using javascript to create a file explorer in my website.
I have a function wich read each file from my website and change them into a caracters chain with a chain.split() for each file.
Then, in the array created, I search words that I take from a form. And then, with an innerHTML, I rewrite my HTML page with the answers.
It works, but, when the page is rewrite, it automaticly refresh, and I lose all my search reults...
I tried to stop refresh with window.stop(), document.execCommand('stop'), and it's still refresh...
Here my form :
<form name="recherche" onsubmit="javascript:maFonction()">
<INPUT class="finder" type="text" name="maRecherche" placeholder="Enter your search"/>
<input class="press" type="submit" name="search" value="Search"/>
<p style="margin-left:5%">It may take five secondes...</p>
</form>
And here, the writing part of my JS function :
var mesResultats = "";
if (bin > 0)
{
a = 0;
mesResultats += 'your search <u><b>' + words + '</u></b> can be found here : <BR><BR>';
for (var i = 0; i < mesLiens.length; i++)
{
if (mesLiens[i] != mesLiens[i-1] )
{
var monLien = '<div style="margin-left:5%; margin-right:5%; text-align:justify;">' + mesTitres[a] + '' + '<BR></div>';
mesResultats += monLien + '<hr>';
}
a++;
}
}
else
{
var monLien = 'Homepage';
mesResultats += 'No answer corresponding to your search <u><b>' + words + '</u></b>... ' + monLien + '</div>';
}
elemnt = document.getElementById("result");
elemnt.innerHTML = mesResultats;
If anyone have an idea of how to keep my search results, thank you !
(PS : I can't show you with a link...)
Add return false into the onsubmit event, to don't refresh the page.
HTML :
<form name="recherche" onsubmit="return myFunction();">
Javascript :
function myFunction(){
return false;
}
In case someone has the same situation as me, the application was using <meta http-equiv="refresh" content="3"> and was refreshing the content every 3 seconds. The solution for me was to execute window.stop(); directly from the console.

Categories