Changing image src with javascript - javascript

I am attempting to change an image with a javascript function. I thought it was easy, but can't get it to work. I can't seem to find my error. Here is the javascript:
function rollDice() {
rollCount = rollCount + 1;
dice1 = Math.floor(Math.random() * 6));
switch (dice1) {
case 0:
document.getElementById("dice1").src = "Photos/redpipdice1.png";
break;
case 1:
document.getElementById("dice1").src = "Photos/redpipdice2.png";
break;
case 2:
document.getElementById("dice1").src = "Photos/redpipdice3.png";
break;
case 3:
document.getElementById("dice1").src = "Photos/redpipdice4.png";
break;
case 4:
document.getElementById("dice1").src = "Photos/redpipdice5.png";
break;
case 5:
document.getElementById("dice1").src = "Photos/redpipdice6.png";
break;
}
}
It is linked to the html with this:
<div class = "dice-images inline">
<img id = "dice1" src = "Photos/redpipdice1.png" />
<p>Click dice to hold</p>
<div class = "button">
<button id = "roll-dice" type="button" onclick = "rollDice()">ROLL!</button>
</div>

<img id="dice1" src="Photos/redpipdice1.png" />
<button id="roll-dice" type="button">ROLL!</button>
document.getElementById(`roll-dice`).addEventListener(`click`, () => {
document.getElementById(`dice1`).src = `Photos/redpipdice${getRandomInt(1, 6)}.png`;
rollCount++;
});
function getRandomInt(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}

Related

JavaScript calculator just returns "NaN"

I'm making a calculator for a game I play and whenever I run it, it just returns "NaN" for two values, only one of the values actually returns as it should. The two values that return NaN are the ones that run through switch statements and I found that the values you get from the switch statements are undefined so I think that's where it goes wrong. I tried looking for other questions like this on StackOverflow and I found some but their answers didn't work for me.
var iron_cost = 0
var string_cost = 0
var spider_e_cost = 0
var tami_1_amount = 0
var tami_2_amount = 0
var tami_1_tier = 0
var tami_2_tier = 0
var ta_per_min_1 = 0
var ta_per_min_2 = 0
var cpt_tpc = 0
var cph_tpc = 0
var cpd_tpc = 0
function calculate_tpc() {
var string_cost = document.getElementById("string_tpc").value;
var spider_e_cost = document.getElementById("spider_eye_tpc").value;
var iron_cost = document.getElementById("iron_tpc").value;
var tami_1_tier = document.getElementById("minions_tier_1_tpc").value;
var tami_2_tier = document.getElementById("minions_tier_2_tpc").value;
var tami_1_amount = document.getElementById("minions_1_tpc").value;
var tami_2_amount = document.getElementById("minions_2_tpc").value;
var step1 = string_cost * 3.16;
var step2 = iron_cost * 0.2;
var step3 = step1 + step2 + spider_e_cost;
switch (tami_1_tier) {
case 1:
var ta_per_min_1 = 2;
break;
case 2:
var ta_per_min_1 = 2;
break;
case 3:
var ta_per_min_1 = 2.3;
break;
case 4:
var ta_per_min_1 = 2.3;
break;
case 5:
var ta_per_min_1 = 2.6;
break;
case 6:
var ta_per_min_1 = 2.6;
break;
case 7:
var ta_per_min_1 = 3.15;
break;
case 8:
var ta_per_min_1 = 3.15;
break;
case 9:
var ta_per_min_1 = 4.1;
break;
case 10:
var ta_per_min_1 = 4.1;
break;
case 11:
var ta_per_min_1 = 6;
break;
}
switch (tami_2_tier) {
case 1:
var ta_per_min_2 = 2;
break;
case 2:
var ta_per_min_2 = 2;
break;
case 3:
var ta_per_min_2 = 2.3;
break;
case 4:
var ta_per_min_2 = 2.3;
break;
case 5:
var ta_per_min_2 = 2.6;
break;
case 6:
var ta_per_min_2 = 2.6;
break;
case 7:
var ta_per_min_2 = 3.15;
break;
case 8:
var ta_per_min_2 = 3.15;
break;
case 9:
var ta_per_min_2 = 4.1;
break;
case 10:
var ta_per_min_2 = 4.1;
break;
case 11:
var ta_per_min_2 = 6;
break;
}
var step4 = ta_per_min_1 * tami_1_amount;
var step5 = ta_per_min_2 * tami_2_amount;
var step6 = step4 + step5;
var step7 = step6 * step3;
var step8 = step7 * 60;
var step9 = step8 * 24;
document.getElementById("cpt_tpc").innerHTML = step3;
document.getElementById("cph_tpc").innerHTML = step8;
document.getElementById("cpd_tpc").innerHTML = step9;
document.getElementById("test1").innerHTML = ta_per_min_1;
document.getElementById("test2").innerHTML = ta_per_min_2;
}
html,
body {
text-align: center;
}
;
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
<body>
<h1>Calculator</h1>
<br /> String Price: <input type="text" id="string_tpc" value="0">
<br /> Spider Eye Price: <input type="text" id="spider_eye_tpc" value="0">
<br /> Iron Price: <input type="text" id="iron_tpc" value="0">
<br /> Minions Tier 1: <input type="text" id="minions_tier_1_tpc" value="0"> Minion Amount 1: <input type="text" id="minions_1_tpc" value="0">
<br /> Minions Tier 2: <input type="text" id="minions_tier_2_tpc" value="0"> Minion Amount 2: <input type="text" id="minions_2_tpc" value="0">
<br />
<button onclick="calculate_tpc()">Calculate</button>
<br /> Current Coins per Tarantula: <span id="cpt_tpc">0</span>
<br /> Coins per hour: <span id="cph_tpc">0</span>
<br /> Coins per day: <span id="cpd_tpc">0</span>
<script type="text/javascript" src="main.js"></script>
</body>
</head>
</html>
The main problem is to use strings from input. The further effect is to get no values from the switch statements, because the value is a string and in all cases, you have numbers. The comparison is here strict, like ===.
For unknown values, you could return the function and omit calculation with not given values.
'use strict';
function calculate_tpc() {
var string_cost = +document.getElementById("string_tpc").value;
var spider_e_cost = +document.getElementById("spider_eye_tpc").value;
var iron_cost = +document.getElementById("iron_tpc").value;
var tami_1_tier = +document.getElementById("minions_tier_1_tpc").value;
var tami_2_tier = +document.getElementById("minions_tier_2_tpc").value;
var tami_1_amount = +document.getElementById("minions_1_tpc").value;
var tami_2_amount = +document.getElementById("minions_2_tpc").value;
var step1 = string_cost * 3.16;
var step2 = iron_cost * 0.2;
var step3 = step1 + step2 + spider_e_cost,
ta_per_min_1,
ta_per_min_2;
switch (tami_1_tier) {
case 1:
case 2:
ta_per_min_1 = 2;
break;
case 3:
case 4:
ta_per_min_1 = 2.3;
break;
case 5:
case 6:
ta_per_min_1 = 2.6;
break;
case 7:
case 8:
ta_per_min_1 = 3.15;
break;
case 9:
case 10:
ta_per_min_1 = 4.1;
break;
case 11:
ta_per_min_1 = 6;
break;
default: return;
}
switch (tami_2_tier) {
case 1:
case 2:
ta_per_min_2 = 2;
break;
case 3:
case 4:
ta_per_min_2 = 2.3;
break;
case 5:
case 6:
ta_per_min_2 = 2.6;
break;
case 7:
case 8:
ta_per_min_2 = 3.15;
break;
case 9:
case 10:
ta_per_min_2 = 4.1;
break;
case 11:
ta_per_min_2 = 6;
break;
default: return;
}
var step4 = ta_per_min_1 * tami_1_amount;
var step5 = ta_per_min_2 * tami_2_amount;
var step6 = step4 + step5;
var step7 = step6 * step3;
var step8 = step7 * 60;
var step9 = step8 * 24;
document.getElementById("cpt_tpc").innerHTML = step3;
document.getElementById("cph_tpc").innerHTML = step8;
document.getElementById("cpd_tpc").innerHTML = step9;
//document.getElementById("test1").innerHTML = ta_per_min_1;
//document.getElementById("test2").innerHTML = ta_per_min_2;
}
<h1>Calculator</h1>
<br /> String Price: <input type="text" id="string_tpc" value="0">
<br /> Spider Eye Price: <input type="text" id="spider_eye_tpc" value="0">
<br /> Iron Price: <input type="text" id="iron_tpc" value="0">
<br /> Minions Tier 1: <input type="text" id="minions_tier_1_tpc" value="0"> Minion Amount 1: <input type="text" id="minions_1_tpc" value="0">
<br /> Minions Tier 2: <input type="text" id="minions_tier_2_tpc" value="0"> Minion Amount 2: <input type="text" id="minions_2_tpc" value="0">
<br />
<button onclick="calculate_tpc()">Calculate</button>
<br /> Current Coins per Tarantula: <span id="cpt_tpc">0</span>
<br /> Coins per hour: <span id="cph_tpc">0</span>
<br /> Coins per day: <span id="cpd_tpc">0</span>

(JS) Using IF/Switch statements to change slider value

Still getting the hang of Javascript so forgive me if this seems like basic stuff.
I've set up a slider on a web page and the CSS/HTML function perfectly but I'm trying to display a year value to correspond with each value of the slider from 1 to 6.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = 133;
slider.oninput = function() {
switch (this.value) {
case 1:
output.innerHTML = 133;
break;
case 2:
output.innerHTML = 88;
break;
case 3:
output.innerHTML = 60;
break;
case 4:
output.innerHTML = 44;
break;
case 5:
output.innerHTML = 36;
break;
case 6:
output.innerHTML = 26;
break;
default:
output.innerHTML = 133;
}
output.innerHTML = this.value;
}
<div class="slidecontainer">
<input type="range" min="1" max="6" value="1" class="slider" id="myRange">
<p><span id="demo"></span> BC</p>
</div>
Currently it outputs 1 to 6 so it does function and I can set the default value to 133 before input, it just doesn't push out the values I need once the slider is moved.
Is a switch statement the correct tool for this job and, if so, where have I gone wrong?
this.value returns a string. You need to make it return a number in order for your comparison to work. Or compare against strings. Either way, the below example works. Look how I added parseInt(this.value) inside your switch operator.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = 133;
slider.oninput = function() {
switch (parseInt(this.value)) {
case 1:
output.innerHTML = 133;
break;
case 2:
output.innerHTML = 88;
break;
case 3:
output.innerHTML = 60;
break;
case 4:
output.innerHTML = 44;
break;
case 5:
output.innerHTML = 36;
break;
case 6:
output.innerHTML = 26;
break;
default:
output.innerHTML = 133;
}
}
<div class="slidecontainer">
<input type="range" min="1" max="6" value="1" class="slider" id="myRange">
<p><span id="demo"></span> BC</p>
</div>

change() jQuery not working

I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.
Relevant Code:
$(document).ready(function() {
$('input[type=radio]').checkboxradio();
var temp = parseFloat()
$('input.listener').change(function() {
var name = $(this).attr("name");
var val = $(this).val();
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
$('span#output').html(((val - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(val + 273.15);
break;
case 'r':
$('span#output').html(val / 1.8);
break;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.
Two mistakes with your code:
Forgetting breaks; for the parent switch statement.
Forgetting name="temp" on the temperature field.
I changed the final temperature to a variable and made that the text of the output just so that there would be so many $('span#output').html(temperature);
Also, you should use the oninput event to detect a change for the number field.
$(document).ready(function() {
//$('input[type=radio]').checkboxradio();
var temp = parseFloat();
$('input.listener').on('change', updateTemp);
$('input.listener').on('input', updateTemp);
function updateTemp() {
var name = $(this).attr("name");
var val = $(this).val();
var final;
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
final = ((temperature - 32) / 1.8) + 273.15;
break;
case 'c':
final = temperature + 273.15;
break;
case 'r':
final = temperature / 1.8;
break;
}
break;
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
final = ((val - 32) / 1.8) + 273.15;
break;
case 'c':
final = val + 273.15;
break;
case 'r':
final = val / 1.8;
break;
}
break;
}
$("#output").text(final);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" name="temp" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
You should set one of the radio buttons as default with checked="checked". Then try following:
$(document).ready(function () {
$('input.listener').change(function () {
if ($(this).attr("type") == 'radio') {
//radio button changed
var u = $(this).val();
} else {
var u = $("input[type='radio']:checked").val();
}
var temperature = $('#temp').val();
switch (u) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
});
});
You do not have break; after
case 'unit':
and when var name = "temp"
var val = $(this).val();
the value of var val above would be a number in string format, so when you do val + something in case 'temp' the number is getting appended instead getting added or substracted. Use parseInt(val) to convert the value of input box to integer in case of 'temp'.

Getting value of a form doesn't work

My task is checking what an user keys in. If he keys in "Mars", he gets the value.
PLanet: <input type="text" id="form_1">
<input type="submit" onClick="send()" value="Send">
<script>
var planetEntered = document.getElementById('form_1').value;
var plantesLength = new Array(3);
plantesLength['Mars'] = 52;
plantesLength['Venera'] = 30;
plantesLength['Earth'] = 10;
plantesLength['Merkyriy'] = 60;
alert(plantesLength['Merkyriy']);
function send() {
switch(form_1) {
case 'Mars':
alert(plantesLength['Mars']);
break;
case 'Venera':
alert(plantesLength['Venera']);
break;
case 'Earth':
alert(plantesLength['Earth']);
break;
case 'Merkyriy':
alert(plantesLength['Merkyriy']);
break;
default:
alert("К сожалению, мы не нашли ни одну программу.");
break;
}
}
The function returns default-block. How to fix? Thanks.
try this
you have to get the input values inside the send function.
Demo Link http://jsbin.com/ejaSUTiH/1/
PLanet: <input type="text" id="form_1">
<input type="submit" onClick="send()" value="Send">
<script>
var plantesLength = new Array(3);
plantesLength['Mars'] = 52;
plantesLength['Venera'] = 30;
plantesLength['Earth'] = 10;
plantesLength['Merkyriy'] = 60;
alert(plantesLength['Merkyriy']);
function send() {
var planetEntered = document.getElementById('form_1').value;
console.log(planetEntered);
switch(planetEntered) {
case 'Mars':
alert(plantesLength['Mars']);
break;
case 'Venera':
alert(plantesLength['Venera']);
break;
case 'Earth':
alert(plantesLength['Earth']);
break;
case 'Merkyriy':
alert(plantesLength['Merkyriy']);
break;
default:
alert("К сожалению, мы не нашли ни одну программу.");
break;
}
}
</script>
You've to declare a variable inside the function send(): And set
planetEntered in switch case for checking:
function send() {
var planetEntered = document.getElementById('form_1').value; // Here
switch(planetEntered) { // Change
}
}
JS Fiddle Demo
You don't assign the value of the input box in the send() method so it's value is the default (empty) when send() is called.

JavaScript Star Rating System

I have a working star rating system, but If a user has already voted and changes their mind on the vote, they cannot reset their vote.
Here is what I have in the Javascript:
<script type="text/javascript">
var set = false;
var v = 0;
var a;
function loadStars() {
star1 = new Image();
star1.src = "images/star1.png";
star2 = new Image();
star2.src = "images/star2.png";
}
function highlight(x) {
if (set == false) {
y = x * 1 + 1
switch (x) {
case "1":
document.getElementById(x).src = star2.src;
document.getElementById('vote').innerHTML = "One star";
break;
case "2":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Two stars"
break;
case "3":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Three stars"
break;
case "4":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Four stars"
break;
case "5":
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
document.getElementById('vote').innerHTML = "Five stars"
break;
}
}
}
function losehighlight(x) {
if (set == false) {
for (i = 1; i < 6; i++) {
document.getElementById(i).src = star1.src;
document.getElementById('vote').innerHTML = ""
}
}
}
function setStar(x) {
y = x * 1 + 1
if (set == false) {
switch (x) {
case "1":
a = "1"
flash(a);
break;
case "2":
a = "2"
flash(a);
break;
case "3":
a = "3"
flash(a);
break;
case "4":
a = "4"
flash(a);
break;
case "5":
a = "5"
flash(a);
break;
}
set = true;
insertrating(x, '<?=$themeid?>');
document.getElementById('vote').innerHTML = "Thank you!";
}
function flash() {
y = a * 1 + 1
switch (v) {
case 0:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star1.src;
}
v = 1
setTimeout(flash, 200)
break;
case 1:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
v = 2
setTimeout(flash, 200)
break;
case 2:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star1.src;
}
v = 3
setTimeout(flash, 200)
break;
case 3:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
v = 4
setTimeout(flash, 200)
break;
case 4:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star1.src;
}
v = 5
setTimeout(flash, 200)
break;
case 5:
for (i = 1; i < y; i++) {
document.getElementById(i).src = star2.src;
}
v = 6
setTimeout(flash, 200)
break;
}
}
</script>
How would I go about allowing the user to resubmit a vote?
My html looks like this:
<span style="float: left; text-align: left;"> Rate This Theme<br />
<img src="images//star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="1" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="2" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="3" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="4" style="float: left;" />
<img src="images/star1.png" onMouseOver="highlight(this.id)" onClick="setStar(this.id)" onMouseOut="losehighlight(this.id)" id="5" style="float: left;" />
</span>
As far as I can tell, the only thing preventing the user from re-voting is your set variable.
if (set==false)
{
...
set=true;
Just get rid of the if clause and it should run even if set==true
Per Tomalak's comment, i forgot to mention that:
If the backend doesn't support this,
then it will insert a new vote rather
than changing the existing one. And
since there doesn't appear to be any
user identification, that would appear
to be the case
If you don't have any user authentication, at least use a cookie or something to keep track of which user is what so that the vote is edited, not a new one created.
As for setting cookies, I'd recommend setting a cookie via Javascript once the user votes the first time. On the backend, whatever you're using for server-side technology should check to see if a cookie already exists, and if it does, edit the ranking entry instead of creating a new one.
Here's a good resource on cookies in JS: http://www.quirksmode.org/js/cookies.html
bootstrap V4 font-awesome pro jquery
$('.starts i').click(function(){
$('.starts i').removeClass('fas').addClass('fal');
var sindex=$('.starts i').index(this);
for(var i=0;i<=sindex;i++){
$('.starts i').eq(i).removeClass('fal').addClass('fas');
}
})
<div class="starts h4 mt-3" style="color:#FBC02D">
<span class=" ml-2"><i class="fal fa-star"></i></span>
<span class="checked ml-2 title"><i class="fal fa-star"></i></span>
<span class="checked ml-2"><i class="fal fa-star"></i></span>
<span class="checked ml-2"><i class="fal fa-star"></i></span>
<span class="checked ml-2"><i class="fal fa-star"></i></span>
</div>

Categories