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 ];
Related
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?
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();
Separating javascript and markup is easy when the script doesn't have parameters. But how is it done with inline script lines that do? Example:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add"
onclick="showSelectTables('none','none','none','table','none','none')">
</td>
(....)
<script>
function showSelectTables(set1a,set1b,set1c,setSetup,set2,set3) {
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
.
I've tried all varieties I can think of, but all I'm getting is error reports, 'undefined' or the silent treatment from the browser. Is it possible at all, and if so, how? I would be looking for a vanilla javascript solution.
EDIT: see here for what I'm trying to achieve: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript, section 2.
I suggest you to change your HTML generation logic to generate the followings:
<td class="input-cell">
<input type="radio" name="action-type" id="change-add" value="change-add" />
</td>
<script>
// just show 2 variables for demo
var settings = { change-add : { set1a: 'some_value', set1b: 'some_value' } }
$('#change-add').click(function() {
showSelectTables($(this).attr('id'));
});
function showSelectTables(the_id) {
var set1a = settings[the_id]['set1']; // which returns 'some_value'
// similar for set1b,set1c,setSetup,set2,set3
var _1a = document.getElementById('careSelector');
_1a.style.display = set1a;
var _1b = document.getElementById('module-I');
_1b.style.display = set1b;
var _1c = document.getElementById('clarificSection');
_1c.style.display = set1c;
var setup = document.getElementById('setup');
setup.style.display = setSetup;
var _2 = document.getElementById('module-II');
_2.style.display = set2;
var _3 = document.getElementById('module-III');
_3.style.display = set3;
}
</script>
Note: this assumes you use jQuery.
An important note: there is nothing wrong to use inline onclick, but it's a better pattern to separate JS and HTML
I am not good at code so am a bit in the hands of anyone who might be able to help.
I have a functioning Ticker Tape working in my wordpress site here www.solosails.com
currently, it works from data manually entered, I would like to modify it so that it takes the title and link from my RSS feed myurl/feed hopefully by using something like this ...
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
The Java Script code is...
function startTicker(){theCurrentStory=-1;theCurrentLength=0;if(document.getElementById){theAnchorObject=document.getElementById("tickerAnchor");runTheTicker()}else{document.write("Error");return true}}function runTheTicker(){var e;if(theCurrentLength==0){theCurrentStory++;theCurrentStory=theCurrentStory%theItemCount;theStorySummary=theSummaries[theCurrentStory];theTargetLink=theSiteLinks[theCurrentStory];theAnchorObject.href=theTargetLink}theAnchorObject.innerHTML=theStorySummary.substring(0,theCurrentLength)+whatWidget();if(theCurrentLength!=theStorySummary.length){theCurrentLength++;e=theCharacterTimeout}else{theCurrentLength=0;e=theStoryTimeout}setTimeout("runTheTicker()",e)}function whatWidget(){if(theCurrentLength%2==1){return theWidgetOne}else{return theWidgetNone}}
This is the part of the code that potentially needs altering so that the hardcoded links and titles become the new code pulling from the rss feed...
var theCharacterTimeout = 50;
var theStoryTimeout = 4000;
var theWidgetOne = "_";
var theWidgetNone = "";
var theSummaries = new Array();
var theSiteLinks = new Array();
var theItemCount = 2;
theSummaries[0] = "Solo Sails proudly sponsor Lizzy Foremans Mini Transat Campaign... Read more here ...";
theSiteLinks[0] = "http://www.solosails.com/solo-sails-sponsor-lizzie-foremans-mini-transat-campaign/"
theSummaries[1] = "10% discounts on ALL multiple sail orders !! Try us for price with your new sails, complete our simple quote form here.";
theSiteLinks[1] = "http://www.solosails.com/quotes"
startTicker();
Many thanks in advance if you can help!
Andrew
Still hoping somebody can help here.
I basically want to either get theSummaries and theSiteLinks to be pulled from the rss or change the arrays so that they use the XML parser in Javascript.
Would really appreciate some help here and happy to donate something via paypal for the working result.
Regards, Andrew
Thanks to #David Hammond for finding the answer ...
var theCharacterTimeout = 75;
var theStoryTimeout = 4000;
var theWidgetOne = "_";
var theWidgetNone = "";
var theSummaries = new Array();
var theSiteLinks = new Array();
jQuery.get('http://www.solosails.com/feed/', function(data) {
var $xml = jQuery(data);
$xml.find("item").each(function() {
var $this = jQuery(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text()
}
//Do something with item here...
theSummaries.push(item.title);
theSiteLinks.push(item.link);
});
theItemCount = theSummaries.length;
startTicker();
});
everyone..i want after i type "0203-ED" in textfield ...two character behind that text can control the radio button.. "ED" character from that text can make one radiobutton which has value="ED" are checked...
this is my code:
<script type="text/javascript">
var model=$("#tags1").val();
var version[0,0]="JD";
var version[0,1]="87.5-107.9";
var version[1,0]="ED";
var version[1,1]="87.5-108.0";
var version[2,0]="EED";
var version[2,1]="65.0-74.0";
// each version
for (var i = 0; i < version.length; i ++) {
if (model.lastIndexOf(version[i,0])!=-1) {
$("#value").replaceWith("<div id='value'>"+version[i,1]+"</div>");
} else {
$("#value").replaceWith("<div id='value'></div>")
}
// end each
}
</script>
what's wrong with my code??
I see a couple things going on.
First, why do you have a default: in there? That's a keyword used in switch statements; it's not valid in an if statement. Remove it entirely.
You also have model,lastIndexOf instead of model.lastIndexOf
you don't have to use .replaceWith()...
for (var i = 0; i < version.length; i ++) {
if (model.lastIndexOf(version[i,0])!=-1) {
$("#value").html(version[i,1]);
} else {
//default
$("#value").html("");
}
// end each
}
Watch your language typing. It should be text/javascript. Right now you have text/jaavascript. Depending on the browser and your doctype, this could prevent your script from even executing (it wouldn't just fail silently, it wouldn't even get the chance to fail).
In addition to the answers already given, try declaring your array only once. There are several ways create the data structure you're after. Use whichever style you find most comfortable.
var version = [['JD',"87.5-107.9"],["ED","87.5-108.0"],["EED","65.0-74.0"]];
var version = [];
version[0] = ["JD","87.5-107.9"]
version[1] = ["ED","87.5-108.0"];
version[2] = ["EED","65.0-74.0"];
var version = [];
version[0] = [];
version[0,0]="JD";
version[0,1]="87.5-107.9";
version[1] = [];
version[1,0]="ED";
version[1,1]="87.5-108.0";
version[2] = [];
version[2,0]="EED";
version[2,1]="65.0-74.0";
About the third version, though, I'm actually not sure that your array notation (version[0,1]) is universally supported. I don't think I've seen anyone use that notation in more than 10 years. Typically, you access members of a multi-dimensional array with the notation: myArray[x][y]. But maybe that's just a style difference. I'm not sure.
[EDIT] Are you trying to do something like this? This isn't terribly efficient, but it may be a starting point for you. In this case, jQuery is definitely your friend.
<input type="radio" name="version" value="87.5-107.9" /><label class="version">JD</label><br />
<input type="radio" name="version" value="87.5-108.0" /><label class="version">ED</label><br />
<input type="radio" name="version" value="65.0-74.0" /><label class="version">EED</label><br />
<input type="text" name="version_text" value="Enter your value" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">//<![[
var jVersionTextInput = $('input[name=version_text]');
var jLabels = $('label.version');
var jRadioButtons = $('input[name=version]');
var intVersionCount = jLabels.size();
var updateRadioButtons = function() {
var rxLabelValue;
var isValueFound = false;
rxLabelValue = new RegExp( $(jVersionTextInput).val() );
for (var i = 0; i < intVersionCount; i++) {
if (!isValueFound && rxLabelValue.test($(jLabels[i]).html())) {
jRadioButtons[i].checked = true;
isValueFound = true;
}
else {
jRadioButtons[i].checked = false;
}
}
}
jVersionTextInput.keyup(updateRadioButtons);
//]]></script>