The function is not running well while using a global variable - javascript

I am trying to make a probability finder to take some random numbers and find the probability of a number from the array of random numbers. I have the following code :
/*********************Select Random Number**********************/
//Number of cases
var nOC = document.getElementById("noc").value;
function rollDice() {
//Number of trials
let nOT = document.getElementById("not").value;
//Empty Array to be filled
let array = [];
//Loop which pushes random numbers in the empty array
for (let i = 1; i <= nOT; i++) {
array.push(Math.ceil(Math.random() * nOC));
}
//Display results in a paragraph
document.getElementById("para").innerHTML = "Your random numbers are " + array;
}
/*********************Get Probability**************************/
function getProbabilityOf() {
//Probability of...
let oP = document.getElementById("op").value;
//Check if the number is out of range. If no, then find the probability of given number
if (oP >= noC) {
alert("This number is out of the range of possible outcomes that you have selected in step 1");
} else {
//Some code here
}
}
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr/>
<p>With our probability finder, you can easily choose the number of possible cases and select the number of times you want to select a random case each time from the total cases and finally find the empirical probability of and case you want from the selected
total number of cases.</p>
<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
<select id="noc">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
<select id="not">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
<button onclick="rollDice()">Get random numbers</button>
<p id="para"></p>
<!----------------------------Step 4----------------------------->
<h3><span class="bold">Step 4 :</span>Get probability of a particular number</h3>
<select id="op" onchange="getProbabilityOf()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Before declaring the second function, nOC was declared local to function rollDice. But after I declared the next function, I needed to access it to complete step 4 (as mentioned in the code snippet). So I removed the variable nOC from the function and declared it globally(as shown in the code snippet).
The problem is that after declaring the variable as a global variable, none of the function was able to access it.
To resolve this problem, I rechecked the syntax many times but found no problems with it (as per my knowledge). I tried changing the type of the variable from let to var and const but still, the problem was not solved.
What could be the problem? As a new newbie in the field of coding, I know that small mistakes are made by me, but it is very important for me to know my mistakes and fix them.

It's generally not a good idea to use inline event handlers.
The error stems from the inline handlers. onchange="getProbabilityOf()" executes when the document renders. So after the page is loaded the onchange attribute will have the value of whatever result getProbabilityOf() returned. That won't be a javascript function I suspect.
Here are a few modifications to your code, making it work (technically). I have not checked if it's the right output, it's just some technical adjustments. Now you can use that as a base to continue your efforts.
About event delegation...
Not related to the code, but to 'number of cases' and for fun: What's a sample of size one worth?
// store a reference to #noc
const nOC = document.querySelector("#noc");
// add event handlers (event delegation)
document.addEventListener("click", rollDice)
document.addEventListener("change",
evt => {
if (evt.target.id === "op") {
return getProbabilityOf();
}
});
function rollDice(evt) {
if (evt.target.tagName !== "BUTTON") { return; }
//Number of trials
const nOT = +document.querySelector("#not").value;
const nocValue = +nOC.value;
// ^ retrieve #nOC value here
//Empty Array to be filled
let array = [];
//Loop which pushes random numbers in the empty array
for (let i = 1; i <= nOT; i += 1) {
array.push( Math.ceil(Math.random() * nocValue));
}
//Display results in a paragraph
document.querySelector("#para").innerHTML = `Your random numbers are ${array}`;
}
/*********************Get Probability**************************/
function getProbabilityOf() {
//Probability of...
const oP = +document.querySelector("#op").value;
//Check if the number is out of range. If no, then find the probability of given number
if (oP >= +nOC.value) {
// ^ determine #nOC value here
alert("This number is out of the range of possible outcomes that you have selected in step 1");
} else {
//Some code here
}
}
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr/>
<p>With our probability finder, you can easily choose the number of possible cases and select the number of times you want to select a random case each time from the total cases and finally find the empirical probability of and case you want from the selected
total number of cases.</p>
<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
<select id="noc">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
<select id="not">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
<button>Get random numbers</button>
<p id="para"></p>
<!----------------------------Step 4----------------------------->
<h3><span class="bold">Step 4 :</span>Get probability of a particular number</h3>
<select id="op">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>

Actually your script uses a DOM element and therefore must run after the DOM is loaded. You can do just use script just before closing body tag:
<!DOCTYPE html>
<html>
<head>
<title>Probability Finder</title>
</head>
<body>
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr />
<p>
With our probability finder, you can easily choose the number of possible
cases and select the number of times you want to select a random case each
time from the total cases and finally find the empirical probability of
and case you want from the selected total number of cases.
</p>
<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
<select id="noc">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
<select id="not">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
<button onclick="rollDice()">Get random numbers</button>
<p id="para"></p>
<!----------------------------Step 4----------------------------->
<h3>
<span class="bold">Step 4 :</span>Get probability of a particular number
</h3>
<select id="op" onchange="getProbabilityOf()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<script>
/*********************Select Random Number**********************/
//Number of cases
var nOC = document.getElementById('noc')
function rollDice () {
//Number of trials
let nOT = document.getElementById('not').value
//Empty Array to be filled
let array = []
//Loop which pushes random numbers in the empty array
for (let i = 1; i <= nOT; i++) {
array.push(Math.ceil(Math.random() * parseInt(nOC.value, 10)))
}
//Display results in a paragraph
document.getElementById('para').innerHTML =
'Your random numbers are ' + array
}
/*********************Get Probability**************************/
function getProbabilityOf () {
//Probability of...
let oP = document.getElementById('op').value
//Check if the number is out of range. If no, then find the probability of given number
if (oP >= parseInt(nOC.value, 10)) {
alert(
'This number is out of the range of possible outcomes that you have selected in step 1'
)
} else {
//Some code here
}
}
</script>
</body>
</html>

Related

Jquery multiply and add span and dropdown values

I am trying to compute the total price of items in a cart in Javascript. This is by multiplying the quantity by the unit price and then getting the grand total.
The cart is populated by a PHP while loop so I am using class names.
The quantity field is a dropdown/select and the price field is a span.
function sum() {
var sum = 0;
var q = 0;
var s = 0;
$('.itPrice,.qtys').each(function() {
q = $('.qtys').text() || 0; //quantity
s = $('.itPrice').text() || 0; //unit price
sum = sum + (q * s);
});
//display total
$("#sumT").text(sum);
}
<!-- inside PHP while loop -->
<label>Price: </label>
<span class="itPrice"><b>'.$row["price"].'</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<span id="sumT" name="sumT">*sum goes here*</span>
The output is NaN (Not a Number). Where am I going wrong? There is also a problem with the HTML select, it's not picking the selected option, only working with option '1'.
You can select both related elements, as two collections of object, an iterate one collection (while using the array index to refer to the other); that way you can get the quantity and the price.
To get a select selected element, use jquery val() function instead of text();
As a side note, you should not use duplicate id's or names for inputs in yout html. If you want an input with the same name, you can use qty[] for example.
function sum() {
var sum = 0, // Total sum
it = $('.itPrice'), // All the .itPrice elements
qty = $('.qtys'); // All the .qtys elements
// For each .itPrice element
it.each(function(i, e) {
var current = $(this), // Gets the current .itPrice element
related = $(qty[i]); // Get the related .qtys element, by array index
// Sum
sum += Number(current.find('b').text()) * related.val();
});
// return total
return sum;
}
$('#calc').click(function() {
console.log(sum());
});
console.log(sum());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Price: </label>
<span class="itPrice"><b>100</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<br>
<br>
<label>Price: </label>
<span class="itPrice"><b>200</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<br>
<br>
<a id="calc" href="javascript:;">Get total</a>

How to manipulate loops with input?

i got a for loop and i would like to manipulate the counter i with a input on screen. Below i can select from 1 to 10 and i want this selection to get replaced by the counter in the loop. That means when i choose 2, then i should be 2. I started with the code below, but document.getElementById('options').innerHTML = "i"; seems to be the wrong code to manipulate. Thanks so much for your help!
<select id="options" size="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
for (i=0, i<someArray; i++){
do somethingWith[i];}
document.getElementById('options').innerHTML = "i";
You need to get the value of the select element and assign that to i.
var i = document.querySelector('#options').value;
for(i < someArray; i++){
//code
}
Add this to HTML
<select onChange="doWork(this)">
In Js
function doWork(obj){
obj.innerHTML = obj.value
}
If want to do some thing on selection, use onchange method with select to trigger a function every time you are selecting an option.
<select id="options" size="1" onchange="myFunction()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<p id="demo"></p>
<script>
function myFunction() {
var selectedValue = document.getElementById("options").value;
var somethingWith = [];
for (i=0; i < selectedValue; i++){
somethingWith.push(i);
}
document.getElementById('demo').innerHTML = somethingWith;
}
</script>
But if you only want to dynamically select an option in select tag, this might help
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
<button type="button" onclick="myFunction()">banana</button>
<script>
function myFunction() {
document.getElementById("mySelect").value = "banana";
}
</script>

How to count days range by name between two input select in Java Script?

is here some solutions how to count days between two select input only by day name of week with JavaScript? Or some demo in jsfiddle?
Example:
I Have two select tag inputs:
<select>
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<select>
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<input type="text" name="c_days">
If user select Friday in the first one and the Monday in the second one (its been result 3 days), should calculate the total number of days between the first and second select and put counted valuee into c_days input.
Thank for idea!
function updateResult() {
// Get selections.
var firstValue = parseInt(document.querySelector('#firstMenu').value);
var secondValue = parseInt(document.querySelector('#secondMenu').value);
// Calculate difference. If < 0, add 7 days.
var difference = secondValue - firstValue;
if (difference < 0) difference += 7;
// Add value to input
document.querySelector('#c_days').value = difference;
}
window.onload = function() {
// Append functions to drop down menus.
document.querySelector('#firstMenu').addEventListener('change', updateResult);
document.querySelector('#secondMenu').addEventListener('change', updateResult);
};
<select id="firstMenu">
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<select id="secondMenu">
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<input type="text" name="c_days" id="c_days" value="0">

How can I limit selected options in select element when using shift key

HTML
<select id="my-select" multiple="multiple" size="8" style="width:200px">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
JQUERY
$('#my-select option').on('click',function(){
var count = $('#my-select').find('option:selected').length;
$('#dg').html(count);
if(count>10){
$(this).attr('selected',false);
alert('limit 10');
}
});
http://jsfiddle.net/LxNMm/
When you click on the options, calculate count of selected options and limit it to 10, but if you click on the options with pressing shift key and select a range, selection could be greater than 10. How can a detect count of selected options when select a range with pressing shift key
You can try updating the values this way:
$('#my-select').on('change', function () {
var count = $(this).find('option:selected').length;
$('#dg').html(count);
if (count > 10) {
$('option:gt(9)', this).attr('selected', false);
count = $(this).find('option:selected').length;
$('#dg').html(count);
alert('error');
}
});
Your updated demo fiddle
Don't use the click event of the <option />s but the change event of the <select />
$('#my-select').on('change', function () {
var count = $(this).find('option:selected').length;
$('#dg').html(count);
if (count > 10) {
$(this).find("option").prop('selected', false);
alert('error');
}
})
fiddle

javascript out update onchange

I'm trying to get the javascript below to automatically update the input field (centimeters) below when a user select there height and inches. It should auto calculate the centimeters, and its not working.
<script type=​"text/​javascript">​
updateHeights:function(type){
if(type=='english'){
var feet=parseInt($F('feet'));
var inches=parseInt($F('inches'));
var cm=((feet*12+inches)*2.54).round();
$('centimeters').value=(feet?cm:'');
}
else
{
var cm=parseInt($F('centimeters'))||183;
if(cm>241||cm<91)cm=183;
var inches_total=(cm*0.3937).round();
var feet=(inches_total/12).floor();
var inches=inches_total%12;
$('feet').value=feet;
$('inches').value=inches;
$('centimeters').value=cm;
}
}
</script>
<label>Height:</label>
<select id="feet" name="add[feet]" onchange="Profile.updateHeights('english')">
<option value="">—</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
</select>ft.
<select id="inches" name="add[inch]" onchange="Profile.updateHeights('english')">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
</select>in. or
<input id="centimeters" type="text" name="centimeters" maxlength="3" value="178" onchange="Profile.updateHeights('metric')" style="width: 30px;" />
centimeters
Assuming that this is just an excerpt from your entire code, Profile is a legitimate class name, and $F is defined somewhere, you're missing a few things.
First off, you're selecting by ID, so you need to include the # sign in your selectors.
Second, you're trying to parse an object as an integer. You need to use parseInt($("#feet").val()) to select the value contained in the input. Likewise, to set a value, you're going to want to use $("#centimeters").val(cm);

Categories

Resources