I am just thinking out loud, is there a more elegant way for my coding solution. The code is working, but I've build a weather app with Freecodecamp.com and the task was to include a fahrenheit/celsius switch. So, there is an API which gives me the temperature, after I click a button, which gets my position. This temperature is in Fahrenheit. Before the output in html starts, the status of the switch should be checked and the temperature should be given out in Fahrenheit or Celsius. After I click the button again I can switch between Fahrenheit and Celsius Temperature.
In my mind, it was logical. Check the prop with IF (Celsius), else (Fahrenheit). Then after the state of the selector changes, the temperature should change accordingly.
My question is, can this code be optimized, I just started with Javascript and the code quality feels suboptimal. Thanks in advance.
Edit: I don't know why I get down voted, trolls?
Working Prototype HERE
JS:
<script>
function a() {
var apiKey = "40683c3325e6ebb13cbf4331b7cc1f44";
var url = "https://api.darksky.net/forecast/";
var lati;
var longi;
var icon;
var data;
var text;
var tempFahrenheit;
var tempCelsius;
var textSummary;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$("#out").html("Geolocation is not supported by this browser.");
}
function showPosition(position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data){
//console.log(data);
tempFahrenheit = data.currently.temperature;
textSummary = data.currently.summary;
// Different sayings based on icon API output
var icon = data.currently.icon;
switch(icon){
case "clear-day":
var text = "Cryyyssstaaal clear today. No clouds, not even the cloud service is working.";
var icon = "img/SVG/Sun.svg";
break;
case "clear-night":
var text = "Clear night.";
var icon = "img/SVG/Moon.svg";
break;
case "rain":
var text = "You need a shower? Now is your time. It's raining.";
var icon = "img/SVG/Umbrella.svg";
break;
case "snow":
var text = "It's so cold. I'm farting snowflakes.";
var icon = "img/SVG/Snowflakes.svg";
break;
case "sleet":
var text = "Falling ice cream or snow rain. Don't know";
var icon = "img/SVG/Cloud-Snow-Sun-Alt.svg";
break;
case "wind":
var text = "Flying umbrella ahead. WIND!?!?!?!";
var icon = "img/SVG/Wind.svg";
break;
case "fog":
var text = "Fucking Fog...";
var icon = "img/SVG/Shades.svg";
break;
case "cloudy":
var text = "Cloudy with a chance of ...";
var icon ="img/SVG/Cloud.svg";
break;
case "partly-cloudy-day":
var text = "Cloudy, but only above you. Sorry.";
var icon ="img/SVG/Cloud-Sun.svg";
break;
case "partly-cloudy-night":
var text = "Cloudy. Have you looked out the window today?";
var icon ="img/SVG/Cloud-Moon.svg";
break;
case "hail":
var text = "Be aware Golf balls made of ice are flying around.";
var icon = "img/SVG/Cloud-Hail.svg";
break;
case "thunderstorm":
var text = "Thor angry. Thor making noise.";
var icon = "img/SVG/Cloud-Lightning.svg";
break;
case "tornado":
var text = "That's .... have you seen it? That was your neighbours car. A tornado is close.";
var icon = "img/SVG/Tornado.svg";
break;
default:
var text = "no weather found. pls restart...";
var icon = "img/SVG/Compass.svg";
break;
}
$("#text").html(text);
$("#icon").attr("src",icon);
$("#summary").html(textSummary);
if($("#tempSwitch").prop("checked") == true) {
var tempCelsius = ((tempFahrenheit-32)/1.8).toFixed(2);
$("#temperature").html(tempCelsius);
} else {
$("#temperature").html(tempFahrenheit);
}
$("#tempSwitch").change(function() {
if($("#tempSwitch").prop("checked") == true) {
var tempCelsius = ((tempFahrenheit-32)/1.8).toFixed(2);
$("#temperature").html(tempCelsius);
} else {
$("#temperature").html(tempFahrenheit);
}
});
})
};
};
EDIT: HTML Code
<h1>No Bullshit Weather App</h1>
<p>Click the button to check the weather</p>
<p>Alternative: If you have a window and can move your head, look outside to check the weather</p>
<p><button onclick="a()">Show my location</button></p>
<div id="out"></div>
<div id="temperature"></div>
<input id="tempSwitch" type="checkbox" unchecked data-toggle="toggle" data-on="Celsius" data-off="Fahrenheit">
<div id="text"></div>
<div id="summary"></div>
<img id="icon" src="">
you can do somthing like this? I could not test it because the api didnt seem to work on your github page.
var temp;
function checkTemp()
{
//CELCIUS
if($("#tempSwitch").checked)
{
temp = ((tempFahrenheit-32)/1.8).toFixed(2);
}
//FAHRENHEIT
else
{
temp = tempFahrenheit;
}
//SET HTML
$("#temperature").html(temp);
}
//ONCHANGE RUN FUNCTION CHECKTEMP
$("#tempSwitch").change(checkTemp);
//FIRST TIME RUN FUNCTION
checkTemp();
I don't think is a more elegant way but you can try the ternary operator:
tempFahrenheit = 0;
$("#tempSwitch").change(function() {
var checked = $(this).is(":checked")
var tempCelsius = ((tempFahrenheit-32)/1.8).toFixed(2);
$("#temperature").html(checked?tempCelsius:tempFahrenheit);
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tempSwitch" type="checkbox" unchecked data-toggle="toggle" data-on="Celsius" data-off="Fahrenheit">
<div id="temperature"></div>
Related
I'm writing a google sheets add on that helps you track data as you play a game. In the sidebar, you can search for a monster in the game and after you hit the submit button the monster's stats, a list of what items they drop after a kill, and a link to the wiki is rendered on screen.
The problem I'm having is that when you search a new monster after having already searched for one, the old items from the drop section won't get removed. The other sections on stats and the wiki link will change, but instead of removing the old drop items, the new items just get added to the end of the list.
I've tried using parent.removeChild() and childNode.remove() and neither seem to do anything and I'm wondering if its because of how google apps script works.
Here is the html for the sidebar itself: note that include() is a custom function that google recommends you add to your script so you can import other files.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('Info sidebar styles'); ?>
</head>
<body>
<form id="monsters">
<input class="monsterInput" type="text"placeholder="Monster Name" name="monsterName" />
<input class="monsterInput" type="text" placeholder="Monster Level" name="monsterLvl" />
<button id="submit">Search</button>
</form>
<div id="output">
</div>
<?!= include('sidebar script'); ?>
</body>
</html>
Here's the code for sidebar script:
<script>
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready(){
// create the divs that are later filled with info
var output = document.getElementById("output");
var stats = document.createElement("div");
stats.id = "statsDiv";
var drops = document.createElement("div");
drops.id = 'dropDiv';
var list = document.createElement("div");
list.id = "dropList";
var wiki = document.createElement("div");
wiki.id = "wiki";
output.appendChild(stats);
output.appendChild(drops);
output.appendChild(wiki);
var index = 0;
// the onSuccess for the onClick eventHandler. data is an object returned from the function call below
function onSuccess(data) {
console.log(`first index ${index}`);
// if the submit button has already been pushed and added the droplist to the DOM, increase the index
if(drops.getElementsByClassName("dropItem")[0]){
index++;
console.log(`second index ${index}`);
};
console.log(index);
// get the stats
var hitpoints = data.hitpoints;
var attackarray = data["attack_type"]
var attackTypes = '';
var attack1 = attackarray[0];
var attack2 = attackarray[1];
var attack3 = attackarray[2];
var attack4 = attackarray[3];
if(attackarray.length === 1){
attackTypes = attack1;
} else if (attackarray.length === 2){
attackTypes = `${attack1}, ${attack2}`;
} else if (attackarray.length === 3){
attackTypes = `${attack1}, ${attack2}, ${attack3}`;
} else if (attackarray.length === 4){
attackTypes = `${attack1}, ${attack2}, ${attack2}, ${attack4}`;
}
var attLvl = data["attack_level"];
var defLvl = data["defence_level"];
var magicLvl = data["magic_level"];
var rangeLvl = data["ranged_level"];
var maxHit = data["max_hit"];
var aggro = '';
if(data.aggressive){
aggro = "Yes";
} else {
aggro = "No";
}
var speed = data["attack_speed"];
// put the stats into html form
var statsInner =
`<h2> Stats </h2>
<ul id="statsList">
<li>Hitpoints: ${hitpoints}</li>
<li>Attack Level: ${attLvl}</li>
<li>Defense Level: ${defLvl}</li>
<li>Magic Level: ${magicLvl}</li>
<li>Ranged Level: ${rangeLvl}</li>
<li>Attack Style: ${attackTypes} </li>
<li>Attack Speed: ${speed}</li>
<li>Max Hit: ${maxHit} </li>
<li>Aggressive? ${aggro} </li>
</ul>`;
stats.innerHTML = statsInner;
drops.innerHTML = '<h2>Drops</h2>';
// Put the wiki url into HTML
var wikiURL = data["wiki_url"];
var wikiInner = `<p>For more info check out this monsters page on the wiki, <a href=${wikiURL}>here</a>.</p>`;
wiki.innerHTML = wikiInner;
// get the drop information and put it in html form. make the data-id attribute of each object equal the value of index
data.drops.forEach(function (item) {
var name = item.name;
var quant = item.quantity;
var members = '';
if(item.members){
members = "(m)";
}
var nameQM = `${name} (x${quant}) ${members}`;
var rarity = (item.rarity) * 100;
var rare = rarity.toFixed(2);
var nameNode = document.createElement("div");
var itemList =
`<p>${nameQM}</p>
<br>
<p> Rarity: ${rare} percent </p>`;
nameNode.innerHTML = itemList;
nameNode.className = "dropItem";
nameNode.dataset.id = index;
list.appendChild(nameNode);
})
drops.appendChild(list);
// if the drop item has a data-id that doesn't match the current index, remove it from the DOM.
var dropArray = list.getElementsByClassName("dropItem");
for(var i = 0; i < dropArray.length; i++){
var item = dropArray[i];
if(item.dataset.id != index){
item.remove();
}
}
}
//add the event listener to the submit button. getMonsterData makes an API call, parses the data, and returns an object filled with the data we add to the DOM through the success handler
document.getElementById("submit").addEventListener("click", function (e) {
e.preventDefault();
var parent = e.target.parentElement;
var monsterName = parent.elements[0].value;
var monsterlvl = parent.elements[1].value;
google.script.run.withSuccessHandler(onSuccess).getMonsterData(monsterName, monsterlvl);
});
}
</script>
var deviceName = '';
if(deviceName == 'sampleOne'){
newName = 'One'
}
if(deviceName == 'sampleTwo'){
newName = 'Two'
}
if(deviceName == 'sampletThree'){
newName = 'Three'
}
I have this simple if statement for Javascript.
How it works?
When a data inputed is sampleOne the output will be One. That's it, very simple right?
Take note that this code is working fine. But my problem is I have so many sample and I think using this kind of If statement is a bad idea because it will be too long. Is there a way to shorten this if statament?
If you have a lot of these you can make an object that maps the deviceName to the newName. Then you can just look it up:
let lookup = {
'sampleOne': 'One',
'sampleTwo': 'Two' ,
'sampleThree': 'Three'
}
let deviceName = 'sampleTwo'
let newname = lookup[deviceName]
console.log(newname)
You can use switch statement:
var deviceName = 'sampleFour';
var newName;
switch (deviceName) {
case 'sampleOne':
newName = 'One';
break;
case 'sampleTwo':
newName = 'Two';
break;
case 'sampleThree':
newName = 'Three';
break;
case 'sampleFour':
newName = 'Four';
break;
case 'sampleFive':
newName = 'Five';
}
console.log(newName);
var deviceName = "sampleOne";
newName =deviceName.split('sample')[1];
console.log(newName );
If your value starts with sample just use this logic
You can use switch statement. Find an example below:
<html>
<body>
<input id="myInput" type="text">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text;
var deviceName = document.getElementById("myInput").value;
switch(deviceName ) {
case "sampleOne":
text = "One";
break;
case "sampleTwo":
text = "Two";
break;
case "sampletThree":
text = "Three";
break;
default:
text = "No Match";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You can also use a Switch instead of IF condition. Switch can be used if you want to do multiple operations in conditions.
var deviceName = 'sampleOne';
switch(deviceName)
{
case 'sampleOne':
newName = 'One';
break;
case 'sampleTwo':
newName ='Two';
break;
case 'sampleThree':
newName ='Three';
break;
default:
break;
}
//id define
var id = function (name) {
return{
element : document.getElementById(name),
html : function (data) {
var ids = this.element;
if (data != undefined) {ids.innerHTML=data;}
else{return ids.innerHTML;}},
val : function (data) {
var ids = this.element;
if (data != undefined) {ids.value=data;}
else{return ids.value;}},
hide : function () {this.element.style.display="none";},
show : function () {this.element.style.display="block";},
clsremove : function (data) {this.element.classList.remove(data);},
clsadd : function (data) {this.element.classList.add(data);},
tex : function (data) { var latex = data.replace(/\^/g, "");
var latex_form = latex.replace(/([a-z])(\d+)/g,
function myFunction(tot,c1,c2) {var tag=(c1 =='^'?'sup':'sup');return c1+'<'+tag+'>'+c2+'</'+tag+'>';});
this.element.innerHTML= latex_form;
}
}
}
//class define
var cls = function (name) {
return{
element : document.getElementsByClassName(name),
html : function (data) {
var ids = this.element;
for (var i=0; i<ids.length; i++) {
if (data != undefined) {ids[i].innerHTML=data;}
else{return ids[i].innerHTML;}}},
val : function (data) {
var ids = this.element;
for (var i=0; i<ids.length; i++) {
if (data != undefined) {ids[i].value=data;}
else{return ids[i].value;}}},
hide : function () { var ids = this.element;for (var i=0; i<ids.length; i++) {ids[i].style.display="none";}},
show : function () {var ids = this.element;for (var i=0; i<ids.length; i++) {ids[i].style.display="block";}},
tex : function (data) { var latex = data.replace(/\^/g, "");
var latex_form = latex.replace(/([a-z])(\d+)/g,
function myFunction(tot,c1,c2) {var tag=(c1 =='^'?'sup':'sup');return c1+'<'+tag+'>'+c2+'</'+tag+'>';});
this.element.innerHTML= latex_form;
}
}
}
<!DOCTYPE html>
<html>
<head>
<script src="jfile/myquery.js"></script>
<script src="steps.js"></script>
</head>
<body>
<input id="myInput" type="text" value="20x+5k-10p-y=0">
<button onclick="checkFruit()">Check Fruit</button>
<p id="equ1"></p>
<p id="equ2"></p>
<p id="equ3"></p>
<p id="equ4"></p>
<p id="equ5"></p>
<p id="equ1p"></p>
<p id="equ2p"></p>
<p id="equ3p"></p>
<p id="equ4p"></p>
<p id="equ5p"></p>
<p id="xoneans1"></p>
<p id="xoneans2"></p>
<p id="xoneans3"></p>
<p id="xoneans4"></p>
<p id="xoneans5"></p>
<p id="xoneans6"></p>
<p id="xoneans7"></p>
<p id="xoneans8"></p>
<p id="xoneans9"></p>
<p id="xoneans10"></p>
<script>
function checkFruit() {
var reg =/([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var equation = id("myInput").val();
var spli= reg.exec(equation);
alert(spli);
var text;
var y= document.getElementById("myInput").value;
switch(y) {
case "20x+5k-10p-y=0":
ans = "First add both side for -20";
ans1= "Both side added by 10p";
ans2= "Next both side added by y";
ans3= "Divide by both side 5";
ans4= "Solution for k value";
document.getElementById("equ1").innerHTML = ans;
document.getElementById("equ2").innerHTML = ans1;
document.getElementById("equ3").innerHTML = ans2;
document.getElementById("equ4").innerHTML = ans3;
document.getElementById("equ5").innerHTML = ans4;
break;
case "20x+5k-10p-y=0p":
ans5p = "First add both side for -20";
ans6p= "Both side added by -5k";
ans7p= "Next both side added by y";
ans8p= "Divide by both side -10";
ans9p= "Solution for p value";
document.getElementById("equ1p").innerHTML = ans5p;
document.getElementById("equ2p").innerHTML = ans6p;
document.getElementById("equ3p").innerHTML = ans7p;
document.getElementById("equ4p").innerHTML = ans8p;
document.getElementById("equ5p").innerHTML = ans9p;
break;
case "20x+5k-10p-y=0x":
xone1 = "First add both side for -5";
xtwo2= "Both side added by 10p";
xthr3= "Next both side added by y";
xfour4= "Divide by both side 20";
xfive5= "Solution for x value";
document.getElementById("xoneans1").innerHTML = xone1;
document.getElementById("xoneans2").innerHTML = xtwo2;
document.getElementById("xoneans3").innerHTML = xthr3;
document.getElementById("xoneans4").innerHTML = xfour4;
document.getElementById("xoneans5").innerHTML = xfive5;
break;
case "20x+5k-10p-y=0y":
xone6 = "First add both side for -20";
xtwo7= "Both side added by -5k";
xthr8= "Next both side added by 10p";
xfour9= "Divide by both side -1";
xfive10= "Solution for y value";
document.getElementById("xoneans6").innerHTML = xone6;
document.getElementById("xoneans7").innerHTML = xtwo7;
document.getElementById("xoneans8").innerHTML = xthr8;
document.getElementById("xoneans9").innerHTML = xfour9;
document.getElementById("xoneans10").innerHTML = xfive10;
break;
// add the default keyword here
}
}
</script>
<p id="super"></p>
</body>
</html>
I have some code in the linear equation steps. How can I allow the user to open the drop-down list, and select a single letter, for which my code will then show the corresponding algorithm steps?
For example, I would like to display the menu
[x
y
z
p]
from that button, the user selects x, and my code should display the steps listed in the switch case for x.
I'm currently working on a digital assistant website which is based around JavaScript and jQuery. The user can type in questions or tell the assistant things into the textbox and the assistant will respond with something relevant to the input. What I am planning to implement is to check if the textbox contains a number (intager) and if it does some sort of function will run. The concept sounds fairly simple and but I am having trouble. I have been searching around for a bit but I can't seem to find anything which will work with my code.
I will add my JavaScript and the nessacary parts of the HTML. But I am warning you, the code is messy.
JavaScript:
// JavaScript Document
function submitted() {
var srch = document.getElementById("srch");
command();
getPlaceHolder();
srch.value = "";
}
function searchKeyPress(e) {
e = e || window.event;
if (e.keyCode == 13) {
//document.getElementById('btn').click();
submitted();
}
}
function goBtn() {
submitted();
}
function refreshBtn() {
getWelcome();
}
function stClock() {
window.setTimeout("stClock()", 1000);
today = new Date();
self.status = today.toString();
}
function getWelcome() {
var ar = new Array(20)
ar[0] = "What's on your mind?";
ar[1] = "How can I help?";
ar[2] = "Anything you need help with?";
ar[3] = "Ask me anything";
ar[4] = "What can I help you with?";
ar[5] = "What would you like me to do?";
ar[6] = "What can I do for you?";
ar[7] = "Need help with anything?";
ar[8] = "Need someone to talk to?";
ar[9] = "I'm here to help";
ar[10] = "Anything you need to know?";
ar[11] = "How else can I help?";
ar[12] = "What can I do now?";
ar[13] = "Need anything?";
ar[14] = "Any problems you need solving?";
ar[15] = "Hello, how do you do?";
ar[16] = "Hi there";
ar[17] = "Hi, I'm aurum";
ar[18] = "Hello there";
ar[19] = "How do you do?";
var now = new Date();
var sec = now.getSeconds();
document.getElementById('output').innerHTML = ar[sec % 20];
}
function getPlaceHolder() {
var ar = new Array(20)
ar[0] = "What's on your mind?";
ar[1] = "How can I help?";
ar[2] = "Anything you need help with?";
ar[3] = "Ask me anything";
ar[4] = "What can I help you with?";
ar[5] = "What would you like me to do?";
ar[6] = "What can I do for you?";
ar[7] = "Need help with anything?";
ar[8] = "Need someone to talk to?";
ar[9] = "I'm here to help";
ar[10] = "Anything you need to know?";
ar[11] = "How else can I help?";
ar[12] = "What can I do now?";
ar[13] = "Need anything?";
ar[14] = "Any problems you need solving?";
ar[15] = "Hello, how do you do?";
ar[16] = "Hi there";
ar[17] = "Hi, I'm aurum";
ar[18] = "Hello there";
ar[19] = "How do you do?";
var now = new Date();
var sec = now.getSeconds();
document.getElementsByName('srch')[0].placeholder=ar[sec % 20];
}
function command() {
var srchVar = document.getElementById("srch");
var srch = srchVar.value;
var t = srch;
var outputElement = document.getElementById('output');
if (srch == '') {
outputElement.innerHTML = "How can I help you, if you don't say anything?";
}
else if (srch.indexOf('about') != -1) {
outputElement.innerHTML = "Hello, I'm Aurum. I was designed by Omar Latreche to help people answer their questions. However, I also like to talk to people aswell as answer their questions.";
}
else if (srch.indexOf('time') != -1) {
outputElement.innerHTML = 'The current time according to your computer is' + ShowTime(new Date());
}
else {
if (confirm("I am sorry but for some reason I don't understand. You could either repeat that or would you like to search Google for that instead?") == true) {
window.open('https://www.google.co.uk/#q=' + srch, '_blank');
}
else { /* Nothing */ }
}
}
//Show time in 12hour format
var ShowTime = (function() {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function(dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
}
return formatted;
};
})();
And the HTML:
<!DOCTYPE html>
<html>
<body onload="getWelcome(); getPlaceHolder();">
<div class="output" id="output">
An error has occoured. Please make sure you have JavaScript enabled in your browser.
</div>
<div class="cont">
<div class="ui-widget">
<div class="search-cont">
<input class="search-field" id="srch" name="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false"> <input class="refresh" onclick="refreshBtn()" title="Refresh the conversation" type="button"> <input class="go" onclick="goBtn()" type="button">
</div>
</div><br>
</div>
</body>
</html>
I really appreciate any help provided. Thanks, Omar.
PS. I apologies for the long paragraph but that is the only way I could think to explain what I need.
PPS. If you need any more information on my project just incase, the URL is http://omarlatreche.tk/aurum/
This is the function I came up with to check for number:
function checkNum() {
text = document.getElementById('srch').value;
valArr = document.getElementById('srch').value.split(' ');
for (i = 0; i < valArr.length; i++) {
if (isNaN(valArr[i])==false) {
alert("Number found");
}
}
}
Here is the JSFiddle demo
I called the function in the goBtn() function.
can you explain this line?
document.getElementById('output').innerHTML = [0].innerHTML=ar[sec % 20];
shouldn't it be
document.getElementById('output').innerHTML = ar[sec % 20];
I have this script:
<script>
function $(id) {
return document.getElementById(id);
}
function getImage() {
$('loader').src='/misc/images/loading.gif';
var url = "http://mousecreator.com/";
// outfit
var head = "&head="+$('head').value;
var ears = "&ears="+$('ears').value;
var eyes = "&eyes="+$('eyes').value;
var mouth = "&mouth="+$('mouth').value;
var neck = "&neck="+$('neck').value;
var ears = "&ears="+$('ears').value;
var hair = "&hair="+$('hair').value;
var fur = "&fur="+$('fur').value;
var tail = "&tail="+$('tail').value;
// sham
if(document.sh.sham.checked)
var sham = "&sham=1";
else
var sham = "";
//alert(document.sh.sham.checked);
var murl = url +"mouse.php?" + head + ears + eyes + mouth + neck + ears + hair + fur + tail + sham;
// set the preview image and text box
$('prem').src=murl;
}
function remLoad() {
$('loader').src="";
}</script>
<select id="head">
<option value="235">Value 1</option>
<option value="324">Value 2</option>
...
...
<button onclick="getImage()">Generate</button>
Is there any way to make a button to randomly pick id's from all the drop-down lists at the same time when clicking the Generate button? Every id (head, ears, eyes, etc. has it's own droplist)
Thanks in advance!
function randomItemFrom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function randomOptionFrom(select) {
return randomItemFrom(select.options);
}
var randomEye = randomOptionFrom($('#eyes')[0]).value;
You could also make the randomOptionFrom function accept jQuery objects or selectors.
function randomOptionFrom(select) {
return randomItemFrom($(select)[0].options);
}
Then you can call it like:
randomOptionFrom($('#eyes')).value;
or
randomOptionFrom('#eyes').value;