Ok so I'm making a video game and I want players to be able to select custom files within the game via a text input box. I was able to get everything to work but when I click the Load Level button it will take me to:
.../Custom Levels/undefined.html
I tried messing around with a few other ways but the only other thing I got was:
.../Custom Levels/[object HTMLInputElement].html
<div>
<p><input type="text" id="LVLNK" value="Level Name"></p>
<p><input type="button" id="MButton" value="Load Level" onclick="LDLVLNK()"></p>
</div>
<script>
var time = setInterval(10,gameLoop)
var LevelLink; /*put: "var LevelLink = document.getElementById("LVLNK");" to get other link example instead*/
function gameLoop()
{
LevelLink = document.getElementById("LVLNK").value;
}
function LDLVLNK()
{
window.location = "../Custom Levels/" + LevelLink + ".html";
}
The file I'm currently trying to access is named "CLevel1"
So I would place CLevel1 in the input box. The gameLoop would set the name toe the LevelLink variable that is then added to the full link in the window.location function located inside of the LDLVLNK function that is activated by the button.
You have the arguments to setInterval() backwards, it should be:
setInterval(gameLoop, 10);
But there's no reason for the LevelLink global variable. You can simply get the input value in LDLVLNK():
function LDLVLNK() {
var LevelLink = document.getElementById("LVLNK").value;
if (LevelLink) {
window.location = "../Custom Levels/" + LevelLink + ".html";
} else {
alert("Nowhere to go to");
}
}
I guess you could try the following :
function LDLVLNK(){
location.href = "../Custom Levels/" + LevelLink + ".html";
//here window is optional, location is a globally accessible object
}
BTW :
You got it wrong with setInterval, you should use setInterval(gameLoop, 10);(even though 10 is probably not very good/maintainable by the browser, try 100 and reduce the amount by a touch if it's too much)
Related
I am so confused. I have a form and for now, I send a value into my javascript function. It works with a specific name "bookDate" but whenever I decide to change the name, it gives me an index unidentified error.
HTML FILE:
<input name="submit" type="button" onClick="postBooking('postbooking.php','targetDiv', pickUpDate.value, pickUpTime.value) " value="Book a Cab!">
Javascript:
function postBooking(dataSource, divID, bookingDate, bookingTime) {
if (xhr) {
var place = document.getElementById(divID);
var url = dataSource + "?bookDate=" + bookingDate + "&bookTime=" + bookingTime;
xhr.open("GET", url, true);
PHP:
$pickUpDate = $_GET["bookDate"];
$pickUpTime = $_GET["bookTime"];
echo $pickUpDate." ".$pickUpTime;
In the javascript, when I change "bookDate" into another name (I change the php GET as well to match) it starts to give an index unidentified message when I click my button. It works fine the way it is so I'm so confused why only that name works.
I have a JSP containing JavaScript function.Within that I created an inner html code.That contain a button with onClick function.When clicking the button I want to pass 2 parameters to the the function of JavaScript. But I can't get the 2 values properly.Please help me
Thank you
<script type="text/javascript">
function find(){
var i=0;
var servicetypevalue="SERVICE";
var td7= document.createElement("td");
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
}
function getStatus(i,servicetypevalue){
alert("enter");
}
</script>
I want to show the enter alert.But the parameter values are not properly passed.
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus(' + i + ',' + servicetypevalue + ');">';
use string concatenation as given above.
If your'e going to generate your own elements in JS, it's different than jQuery. While in jQuery you can make strings into valid markup reliably, but JS is not as sophisticated. Yes you can make an element by innerHTML, but it's error prone. The procedure to accomplish what you want in plain JS is as follows:
#1. Create an element.
#2. Append element to a parent.
#3. Add attributes to element.
The way your code is, it wouldn't work because your'e skipping #2. .td7 is never appended on the DOM and if the innerHTML of .td7 was rendered, it might succeed that'd be wierd. Instead of using an inline event which limits you, addEventListener gives you much better control and is more manageable. Also your getStatus just alerts "enter" which doesn't prove that your 2 parameters actually were passed. I added another alert as proof that the parameters were passed.
var i = 0;
var servicetypevalue = "SERVICE";
var host = document.querySelector('body');
var td7 = document.createElement('td'); //#1
var ptBtn = document.createElement("button"); //#1
host.appendChild(td7); //#2
td7.appendChild(ptBtn); //#2
ptBtn.className = "button"; //#3
ptBtn.name = "ptBtn"; //#3
ptBtn.id = "ptBtn"; //#3
ptBtn.innerHTML = "View Status"; //#3
function getStatus(i, servicetypevalue) {
alert("enter");
alert("i: " + i + "\nservicetypevalue: " + servicetypevalue)
}
ptBtn.addEventListener('click', function(event) {
getStatus(i, servicetypevalue);
}, false);
window.load = find;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
Try to replace
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
to
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="' + "getStatus('i','servicetypevalue'" + ');">';
Yeah, i know the title is a bit confusing but that's what it is...
Here is the piece of JavaScript code i have inside my ASP.NET Web app,
the line that troubles me is the 7th line from the bottom, after chat.server.send.
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div /> ').text(message).html();
var tremp_id = $('<div /> ').text("<%=Request.QueryString["tid"]%>").html();
var chatMessage = document.getElementById('<%= chatMessage.ClientID %>');
chatMessage.value = 'value from javascript';
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val('<%=returnName()%>');
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('<div /> ').text('<img src="<%=getUserImage(Convert.ToInt32(Request.QueryString["uid"]))%>" height="50" width="50" border="1" bordercolor=black />').html() + $('#displayname').val(), $('#message').val() + $('<div /> ').text(" | Tremp: <%=Request.QueryString["tid"]%>").html());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
As you can see I'm trying to add an image that gets the URL from a function within my C# code behind.
It gets some number from the URL and sends it to the function, that returns an image URL.
It seems alright except it shows the following instead:
What am i doing wrong and how can i fix it?
I'm sure it should be pretty simple.. but i can' find the right way..
Thanks.
You're using jquery Text function which escape the string (intended for text).
What you're looking for it the jquery append function.
chat.server.send($('<div /> ').append(...
In fact, you have the same problem when you broadcast your message (chat.client.broadcastMessage). You're using text instead of append
var encodedMsg = $('<div /> ').append(message).html();
Also make sure that your message variable is not already encoded from the server.
I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.
I'm working on a javascript program that is a simple guessing game. It comes up with a random number between 1 and 10 and provides an input field and a button for the user to make their guess. The program tells after each guess whether the user guessed too high or too low, and it keeps up with the number of guess it took the user to get the correct answer which it displays along with a "congratulations" message when they get it right.
I'm having some trouble getting it to work properly. The page displays properly, but when I enter a guess and click my submit button, nothing happens.
Here is my code:
<html>
<head>
<title>Guess My Number</title>
<script type="text/javascript">
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum() : function() {
this.num = parseInt(Math.random() * 10) +1;
},
checkNum() : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
alert("Correct! It took you " + this.turns + "turns to guess my number.");
return true;
}
else if(guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
}
else (guess < this.num) {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="button" value="Reset Game" onclick="resetGame()" />
</p>
</body>
</html>
I've never actually worked with Javascript before so I know this is probably a very basic thing that I'm overlooking. Any ideas as to why this isn't working correctly?
You variable guess is undefined.
Just initialize it with :
var guess = 0;
However be careful there's a possibility that num is initialize to 0. So, the user guessed immediatly without doing nothing.
var num = Math.random() *10 + 1;
BR
You should call your function in first place, one possible thing you can do is:
<input type = "button" value = "Submit Guess" onclick="guessNumber()">
now that your function is called you need to get the value entered by the user into your guess variable, which I don't see in your code, you can do it as:
Your guess:<input type = "text" name = "guess" size = "10" id="guess" /> <br />
and then in your java script initialize the variable guess as:
guess=document.getElementById("guess").value;
This should do the thing!
EDIT:
Also make sure that Math.random() returns an Integer,as others have suggested use Math.ceil() !
Several other answers have pointed out some issues in the test code:
type="submit" but no <form> tags.
Misspelled variable name tunrs instead of turns.
Use of the while loop
No event connections between the buttons and the JavaScript
This is a simple code example, and there are so, SO many ways to tackle it in JavaScript. Here is my method.
When creating a simple game board where the page does not need to be reloaded, I like to create a game object. In JavaScript you can create objects in a variety of ways. But one of the simplest is this:
var game = {};
This creates an empty object with no properties or methods. To create a couple of properties:
var game = {
num: 0,
turns: -1
};
Each of these properties can be referenced globally like var x = game.num;. To create the object with a function:
var game = {
num: 0,
turns: 0,
reset: function() {
this.turns = 0;
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
//Note: "this" lets you refer to the current object context. "game" in this case.
//There are a couple of ways to force the value to an Int, I chose parseInt
}
};
Game now has a game.reset() function that will set game.turns back to 0 and get a new game.num. Here is the full javascript code for my example (slightly different than the above examples):
<script type="text/javascript">
//Create an object to hold the game info
var game = {
num : 0,
turns : 0,
reset : function() {
//function to reset
this.turns = 0;
this.newNum();
},
newNum : function() {
//get a random integer between 1 and 10
this.num = parseInt(Math.random() * 10) + 1;
},
checkGuess : function(guess) {
//try to convert the guess into a integer
try {
guess = parseInt(guess);
} catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
//perform strict check of equality
if (guess === this.num) {
alert("Correct! It took you " + this.turns + " turn(s) to guess my number");
return true;
} else if (guess > this.num) {
alert("Your guess is too high. Try again.");
this.turns++;
return false;
} else {
alert("Your guess is too low. Try again.");
this.turns++;
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.checkGuess(guess);
}
function resetGame() {
game.reset();
}
resetGame();
</script>
Note: I didn't do a window.onload event here because those are only needed when the code will be interacting with elements on the document, or DOM elements. If you try to execute JS code in the head of the document, it gets executed instantly before the rest of the document gets loaded. This is bad if your JS code is trying to get, set, or manipulate elements in the page because you're still in the head and the body hasn't been loaded yet.
So in the case where your code needs to get access to elements of the page, often a window.onload = someInitFunction(); will be used so that the JS code will be executed after the document has completed it's load.
Below is my HTML code. It is mostly similar to your code except that I change the name attribute to id on the "guess" input to make it easier to access with document.getElementById(). Using name is helpful when you are in a form and will be submitting values to a server. Only fields with the name attribute set get submitted in that case. Often on forms you will have something like <input type="text" id="textfield" name="textfield" />. The id is used in JavaScript for easy of access, and name is used when submitting the form back to the server.
I also added onclick attributes to the buttons, and changed the input type="submit" to input type="button".
<h1>Would You Like To Play A Game?</h2>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Instructions</h2>
<p>
The game is very simple, I am thinking of a non-decimal number between 1 and 10
and it is your job to guess what that number is. If you do not guess my number
correctly on your first attempt, that's ok, you can keep guessing until you are correct.
</p>
<p>
Your guess:<input type="text" id="guess" size = "10" />
<br />
<input type="button" value = "Submit Guess" onclick="guessNumber()" />
<input type="button" value = "Reset Game" onclick="resetGame()" />
</p>
Here is a JSFiddle example that operates, I believe, the way you want it to.
update
As I was saying there are so many ways to do this. Here is an alternate way to give number selections.
A few issues with your code:
Math.random()*10 will return something that looks like 8.523525235, so you'll have a hard time matching that to any guesses. Instead, use Math.ceil(Math.random()*10). This generates a random number and then rounds up to the nearest integer.
In your JavaScript code, you're calling guessNumber() on the last line, which will execute the function as soon as the browser gets to that line. This will mean the function being executed before the user puts in any guesses. Instead you need to attach an event listener to the button, so that when the button is clicked, guessNumber() is called. Something like:
document.getElementById('button').addEventListener('click', guessNumber).
Right now you're not setting the variable guess in any way. You need to grab the value of the text box and assign that to guess. Something like:
guess = document.getElementById('textbox').value
Using a while loop is not appropriate here, since the user is using the textbox and the button to submit guesses each time. There are ways of doing this with a while loop, but let's stick with your current setup.
You want something that resembles this:
HTML:
<p>Your guess:
<input type="text" id="textbox" />
<input type="button" id="button" value="Guess" />
</p>
JS:
var rand = Math.ceil(Math.random()*10);
var turns = 0;
var guess;
document.getElementById('button').addEventListener('click', guess);
function guess() {
guess = document.getElementById('textbox').value;
if (guess == rand) {
alert('Correct! It took you ' + turns + ' turns to guess the number!');
} else if (guess < rand) {
alert('Your guess is too low. Try again.');
turns++;
} else if (guess > rand) {
alert('Your guess is too high. Try again.');
turns++;
} else {
alert('You didn\'t enter a number. Try again.');
}
}
Here's a fiddle. I added some for the reset functionality.