Somehow I figure the "this" keyword isn't paying reference to the value. However as you know I could use continual if/else if statements and it will work just fine. For example I could write the code this way.
if(painStatus == 1) {
msg.innerHTML = "pain message 1";
}
else if(painStatus == 2) {
msg.innerHTML = "pain message 2";
}
so on and so forth, but using a switch statement it fails on me. I'm sure it is something simple I am not doing right. Sorry for being a noob.
<head>
<script type="text/javascript">
function painLevel(val) {
var painStatus = document.getElementById("pain_status").innerHTML = val;
var msg = document.getElementById("painMsg");
switch (painStatus) {
case 1:
msg.innerHTML = "Pain message 1";
break;
case 2:
msg.innerHTML = "Pain message 2";
break;
.
.
.
default:
msg.innerHTML = "";
}
}
</script>
</head>
<body>
<p>Please use the bar to select pain level</p>
<p>My Pain Level</p>
<input type = "range" min="0" max="10" value="1" onchange="painLevel(this.value)" />
Pain Level = <span id="pain_status">1</span>
<br /><br />
<div id="painMsg"> rePain message 1</div>
</body>
I believe you just need to parseInt like this
switch (parseInt(painStatus)) {
// As before....
}
Related
Title says it all, i am setting a value in a variable in a javascript.
I want to set that value as value of the one of the row in my form.
here is the code, this is based on previous similar questions and their accepted answers, but somehow it does not work for me.
<html>
<head>
<script>
var counter = 0;
var limit = 50;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Element " + (counter + 1) + " <input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
</head>
<body>
<form method="POST" align="center">
<script>
var emotion = "";
var raw = Math.random();
var final = Math.ceil(raw * 4);
if (final == 1)
document.getElementById("someid").value = "A";
else if (final == 2)
document.getElementById("someid").value = "B";
else if (final == 3)
document.getElementById("someid").value = "C";
else if (final == 4)
document.getElementById("someid").value = "D";
</script>
<div id="dynamicInput">
Title<br><input type="text" value="" name="myInputs[]" id="someid" disabled>
</div>
<input type="button" value="Add another event" onClick="addInput('dynamicInput');">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I also tried something like:
document.forms[0].myInputs[0].value="Whatever"
inside the script tags, but that also does not work.
Edit_1
I expect some value in the disabled input field, just below the title, but its empty.
Here is the image:
How can I have some value based on a random number generator there?
check the jsfiddle, this is due to how u arrange ur script, you either move ur code below the html, or use onload() event
example
onload="test()"
then you will no need to worry where the js should put
<script>
function test(){
var emotion = "";
var raw = Math.random();
var final = Math.ceil(raw * 4);
if (final == 1)
document.getElementById("someid").value = "A";
else if (final == 2)
document.getElementById("someid").value = "B";
else if (final == 3)
document.getElementById("someid").value = "C";
else if (final == 4)
document.getElementById("someid").value = "D";
}
</script>
https://jsfiddle.net/gw04jhoj/
you can refer to this for more info
Javascript that executes after page load
Your script is running before those HTML elements have been created, and so setting their value will fail, as document.getElementById("someid") doesn't exist yet. You should see this fail in the error console in the browser (F12).
Try moving the script until after you've created the HTML elements in question, or better yet change your script to only execute once the document has loaded.
You should use :
document.getElementById("someid").value="whatever";
I have five input fields, I need to validate all the fields by showing a circle type validation modal. It will be incremented dynamically.
Please find attached sample validation images.
Here is the code:
$("#field1, #field2, #field3").blur(function() {
var getImageName = $('#step-dwld').attr('src').slice(7, 30);
if( !this.value ){
$('#step-dwld').attr('src', 'images/'+getImageName);
} else{
switch (getImageName) {
case "step-bg.png":
$('#step-dwld').attr('src', "images/step-1.png");
break;
case "step-1.png":
$('#step-dwld').attr('src', "images/step-2.png");
break;
case "step-2.png":
$('#step-dwld').attr('src', "images/step-3.png");
break;
}
}
});
Because of your vague question without or with very less code it is hard for us to guess what your code is and your HTML structure, you need to create a Minimal, Complete, and Verifiable example so that others can help you.
However check this it might give you an idea on how to do it, I don't now your code this why and based on guesswork I implemented a similar one to simulate it
JS Fiddle
var validate = $('.validate'), score= 0;
validate.on('change', function(){
score = 0;
validate.each(function(){
if($(this).val() != ''){
score += 100 / validate.length;
}
console.log(score);
setImage(score);
});
});
function setImage(score){
var url;
switch (score){
case 20:
url = '20%';
break;
case 40:
url = '40%';
break;
case 60:
url = '60%';
break;
case 80:
url = '80%';
break;
case 100:
url = '100%';
break;
default:
url = '0%';
}
var img = '<img src="//placehold.it/100x100/?text=' +url+ '">';
$('#img').html(img);
}
#img{width:100px;height:100px;border:1px solid gray;margin:10px 0;}
input[type="text"]{display:block;margin:2px 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="img"></div>
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<button id="done">I'm Done!</button>
In this project, I need to set a maximum of 10 guesses, an indication of what number is being guessed and keep those results on the screen at the end of each game without overwrite the previous guesses.
Each set of guess output needs to be numbered to indicate how many guesses have been made. For the output, I need to use innerHTML. The user will guess a number from 1 to 999. I have to use while loop.
So far this is the code where I'm working and I have some errors and it's not working. Can anybody put me in the right direction to finish this code?
The errors that I found when I inspect the document are checkGuess() function and an anonymous function with a message "Cannot read property 'value' of null"
<script type="text/javascript">
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.getElementById("guesses");
var lastResult = document.getElementById("lastResult");
var lowOrHi = document.getElementById("lowOrHi");
var guessSubmit = document.getElementById("guessSubmit");
var guessField = document.getElementById("guessField");
var guessCount = 1;
function checkGuess() {
var userGuess = Number(guessField.value);
guesses.innerHTML += userGuess + "";
}
while (guessCount == 10) {
lastResult.innerHTML = "!!!GAME OVER!!!";
disableForm();
} else {
if (userGuess == randomNumber) {
lastResult.innerHTML = "Congratulations! You got it right!";
lowOrHi.innerHTML = "";
disableForm();
} else {
lastResult.innerHTML = "Wrong!";
if (userGuess < randomNumber) {
lowOrHi.innerHTML = "Your guess is too low!";
} else if (userGuess > randomNumber) {
lowOrHi.innerHTML = "Your guess is too high!";
}
}
guessCount++;
guessField.value = "";
}
}
function disableForm() {
var wholeForm = document.querySelector(".form"); // grab a reference to the whole form (the contents of the div with class form)
wholeForm.style.opacity = 0.5; // change the opacity of the form to 0.5
guessField.setAttribute("disabled", "disabled");
guessSubmit.setAttribute("disabled", "disabled"); // disable the form field and submit button so they can no longer be used
}
guessSubmit.onclick = checkGuess;
</script>
</head>
<body>
<h1>Number guessing game</h1>
<p id="guesses"></p>
<p id="lastResult"></p>
<p id="lowOrHi"></p>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit">Enter Guess</button>
</div>
<p></p>
</body>
</html>
Your program is all wrong and is actually doing nothing
the only thing that actually executes is everything outside your functions,
and those are being called only when the page is loaded for first time
in order to execute your CheckGuess you need to actually call it :
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
but everything else that is actually outside of your functions are only executed when the page is loading
also you have a while--else statement, that's not even possible
then again... it is outside a function so it is useless
You need to put everything on one single statement
YOU DO NOT NEED A WHILE
once you write something down on the page it will stay there until it reloads
if you write a while like that you will just loop your code endless.
this code and logic is so wrong in so many ways i will sent you a functional code :
<script type="text/javascript">
var guesscount =0;
var randomNumber = Math.floor(Math.random() * 100) + 1;
function checkGuess()
{
guesscount = guesscount +1;
var userGuess = document.getElementById("guessField").value;
document.getElementById('guesses').innerHTML += Number(userGuess)+ '<br>';
CheckResults();
}
function CheckResults()
{
//add here your logics if the number is wrong
if ( guesscount>= 10)
{
document.getElementById("guessField").disabled = true;
document.getElementById("guessSubmit").setAttribute('disabled', 'disabled');
document.getElementById('guesses').innerHTML += 'game Over !';
}
}
</script>
</head>
<body>
<h1>Number guessing game</h1>
<label id="guesses"></label>
<label id="lastResult"></label>
<label id="lowOrHi"></label>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
</div>
<p></p>
</body>
</html>
The converter is working fine, it looks for a match to the input and if it finds one, it converts it to the new value.
The problem I am running into is that I can output the new value with document.write(userInput);
But I dont know how to format or add html and text to the output. Help!
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
userInput="yyyy";
}
else if(userInput == "yyyy") {
userInput="zzzz";
}
else {
userInput="Not Found";
}
document.write("<br /><br /><b> The equivalent value is: </b>") + (userInput) + ("< br /><br /><b>Click here to Start Over</b>");
}
// Need to fix the "reset" to go back to restart the program
</script>
</body>
</html>
Change
document.write("<br /><br /><b> The equivalent value is: </b>") + (userInput) + ("< br /><br /><b>Click here to Start Over</b>");
For
document.write("<br /><br /><b> The equivalent value is: </b>" + userInput + "< br /><br /><b>Click here to Start Over</b>");
You should setup the html the way you want it to look, and then modify it using innerHTML or whatever DOM function/attributes instead of overwriting the page or having to reload it.
HTML
<h1>Value Converter</h1>
<input type="text" id="userInput" placeholder="Enter a value" />
<div>
<span>The equivalent value is: </span>
<span id="output">Enter a value and submit first</span>
</div>
<button onclick="test()">Submit</button>
JS
function test() {
var userInput = document.getElementById("userInput").value;
var converted = "";
switch(userInput){
case "someXXX":
//Do whatever code here
converted = "yyy";
break;
case "someYYY":
//Do whatever code here
converted = "zzz";
break;
default:
//Do whatever when all else fails
converted = "Not found";
break;
}
var output = document.getElementById("output");
output.innerHTML = converted;
}
Note that I changed your if statements to a switch/case
JSFiddle Demo
I'm new to Javascript and don't understand the following behaviors.
When the textarea is empty, the "process" code doesn't recognize it as null, and doesn't prompt for text.
When there is text in the textarea, the "process" code does not display the text in the alert. It seems this may be a scope problem I think all my variables are global.
HTML code:
<input type="button" name="btnProcessTA" onclick="myTextArea('process')" value="Process Text Area" />
<input type="button" name="btnClearTA" onclick="myTextArea('clear')" value="Clear Text Area" />
<form id="formExample" action="" method="get">
<label for="textAreaField">A text area field</label>
<textarea name="textAreaField" id="textAreaField" rows="4" cols="50"></textarea>
</form>
Javascript code:
<script type="text/javascript">
function myTextArea(op)
{
oTextArea = document.getElementById("textAreaField");
textAreaValue = oTextArea.value;
alert(op + "\n" + oTextArea + "\n" + textAreaValue);
switch (op){
case "clear":
oTextArea.value = "";
alert("Clearing");
break;
case "process":
if (textAreaValue = "")
alert("Would you please enter some text?");
else
alert("You entered:\n\n" + textAreaValue);
break;
default : alert("unknown op code");
}
}
</script>
Change
if (textAreaValue = "")
to
if (textAreaValue === "") // or ==
You are performing assignment instead of doing a comparison.
To compare, you have to use == instead of = :)
case "process":
if (textAreaValue == "")
alert("Would you please enter some text?");
else
alert("You entered:\n\n" + textAreaValue);
break;
if (textAreaValue = "")
The single equal sign in the if statement is interpreted as an assignment (It doesn't throw an error because technically it's correct syntax, but many people make this mistake by using a single equal sign instead of the double equal sign). The correct syntax would be the triple equal sign if you are intending to compare instead of assign.
if (textAreaValue === "")