Hello Everyone!
Im having some issues with a simple calculator type website. My issue involves using a javascript function to calculate an equation using variables from an HTML input form.
Below is my javascript function, which is placed above the form in the HTML file.
var userName = document.getElementsByName("userName")[0].value;
var userMmr = document.getElementsByName("userMmr")[0].value;
var userDesmmr = document.getElementsByName("userDesmmr")[0].value;
var userWinrate = document.getElementsByName("userWinrate")[0].value;
function findshit(){
alert(userMmr.value);
var LR = 1.0 - userWinrate.value;
var GP = 1;
while (1){
var GW = GP * userWinrate.value;
var GL = GP * LR;
var MMRG = GW * 25;
var MMRL = GL * 25;
var TMG = MMRG - MMRL;
if (TMG + userMmr.value >= userDesmmr.value) {
alert("Congrats! it will take you " + String(GP));
} else {
GP += 1;
}
}
}
<h2>Enter your information below</h2>
</br>
<form>
What's your name?:<br>
<input type="text" name="userName" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current mmr?:<br>
<input type="text" name="userMmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your desired mmr?:<br>
<input type="text" name="userDesmmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current win rate?<br>(put in decimal form eg. 50% = .50):<br>
<input type="text" name="userWinrate" onkeyup="findshit();" onchange="findshit();"/"><br>
<br>
<button onclick="findshit();">Try it</button>
Don't use .value when you set all the variables at the top. The code in the function expects those variables to just be the elements, because it uses .value to get their updated values. So it should just be:
var userName = document.getElementsByName("userName")[0];
var userMmr = document.getElementsByName("userMmr")[0];
var userDesmmr = document.getElementsByName("userDesmmr")[0];
var userWinrate = document.getElementsByName("userWinrate")[0];
You also need to put the script after the HTML, or put all the code inside the window.onload function. If you run the script before the HTML is loaded, none of the document.getElementsByName() calls will find the elements.
You should remove or modify while (1) loop. Because it is an infinite loop. I think you should use If loop in the scenario.
Related
I wrote the code provided. But on clicking the button, nothing appears.
function calculate() {
var colony = document.getElementById("co").value;
var dilution = document.getElementById("dil").value;
var inoculum = document.getElementById("in").value;
var b = parseFloat(dilution) * parseFloat(inoculum);
var c = parseFloat(colony) / b;
if (!isNaN(c)) {
document.getElementById("multiplication").innerHTML = "the conentration is " + c;
}
}
<button type="button" onclick="calculate">Calculate</button>
<p id="multiplication"></p>
You didn't call calculate() function. It should be onclick="calculate()" not onclick="calculate".
There's no value property in an element. Use innerText property of an element.
function calculate() {
var colony = document.getElementById("co").innerText;
var dilution = document.getElementById("dil").innerText;
var inoculum = document.getElementById("in").innerText;
var b = parseFloat(dilution) * parseFloat(inoculum);
var c = parseFloat(colony) / b;
if (!isNaN(c)) {
document.getElementById("multiplication").innerHTML = "the conentration is " + c;
}
}
<button type="button" onclick="calculate()">Calculate</button>
<p id="multiplication"></p>
<div id="co">1</div>
<div id="dil">2</div>
<div id="in">4</div>
I have added the HTML, which wasn't provided in the shared code
and it works. It is permissible for input fields to not have an ID attribute.
Client Side:
function calculate() {
var colony = document.getElementById("co").value;
var dilution = document.getElementById("dil").value;
var inoculum = document.getElementById("in").value;
var b = parseFloat(dilution) * parseFloat(inoculum);
var c = parseFloat(colony) / b;
if (!isNaN(c)) {
document.getElementById("multiplication").innerHTML =
"the conentration is " + c;
}
}
HTML:
co: <input type="text" id="co"><br>
dil: <input type="text" id="dil"><br>
in: <input type="text" id="in"><br>
<button type="button" onclick="calculate()">Calculate</button>
<div id="multiplication">fff</div>
In your inital code, your onclick="calculate" was missing () after calculate.
I've added that as well as a script tag within your html with your JavaScript function without changing much of your original code's text.
Working Jsfiddle: https://jsfiddle.net/yuL58da1/
For presentation/educational purposes, I solved the problem using JQuery as well to show you what the solution would look like using JQuery.
Working JsFiddle: https://jsfiddle.net/4g9ayoqb/
Using the JQuery method, I've updated your html button to include a id attribute and removed onclick:
<button id="calculate" type="button">Calculate</button>
and added a JQuery click selector for that button's id:
$(document).on('click','#calculate',function()
I'm trying to use create a converter by using the data attribute to refer back to a previous value.
I cannot seem to get:
data-my_currency to refer back to 301.46
data-this to refer back to 4259.00
$('input').keyup(function() {
var BTC = 4259.00
var ETH = 301.46
var LTC = 67.72
var USD = 1
var EUR = 0.83
var CNY = 6.46
var convertFrom = $('.js').data('my_currency');
//Should refer back to EUR var
var convertTO = $('.js').data('this');
//Should refer back to BTC var
var amount = $('input').val();
var result = convertFrom * convertTO * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js" data-my_currency="EUR"></div>
<div class="js" data-this="BTC"></div>
<input type="text" class="input" />
<div class="output">Me</div>
Alternatively and without changing your existing code much, you can declare your variables at global scope (which you should avoid) and use window object to get the value of the variable.
var BTC = 4259.00
var ETH = 301.46
var LTC = 67.72
var USD = 1
var EUR = 0.83
var CNY = 6.46
$(document).ready(function () {
$('input').keyup(function () {
var convertFrom = $('[data-my_currency]').data('my_currency');
var convertTO = $('[data-this]').data('this');
var amount = $('input').val(); //Assuming user enters only numbers
var result = window[convertFrom] * window[convertTO] * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="js" data-my_currency="EUR"></div>
<div class="js" data-this="BTC"></div>
<input type="text" class="input" />
<div class="output">Me</div>
If you are attempting to make them refer back to the JavaScript variables, why not simply use those JavaScript variables directly?
If, however, you have your Bitcoin and currency prices written as an element in the page (which is what I assume is the case), you're looking for $('.js[data-my_currency]')[0].innerHTML and $('.js[data-this]')[0].innerHTML respectively.
Breaking this down:
.js targets the class js
[data-my_currency] targets the attribute data-my_currency
$('.js[data-my_currency]') returns a nodeList
[0] grabs the first node
.innerHTML grabs the content inside of that node.
$('input').keyup(function() {
var convertFrom = $('.js[data-my_currency]')[0].innerHTML;
var convertTO = $('.js[data-this]')[0].innerHTML;
var amount = $('input').val();
var result = convertFrom * convertTO * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js" data-my_currency="EUR">0.83</div>
<div class="js" data-this="BTC">4259.00</div>
<input type="text" class="input" />
<div class="output">Me</div>
Hope this helps! :)
I'm trying to change the value of a property through a function method. I have it working but not exactly how i need it to work. Right now based of of user input it adds the number to value of speed. But not in a mathematical way. Instead it just adds it to the end of the value. so instead of doing 12 + 2 and getting 14. I get 122. How do i get it to add the values together?
HTML
<form>
<input type="number" id="speed" min="-6" max="15" required>
<input type="button" id="gear_submit" value="Submit" onclick="createBike();">
</form>
<p id="show_speed"></p>
Javascript
function createBike(){
function bike(model, speed){
this.model = model;
this.speed = speed;
// this will change speed based on user input
this.changeSpeed = function (changeSpeed) {
var new_speed = document.getElementById("speed").value;
if (new_speed > 0 ){
bikeArray[0].speed = speed + new_speed;
}
else if (new_speed < 0 ){
bikeArray[0].speed - speed - new_speed;
}
}
}
var bike1 = new bike("Ghost Ryder", "12");
bikeArray[0] = bike1;
bike1.changeSpeed();
document.getElementById("show_speed").innerHTML = bikeArray[0].model + " " + bikeArray[0].speed;
}
It's treating your numbers as strings, and concatenating the strings instead of adding the numbers. To fix this you need to first remove the quotes around the number in your constructor so that it's a number and not a string, and secondly you need to use parseInt on the value that comes from your speed input element.
Working Example:
var bikeArray = [];
function createBike() {
function bike(model, speed) {
this.model = model;
this.speed = speed;
// this will change speed based on user input
this.changeSpeed = function(changeSpeed) {
/* The value on the following line gets parsed using parseInt */
var new_speed = parseInt(document.getElementById("speed").value, 10);
bikeArray[0].speed = speed + new_speed;
}
}
/* The object gets initialized using an integer value here instead of a string */
var bike1 = new bike("Ghost Ryder", 12);
bikeArray[0] = bike1;
bike1.changeSpeed();
document.getElementById("show_speed").innerHTML = bikeArray[0].model + " " + bikeArray[0].speed;
}
<form>
<input type="number" id="speed" min="-6" max="15" required>
<input type="button" id="gear_submit" value="Submit" onclick="createBike();">
</form>
<p id="show_speed"></p>
JSFiddle Version: https://jsfiddle.net/a453bngn/2/
You need to read the variable as a number, not a string. parseInt() does this.
bikeArray[0].speed = parseInt(speed, 10) + parseInt(new_speed, 10);
Ok, I am more than impressed that you guys took your time to answer this, thank you so much, I did not expect it. Hope well follows you.
To explain my problem, I used that fiddle tool you all had. This is the code I have:
enter code here
http://jsfiddle.net/5xzSy/1/
-What I need, is to sum up the values that get calculated in the spans : budgetI + actualI
Modified your code to : Use .text() to populate the Span and assign some value to your inputs..(Since you have used jQuery)
http://jsfiddle.net/xubam99v/
HTML Code
<pre>
<input id=primaryB type="text" value="100"></input><input id=primaryA type="text" value="100"></input><span id=primary></span><br />
<input id=spouseB type="text" value="100"></input><input id=spouseA type="text" value="100"></input><span id=spouse></span><br />
Budget: <span id=budget></span> <br />
Actual: <span id=actual></span><br />
</pre>
Javascript/jQuery Code
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').text(primaryBValue + spouseBValue);
$('#actual').text(primaryAValue + spouseAValue);
listen on the change-event to sum numbers after you insert then
http://jsfiddle.net/55c5uqhc/2/
$('#primaryB,#primaryA,#spouseB,#spouseA').change(calc);
function calc() {
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').html(primaryBValue + spouseBValue);
$('#actual').html(primaryAValue + spouseAValue) ;
}
You need to create a trigger upon which you populate the <span>s, also use text() instead oh html()
Here's example(probably a bad one but it's good place to start):
function:
$('input').keyup(function(e){
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#spouse').text(spouseBValue - (-spouseAValue));
$('#primary').text(primaryBValue - (-primaryAValue));
$('#budget').text(primaryBValue - (-spouseBValue));
$('#actual').text(primaryAValue - (-spouseAValue));
});
fiddle
I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.