Getting number from user input: string is empty on submit? - javascript

I'm stuck on a problem. I'm working on an exercise that generates a random integer between 1-10. The user will submit a number from 1-10 in the input box. If a match occurs, the user will get an alert notifying them of success.
I'm stuck on getting the number from the user input. I want to log to the console the form input, but for the life of me, I cannot figure this out. I've tried changing the form type="number", type="text" and tried using parseInt().
Anything glaring in my code?
function exerciseEight() {
let input = document.querySelector("#number").value;
let button = document.querySelector("#guess");
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
button.onclick = function() {
console.log(input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>

You need to get the input value when the user clicks. You're setting input and all the other variables that depend on it when the page is first loaded.
function exerciseEight() {
let button = document.querySelector("#guess");
let number = Math.ceil(Math.random() * 10);
button.onclick = function() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
console.log(number, input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>

The problem is that you are calling the function when the page loads, so it gets the values from the start, and doesn't change them at runtime when user enters input. You should call the function when user clicks the button.
function exerciseEight() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
}
let button = document.querySelector("#guess");
button.onclick = exerciseEight;
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>

Related

How do I make this conversion function work in both directions?

I'm new in JS and I have trouble to finish a converter only with inputs, I explain the problem !
We have two input, Meters and Feet. when I transmit a number to Feet I have the result in Meters. And I Want to do the same think with Meters . and vice versa
let metresEl = document.getElementById('inputMetres');
function LengthConverter(valNum) {
metresEl.value = valNum/3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres">
</div>
</div>
You can add another parameter in the LengthConvertor function which will say the input unit (meter or feet) and convert it accordingly inside the function using if.
function LengthConverter(valNum, inputUnit) {
if(inputUnit === 'feet')
metresEl.value = valNum/3.2808;
if(inputUnit === 'meter')
feetsEL.value = valNum * 3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value,"feet")" onchange="LengthConverter(this.value,"feet")" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="LengthConverter(this.value,"meter")" onchange="LengthConverter(this.value,"meter")" >
</div>
</div>
Added inverse conversion:
let metresEl = document.getElementById('inputMetres');
let feetEl = document.getElementById('inputFeet');
function FeetToMetres(valNum) {
metresEl.value = valNum/3.2808;
}
function MetresToFeet(valNum) {
feetEl.value = 3.2808*valNum;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="FeetToMetres(this.value)" onchange="FeetToMetres(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="MetresToFeet(this.value)" onchange="MetresToFeet(this.value)">
</div>
</div>
You can add a element.addEvenetListener to each input, and when it chances you get it's value, convert, and put in on the right input.
let metresEl = document.getElementById('inputMetres');
let feetsEl = document.getElementById('inputFeets');
metresEl.addEventListener('change', yourCode);
feetsEl.addEventListener('change', yourCode);
For exemple, if metres input changes, you convert to feets and add to feets input.

Getting NaN In Building a Simple Calculator

I'm fairly new to Javascript and I'm currently working on a simple calculator that would allow users to answer a few questions in order to calculate their total price. The price would show up in the DIV below the form. But, the issue that I'm having is that the output in the div is NaN until the last option is selected.
The code isn't perfect since I'm just testing at this point, but here's the HTML.
const looks = document.getElementById('looks');
const edits = document.getElementById('edits');
const studio = document.getElementById('studio');
const total = document.getElementById('total');
const btn = document.getElementById('btn')
looks.addEventListener('change', totalCost);
edits.addEventListener('change', totalCost);
studio.addEventListener('change', totalCost);
btn.addEventListener('click', totalCost);
function totalCost() {
total.innerText = (looks.value * 100)
+ (edits.value * 50)
+ parseInt(studio.value);
}
<div class="container">
<form action="">
<h3>How Many Looks?</h3>
<input type="number" id="looks" value="">
<h3>How Many Edits?</h3>
<input type="number" id="edits" value="">
<h3>Location:</h3>
<select name="studio" id="studio">
<option value="">On-Location</option>
<option value="100">In-Studio</option>
</select>
<h3>Total:</h3>
<div id="total"></div>
<input type="button" value="submit" id="btn">
</form>
</div>
I'd also like to implement something where the total doesn't show up until the submit button is pressed. I'd greatly appreciate any help in these matters. Thanks a lot!
You have an issue in studio.value, its come NaN for first init, you need to check your param if its number or not before do a calculation or convert it to number like below example:
const looks = document.getElementById('looks');
const edits = document.getElementById('edits');
const studio = document.getElementById('studio');
const total = document.getElementById('total');
const btn = document.getElementById('btn')
looks.addEventListener('change', totalCost);
edits.addEventListener('change', totalCost);
studio.addEventListener('change', totalCost);
btn.addEventListener('click', totalCost);
function totalCost() {
let stdValue = parseInt(studio.value);
if(isNaN(stdValue)){
stdValue = 0;
}
total.innerText = ((looks.value * 100)
+ (edits.value * 50)
+ stdValue);
}
<div class="container">
<form action="">
<h3>How Many Looks?</h3>
<input type="number" id="looks" value="">
<h3>How Many Edits?</h3>
<input type="number" id="edits" value="">
<h3>Location:</h3>
<select name="studio" id="studio">
<option value="">On-Location</option>
<option value="100">In-Studio</option>
</select>
<h3>Total:</h3>
<div id="total"></div>
<input type="button" value="submit" id="btn">
</form>
</div>
====================
Update 1:
Like Nick Parsons Suggestion, the real answer must be via set the 0 as a default option if its needed as a number...
<option value="0">On-Location</option>
So that, look when and where you need to validate and when need to setup initial value...do both to get a good code...
this way
const
myForm = document.getElementById('my-form')
, total = document.getElementById('total')
;
myForm.oninput = evt =>
{
total.textContent = (myForm.looks.valueAsNumber * 100)
+ (myForm.edits.valueAsNumber * 50)
+ (parseInt(myForm.studio.value) || 0)
}
myForm.onsubmit = evt => // beter than btn.onclick
{
evt.preventDefault() // stop form submiting
}
<div class="container">
<form action="" id="my-form">
<h3>How Many Looks?</h3>
<input type="number" name="looks" value="0" min="0">
<h3>How Many Edits?</h3>
<input type="number" name="edits" value="0" min="0">
<h3>Location:</h3>
<select name="studio" >
<option value="" selected > On-Location </option>
<option value="100" > In-Studio </option>
</select>
<h3>Total:</h3>
<div id="total"> ? </div>
<button type="submit">submit</button>
</form>
</div>

Make multiple additions with multiple input value Javascript

I am creating a lot of numbers inside of a div. Each time someone clicks a number I want to add it to another div. Let me make myself clear with some examples:
When a user clicks on the add class, the value of .addcop should be added to the value of .totalyHide. That means the value should change to 12.
When I click on the .add2 the value should be added on to 12, so the value of .totalyhide becomes 32.80.
and other terms, if I click the first + and click the second +, they should be added together on Yearly Price.
I hope you understand what I am trying to do.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totaly").val("$" + bigTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div class="box box6">
<div class="titlet">work on it
<hr>
</div>
<div class="explain">to help you better</div>
<div class="money">
<p class="me">$12 Yearly</p><i class="add fas fa-plus-square fa-2x"></i></div>
<input type="text" name="content" class="addcop" style="display: none;" value="12">
</div>
<div class="box box5">
<div class="titlet">Procurement
<hr>
</div>
<div class="explain"></div>
<div class="money">
<p class="me">$20.80 Yearly</p><i class="add2 fas fa-plus-square fa-2x"></i></div>
<input type="text" class="procurement" style="display: none;" value="20.80">
</div>
<div class="box box8">
<div class="total">Your First Deposit will be: <input class="total1" type="button" value="$546"></div>
<input type="text" class="totalHide" style="display: none;" value="546">
<div class="total">Yearly Price: <input onchange="myFunction()" class="totaly" type="button" value="$0"></div>
<input type="text" class="totalyHide" style="display: none;" value="0">
<div class="total">On-off Price: <input class="total" type="button" value="$546"></div>
<input type="text" class="total" style="display: none;" value="546">
</div>
There is a minor issue with the JQuery code that you have written. You can add the following changes to get the desired result.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
The thing to note here is that whenever you are calculating the total,
you'll have to set that total to $(".totalyHide"), so that you can read the updated value upon next click.

Launching a new window and filling form values using Javascript

I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}

Total of input fields should not exceed certain Amount

I have created an Add / Remove input fields. I want to get total of 'Amount' using Javascript which should not exceed 100%. Means the total of amount should not exceed 10000.
Say for example first field will have 3000, second will have 6000 and third will have 1000. If we enter larger number it should not accept it.
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="fund-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_amount[]" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<center><b>Allocation of Funds</b></center>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-5">
<label>Allocation Items <b style="color:#FF0000;">*</b></label>
</div>
<div class="col-md-5">
<label>Amount <b style="color:#FF0000;">*</b></label>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]" placeholder="">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_amount[]" placeholder="">
</div>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add
</button>
</div>
</div>
<div id="fund-allocation-fields"></div>
<p class="help-block"><i>Total amount must be equal to the goal amount.</i></p>
</div>
</div>
Please Help me. Thanks in advance.
If I understand correctly you could do something as simple as:
var val1 = document.getElementById('inputOne').value;
var val2 = document.getElementById('inputTwo').value;
var val3 = document.getElementById('inputThree').value;
if(val1+val2+val3 < 10000){
// Less then 10000 so do your stuff
} else{
// More then 10000 so let the user know they went too far
}
You can also do it in jQuery. Just change document.getElementById('inputOne').value to $('#inputOne').val()
If the elements are built dynamically you could just do something like this:
var inputs = Array.from(document.querySelectorAll('.inputsToAdd'));
var number = 100;
document.getElementById('btn').addEventListener('click', ()=>{
inputs.map(input=>{
number+=parseInt(input.value);
})
if(number<10000)
console.log(true);
else console.log(false)
})
This is a bit of a connundrum since you have the ability to add infinite input fields, in common practice this is a bad UI experience but to resolve your issue.
You want to sum all the values on click and if the values are too high throw an error. You can accomplish this by assigning each inputField a class and then summing the collection of that class.
I made a small sample using jQuery, a conditional and .each() like so:
$('#sum').click(function(){
var nums = 0
$('.valueField').each(function(){
nums += parseInt(this.value)
});
nums > 10000 ? console.log("value too high", nums) : console.log("compute works", nums)
})
See my small demo below:
$('#sum').click(function() {
var nums = 0
$('.valueField').each(function() {
nums += parseInt(this.value)
});
nums > 10000 ? alert("value too high", nums) : alert("compute works", nums)
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type='number' class='valueField' />
<input type='number' class='valueField' />
<input type='number' class='valueField' />
<button id='sum'>Click</button>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>

Categories