Im quite new at javascript so dont expect me to know much else than whats written :)
So i have a javascript file with a lot of javascript codes that almost looks the same except a number is changing with each element.
Most of my code are inside a function just not written since it's a cut out.
The relevant part of my code looks something like:
//Upgrade 1
if (CREDITS >= UpgradePrice1 && Upgrade1 === 0){
document.getElementById("Upgrade1").style.display = "block";}
else{document.getElementById("Upgrade1").style.display = "none";}
//Upgrade 2
if (CREDITS >= UpgradePrice2 && Upgrade2 === 0){
document.getElementById("Upgrade2").style.display = "block";}
else{document.getElementById("Upgrade2").style.display = "none";}
//Upgrade 3
if (CREDITS >= UpgradePrice3 && Upgrade3 === 0){
document.getElementById("Upgrade3").style.display = "block";}
else{document.getElementById("Upgrade3").style.display = "none";
And so on...
The values are assigned in a file named StandardValues.js:
var UpgradeName1 = "Craftmanship Lvl 1";
var UpgradePrice1 = 100;
var UpgradeContent1 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade1 = 0;
var UpgradeName2 = "Craftmanship Lvl 2";
var UpgradePrice2 = 200;
var UpgradeContent2 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade2 = 0;
And so on...
If it were a html code i tried to generate i would use a php while function and make it echo the same code with the changed number a specefic amount of times.
But since this is inside a javascript file i really dont think thats an option?
The javascript code from before is in a .js file.
I think a potential fix could be:
Inside a .php file:
<?php
$Upgrades = 10;
$CurrentUpgrade = 1;
while ($Upgrades >= $CurrentUpgrade){
echo "
<script>
function Upgrade1(){
//Upgrade ".$CurrentUpgrade."
if (CREDITS >= UpgradePrice".$CurrentUpgrade." && Upgrade".$CurrentUpgrade." === 0){
document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'block';}
else{document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'none';}
}
</script>
";
$CurrentUpgrade ++;
}
?>
*Sry for any typo in this part, made it quite quick.
But i would quite like to keep the javascript code inside my .js file instead of having it in my .php file.
So to sum it up i would like to (If possible):
Keep all code inside the .js file
Generate javascript code with javascript code
Repeat the same javascript element with only a number changing with each element
Try to shorten the amount of code by doing this.
Still be able to use any of the assigned variables alone somewhere like in a buy function.
I hope i gave all relevant information :)
Thanks in advance.
You can create a method (in index you are passing the number in the end of your variables):
function myFunction(newUpgradePrice, newUpgrade, index) {
if (CREDITS >= newUpgradePrice && newUpgrade === 0){
document.getElementById("Upgrade" + index).style.display = "block";}
else{document.getElementById("Upgrade" + index).style.display = "none";
}
Is This what you are looking for? Anything needing to be changed to meet your needs?
Related
I've an array thats downloaded from php to JS with paths to images, i want to switch the value on clicking the arrow image, -1 for left and +1 for right, my code doesn't seem to work tho.
<script>
var urls = <?php echo json_encode($urls); ?>;
var i = 4;
function goleft(){
if (i > 1) {
i = i - 1;
return i;
}
}
document.write('<div id=showcase><a id=leftslide><img onclick=goleft() src=images/left.png></a><img id=bigpic src='+urls[i]+'></div>');
</script>
img src=images/left.png is the left arrow.
urls[i] is what i want to change onclick an make it interactive
Thanks every one for guiding me to solution, it works with jquery now.
var urls = <?php echo json_encode($urls); ?>;
var i = 4;
function goleft(){
if (i > 1) {
i = i - 1;
$("#bigpic").attr("src",urls[i]);
}
}
</script>
<div id=showcase><a id=leftslide><img onclick=goleft() src=images/left.png></a><img id=bigpic src=></div>
I would like to start by saying I am a student, very new to front-end development and not really familiar with javascript, but i'm slowly trying to learn by coding some very basic stuff.
What I am doing
I am trying to create an odds comparison calculator, that will display the best odds for a selected match. You can view my fiddle here
Javascript
function createTeams() {
var tour = document.getElementById('tournaments').value;
if (tour == "six-nations") {
var create = document.getElementById('teamsDiv').innerHTML = "<h3>Select Team</h3><select id='teams'><option value='Wales'>Wales</option><option value='England'>England</option><option value='Ireland'>Ireland</option><option value='Scotland'>Scotland</option> <option value='France'>France</option><option value='Italy'>Italy</option></select><input type='submit' value='Check Odds' onClick='checkOdds()' />"
}
}//function createteams
function checkOdds() {
var teams = document.getElementById('teams').value;
//set bookmaker values
var EngBestOdds = "<h3>Best Odds For England:</h3> Ladbrokes # 3.00";
var WalesBestOdds = "<h3>Best Odds For Wales:</h3> BetVictor # 4.33";
var IrelandBestOdds = "<h3>Best Odds For Ireland:</h3>Sportingbet # 4.00";
var ScotlandBestOdds = "<h3>Best Odds For Scotland:</h3>Paddy Power # 17.00 AND BetVictor #17.00"
var FranceBestOdds = "<h3>Best Odds For France:</h3>Sportingbet # 6.50"
var ItalyBestOdds = "<h3>Best Odds For Italy:</h3>BetVictor #501.00"
//get teams
var selectedTeam = document.getElementById("teams").value
if (selectedTeam == "England") {
document.getElementById("dispOdds").innerHTML = EngBestOdds;
}
if (selectedTeam == "Wales") {
document.getElementById("dispOdds").innerHTML = WalesBestOdds;
}
if (selectedTeam == "Ireland") {
document.getElementById("dispOdds").innerHTML = IrelandBestOdds;
}
if (selectedTeam == "Scotland") {
document.getElementById("dispOdds").innerHTML = ScotlandBestOdds;
}
if (selectedTeam == "France") {
document.getElementById("dispOdds").innerHTML = FranceBestOdds;
}
if (selectedTeam == "Italy") {
document.getElementById("dispOdds").innerHTML = ItalyBestOdds;
}
} //function
HTML
<h3>Select Tournament</h3>
<select id="tournaments">
<option value="">-----</option>
<option value="six-nations">Six Nations</option>
</select>
<input type="submit" onclick="createTeams()" />
<div id="teamsDiv">
</div>
<div id="dispOdds">
</div>
My Problems
When running this in my fiddle I get the error undefined function
createTeams()
I feel this code is not very effective, and can be greatly improved, any tips or advice as to how I can improve this will be greatly appreciated.
What the ultimate output should look like
Any help and advice will be greatly appreciated
createTeams method is not visible in the global scope since it is enclosed in document.ready event handler.
You need to put this in global scope by changing the JS settings in fiddle from onload to No wrap - in head
For improving the code, you can form an object (key-value) of team-message like
var teamMessage = {
"England" : "Your odds are...";
}
then based on the team selection, you can simply show the message like
document.getElementById("dispOdds").innerHTML = teamMessage[ team ];
Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();
This is my code, I am trying to do an animation with 8 pictures, I was thinking first that the error is because the images are .jpg, but i tryed even converting them to .gif format and the code still did not work, When I try to run the code, i get an error saying: "Cannot set property 'src' of undefined", I don't see any mistakes in the code, i tryed looking at it multiple times, please if someone can help, thanks.
G:\Year 2\OOD - object oriented development\Webpages\Assignment\Explosion
<script>
var explosion = new Array(8);
var c = 0;
var startExplode;
var i = 0;
explosion[0] = 'ex1.jpg'
explosion[1] = "ex2.jpg"
explosion[2] = "ex3.jpg"
explosion[3] = "ex4.jpg"
explosion[4] = "ex5.jpg"
explosion[5] = "ex6.jpg"
explosion[6] = "ex7.jpg"
explosion[7] = "ex8.jpg"
function explode()
{
if(c == 7 | (i > 0 & i <= 1))
{
c = 0;
}
else
{
c++;
document.animation.src = explosion[c];
}
}
</script>
<body>
<form>
<img src ="ex1.jpg" name = "explosion" position = "fixed">
<input type="button" name="startExplode" value="explode"
onClick="startExplode=setInterval('explode()',20);">
</form>
</body>
</html>
There are a couple of problems with the code:
In the function, the AND and OR operators are doubled, not singles:
if(c == 7 | (i > 0 & i <= 1))
SHOULD BE:
if(c == 7 || (i > 0 && i <= 1))
NEXT, you are not referring to the image tag properly, so the SRC will not update, in addition, the image is call "explosion", not "animation", at least in your HTML. Also, if you give the image tag an ID, you can refer to the ID (much easier).
So the code:
document.animation.src = explosion[c];
<img src ="ex1.jpg" name = "explosion" position = "fixed">
SHOULD BE:
document.getElementById("explosion").src=explosion[c];
<img src="ex1.jpg" name="animation" position="fixed" id="explosion">
I hope this helps!
I have a string array(APN) in my bean(accessed as header). I am accessing it like this
<c:forEach var="apn" items="${header.APN}" >
var g = apn;
if (g.length!=0 && g!="null"){
if(counter == 1){
count=0;
$("#img0").show();
$("#apn0").show();
$("#rtu0").show();
}
if(counter == 2){
count=1;
$("#img0").hide();
$("#apn0").show();
$("#rtu0").show();
$("#img1").show();
$("#apn1").show();
$("#rtu1").show();
$("#removeimg1").show();
}
if(counter == 3){
count=2;
$("#img0").hide();
$("#apn0").show();
$("#rtu0").show();
$("#img1").hide();
$("#apn1").show();
$("#rtu1").show();
$("#removeimg1").hide();
$("#img2").show();
$("#apn2").show();
$("#rtu2").show();
$("#removeimg2").show();
}
}
</c:forEach>
When I keep an alert after
var g = apn;
Alert is not popped up. I have some text boxes in my UI. When I press on + icon(rendered in the form of image), another set of text boxes appear to enter multiple values. My code is not working. Can anyone help me out
I think your assignation part is incorrect. Try this -
var g = ${apn};
Seems you need an } just before /c:out. I don't know if this is the cause of your problem, i just noticed it.