pick random value from a drop-down list - javascript

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;

Related

JS doesn't detected when I change Option, Variable keeps undefined

I'm trying to generate an automatic email address, based on user change.
The point is to print the domain name, the rest is working fine.
here is my issue, I'm getting the element ID, if the element ID the Var x takes the values of an other var depending on the selection however, X keeps undefined.
I think that somehow it doesn't detect when I select an other option.
Any kind of help will be much appreciated.
<select name="select" id="selecto">
<option value="">--Please choose an option--</option>
<option value="value1" id="1">SEE</option>
<option value="value2" id = "2">Guillebert</option>
<option value="value3" id = "3">Saelen</option>
<option value="value4" id ="4">SEE Produktion</option>
<option value="value5" id ="5">TS-Industrie</option>
<option value="value6" id="6">Schliesing</option>
</select>
<script type="text/javascript">
var a = "#groupesee.com";
var b = "#guillebert.fr";
var c = "#saelen.fr";
var d = "#see-produktion.net;"
var e = "#ts-industrie.de";
var g = "#schliesing.net";
var x;
if(document.getElementById('selecto').value == "value1") {
x = a;
alert("Success");
}
</script>
For some reason, and I do not understand why, the var x, is keeping null even if I select the value1 in my form.
<script>
$("#field1, #field2").keyup(function(){
update();
});
function update() {
$("#result").val($('#field1').val().substr(0,1).toLowerCase() + $('#field2').val().toLowerCase()+x);
}
</script>
Result
Your code just runs as it loads. It only checks the value of the select element once (as the page loads and the script element is executed).
If you want it to run every time the select element is changed, then you need to say so.
Put your code in a function
Find the select element in the DOM
Listen for the value to change and call the function
Here is the fix, using the in the Update function. :) Tyvm #Quentin
function update() {
var a = "#groupesee.com";
var b = "#guillebert.fr";
var c = "#saelen.fr";
var d = "#see-produktion.net;"
var e = "#ts-industrie.de";
var g = "#schliesing.net";
var x;
var elt = document.getElementById(selecto);
if(document.getElementById('selecto').value == "value1") {
x = a;
} if(document.getElementById('selecto').value == "value2") {
x = b;
}
if(document.getElementById('selecto').value == "value3") {
x = c;
}
if(document.getElementById('selecto').value == "value4") {
x = c;
}
if(document.getElementById('selecto').value == "value5") {
x = c;
}
if(document.getElementById('selecto').value == "value6") {
x = c;
}
$("#result").val($('#field1').val().substr(0,1).toLowerCase() + $('#field2').val().toLowerCase()+x);
}

JQuery - more elegant coding solution for checking button state

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>

Create an array of external html pages and shuffle it into several divs

I'm currently working on a site that consists in a grid of divs (4x4) into which a set of texts have to be shuffled at each reload. This basically looks like this at the moment.
My index.htm reads :
<div class="container">
<div class="colonne">
<div class="case">
<span class="boxwatermark">1</span>
<span class="case1">
</span>
</div>
<div class="case">
<div class="boxwatermark">5</div>
<span class="case5">
</span>
</div>
<div class="case">
<div class="boxwatermark">9</div>
<span class="case9">
</span>
</div>
...
and so on up to 15 (16 remains empty).
The set of texts that I need to be distributed into the boxes (boxes = divs with classnames "case+number") are each in a separate html file (named "case1.html", "case2.html" etc.). I would like these html files to constitute the array, and this array to be shuffled "randomly" into each box.
I tried several things for the past two days, but the solution to this problem seems presently to exceed my (little) competences... I've been impressed by some of the attention given to such questions on this forum and decided to request your help. Thanks !
Try using Array.prototype.slice(), Array.prototype.splice() , .eq() , .each() , .load()
$(function() {
var c = "case";
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var copy = arr.slice(0);
$("." + c).each(function() {
var curr = copy.splice(Math.floor(Math.random() * copy.length), 1)[0];
$(this).load(c + curr + ".html")
})
})
plnkr http://plnkr.co/edit/rAhq6fkbUqM3BfnahAVy?p=preview
try this https://fiddle.jshell.net/
var shuffle = function (htmls) {
for (var j, x, i = htmls.length; i; j = parseInt(Math.random() * i), x = htmls[--i], htmls[i] = htmls[j], htmls[j] = x);
return htmls;
};
var display = function (shuffledArray) {
var index = 0;
for (var spot in shuffledArray) {
index++;
var cssClass = '.case' + index;
var div = document.querySelector(cssClass);
div.innerHTML = shuffledArray[spot];
}
}
if (!sessionStorage.getItem('htmlFiles')) {
var htmls = [];
htmls[0] = 'this a text for example';
htmls[1] = 'Another text for example';
htmls[2] = 'Yet anohter text for example';
htmls[3] = 'The texts keep up comming';
htmls[4] = 'More example texts here';
htmls[5] = 'Even more texts';
htmls[6] = 'The last example';
sessionStorage.setItem('htmlFiles', htmls);
}
var htmls = sessionStorage.getItem('htmlFiles').split(',');
var shuffledArray = shuffle(htmls);
display(shuffledArray);

Update dynamically generated price of two boxes with select option

I am trying to make this work with the help of jQuery docs but not success so far.
I have two boxes paynow and payfull that has 0 initial value but I am filling these boxes dynamically (jQuery) with product prices.
Now I have to update these values further with select option to discount the price (multiply with data-percent). This is the HTML.
<select class="discount">
<option data-percent="0">Select Discount Coupon</option>
<option data-percent="5">ABCD</option>
<option data-percent="10">EFGH</option>
<option data-percent="15">IJKL</option>
</select>
<span class="price" id="paynow">$0.00</span>
<span class="price" id="payfull">$0.00</span>
EDIT: jQuery code
$(document).ready(function() {
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
How about this one:
var totalPayNowPrice=parseFloat($('#paynow').text());
var totalPayFullPrice=parseFloat($('#payfull').text());
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
});
Just put the $ sign in you spans after the numbers, in order to parse function would work.
JSFIDDLE
UPDATE
From another point I think there is a better solution to use prototype and store you current prices in spans inside global variable, then you can use them wherever you want. Here the pseudo prototype for your use, if you`d like just customize it for you using:
function Test(){
this.totalPayNowPrice=1;//the is 1 only for check code working
this.totalPayFullPrice=1;
}
Test.prototype={
init: function(){
var scope=this;
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((scope.totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((scope.totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
},
updatePaynowPrice:function(newPrice){
this.totalPayNowPrice=totalPayNowPrice;
},
updatePayfullPrice:function(newPrice){
this.totalPayFullPrice=totalPayNowPrice;
}
}
you can use
$(document).ready(function(){
// get price from #paynow (just a number)
var getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
var getPayfull = $('#payfull').text().match(/\d+/);
$('.discount').on('change', function(){
// get data-percent from selected option
var discount = parseFloat($(this).find('>option:selected').attr('data-percent'));
//alert(discount +'///'+ getPaynow+'///'+ getPayfull);
//update price for #paynow and #payfull
$('#paynow').text('$'+parseFloat(getPaynow - (getPaynow * discount / 100)));
$('#payfull').text('$'+parseFloat(getPayfull - (getPayfull * discount / 100)));
});
});
Working Demo
in your code you can update prices after this part of code
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
//get price from #paynow (just a number)
getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
getPayfull = $('#payfull').text().match(/\d+/);

Sort a list by Days of the week

I have created a list of items that contains information such as a taskname (i.e. take out the garbage), who must do the task, and what day of the week the task needs to be done by. All this information is gathered through text inputs in the html, then displayed as a list item using JavaScript.
Im wondering if there is a simple way to sort my list by the day of the week the task needs to be done. I was thinking perhaps i should add numerical value of 1-7 to strings containing days of the week. (for instance one that contains monday would have a value of 1, ones that have sunday have a value of 7). Then i could sort these numerically.
If anyone could show me how to do this with JavaScript (not jQuery), or an easier way, that would be greatly appreciated. (The more comments in the code the better).
Thanks
//links html elements to corresponding javascript variable names
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function(taskText, personText, dayText){
var self = this;
self.name="taskName";
self.listItem;
self.init = function(){
//create html elements
self.listItem = document.createElement("li");
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + " ";
//create text box and have it display information from the previous inputed person
var text2 = document.createElement("text");
text2.innerText = personText + " ";
//create text box and have it display information from the previous inputed day of the week
var text3 = document.createElement("text");
text3.innerText = dayText + " ";
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(text2);
self.listItem.appendChild(text3);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild (self.listItem);
}
self.deleteMe = function(){
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function (){
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
There is an in-built javascript function that helps in getting the day of the week.
//Calling the date function
var date = new Date();
//Getting the day of the week
var day_of_week = date.getDay();
date.getDay() returns a value from 0 to 6 for sunday to saturday respectively
//A function to get the day of the week
function dayOfTheWeek()
{
var date = new Date();
var day_of_week = date.getDay();
switch (day_of_week)
{
case 0: return "sunday"
case 1: return "monday"
case 2: return "tuesday"
case 3: return "wednessday"
case 4: return "thursday"
case 5: return "friday"
default: return "saturday"
}
}
//Calling the function
var day_of_week_in_string = dayOfTheWeek();
(javascript)
//define your task objects as an array (outside of TaskObject)
var tasks = [];
//retrieve a number rather than a text value
var dayInput = document.getElementById('dayInput').selectedIndex
var newTask = ...
//add this task object to the Task array
tasks.push(newTask)
//now you can sort the array:
tasks.sort(function(a, b){return a.dayInput-b.dayInput});
(html)
<select id="dayInput">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
<option value="3">Thursday</option>
<!-- etc.. -->
</select>
Here is my solution to your problem. When a new li is created, you store a hidden attribute called "data-day-text" and attach it to the li. When you sort, you remove the ul from the DOM (for performance gains), sort the lis according to the data-day-text, then re-attach the lis and the ul.
http://jsfiddle.net/g3et9abh/3/
html:
<div id="allTasksContainer">
<ul id="allTasks"></ul>
</div>
<p>task:
<input type="text" id="taskInput" />
</p>
<p>person:
<input type="text" id="personInput" />
</p>
<p>day:
<input type="text" id="dayInput" />
</p>
<button id="addBtn">add</button>
<button id="sortBtn">sort</button>
javascript:
//links html elements to corresponding javascript variable names
var allTasksContainer = document.getElementById('allTasksContainer');
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function (taskText, personText, dayText) {
var self = this;
self.name = "taskName";
self.listItem;
self.init = function () {
//create html elements
self.listItem = document.createElement("li");
self.listItem.dataset.dayText = dayText;
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + ' ' + personText + ' ' + dayText;
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild(self.listItem);
}
self.deleteMe = function () {
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function () {
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
sortBtn.onclick = function () {
allTasksContainer.removeChild(allTasks);
var nodes = [].slice.call(allTasks.getElementsByTagName('li'), 0);
[].sort.call(nodes, function (a, b) {
return b.dataset.dayText < a.dataset.dayText ? 1 : b.dataset.dayText > a.dataset.dayText ? -1 : 0;
});
while (allTasks.firstChild) {
allTasks.removeChild(allTasks.firstChild);
}
nodes.forEach(function (node) {
allTasks.appendChild(node);
});
allTasksContainer.appendChild(allTasks);
}

Categories