How to stop Infinity showing during input - javascript

I have created a form which works out a sum depending on the users input, this works fine but during the input stage i get the infinity property displayed in the total. Is there anyway of avoiding this?
I'm by no means a Javascript expecrt so any help would be appreciated. Here is the code.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var third = first / second;
var four = third * 100;
document.getElementById("final").innerHTML = four+"%";
}
</script>
</div><!-- /.wrapper -->

Don't divide by zero.
What you want to do when second is zero is up to you. But probably the easiest way to handle it is to just not do the calculation and not write anything in final unless you have a non-zero value from second.
In addition, you might want to check for NaN as well. If somebody writes a something in either textbox that is not actually a number, you will end up with NaN% in your output. (here you can use isNaN or you can compare the results of parsing your values with NaN).
So you could do something like:
var first = parseFloat(document.getElementsByName("child")[0].value);
var second = parseFloat(document.getElementsByName("parent")[0].value);
if (first !== NaN && second) { // note NaN and 0 are both falsy
// do your calculation here
}

You're going to need to do some validation on your values first. Your calculation only makes sense with numeric values and you're going to have to ensure that you don't try to calculate it if your second variable == 0.

In this case, I wouldn't try to parse/validate the inputs. Do as few as possible, and assume valid inputs.
Just test wether you get a valid output, before showing the result.
function isValidNumber(v){
//!NaN && !Infinity
return v===v && v !== Infinity && v !== -Infinity;
}
//cast the inputs to a valid number
function number(v){
//return +String(v).replace(",", ".");
return +v;
//return +v || 0;
}
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var result = 100 * number(first) / number(second);
document.getElementById("final").innerHTML = isValidNumber(result)?
Math.floor(result) + "%": //I have a valid result
""; //values have changed, but sth. went wrong
}

I think that will work for you.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
if(second == ""){second=1};
if(first != "" && second != ""){
var third = parseInt(first) / parseInt(second);
var four = parseInt(third) * 100;
document.getElementById("final").innerHTML = four+"%";
}
}
</script>
</div><!-- /.wrapper -->
Thanks

Related

Trying to create a random game but doesn't seem to work

Under my form action, I called the textbox and buttons. It was suppose for the user to key in 2 values one being the highest value and another being the lowest value, it will then generate a random value between the lowest and the highest. The user will than guess the number if its correct it will print out the message correct
<form action="random" method="get" onSubmit="return validate()">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<br/><span id="numbers1"></span>
<br/><input id="rand" type="submit" value="submit" onclick="Random()"><br/>
<input id="guess" type="text" value="Random Number Generator">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</form>
My script consist of the methods and functions to use, I think the problem lies at the RandomNumber() function, im not sure where did I go wrong, but please assist me
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
This is the function to generate a random number in between the lowest number and the highest number.
function Random()
{
var value1 = document.getElementById("digit").value;
var value2 = document.getElementById("digit1").value;
minvalue= Math.ceil(value1);
maxvalue= Math.floor(value2);
var random = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
document.getElementById("guess").value=random;
}
And this is the part where I assume it may have cause the entire program to stop working, its after I wrote down this codes and my web page doesn't perform the way I want it to be.
function RandomNumber()
{
var value3 = document.getElementById("digit").value;
var value4 = document.getElementById("digit1").value;
minvalue= Math.ceil(value3);
maxvalue= Math.floor(value4);
var random1 = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
var maxtries=5;
var counter=0;
var true=document.getElementById("textbox").value;
while(true!=random1)
{
document.getElementById("total").value=total;
counter +=1;
if(counter>maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
if(true==random1)
{
document.getElementById("correct").innerHTML="Correct"
}
}
}
When I look at your code I see a couple of red flags.
E.g. true is a reserved keywoard in JS, you can't assign a value to it:
var true=document.getElementById("textbox").value;
This must throw an error in your development console.
Also in your loop while(true!=random1) neither true or random1 are reassigned, so if true in the beginning, the condition will never become false, hence the loop is never left in this case!
In general you should try to narrow your issue down, look at the errors and rather ask for help on smaller snippets where you ask concrete questions. With a statement like my web page doesn't perform the way I want it to be it is hard to provide help.

Javascript form value restriction

I am trying to create a form which will store values in an empty array but the values must be between 0 to 5 and comma separated. the problem is it alerts if values is more than 5 but still stores the value in the array. I want it to alert and then restore the form value.
Here is my code:
<form name ="form1" onsubmit="return validateForm()">
<input type="number" name="text" id="inputText" name="inputText" />
<button onclick="pushData();">Insert</button>
<p id="pText"></p>
</form>
And javascript:
function validateForm () {
var form = document.forms["form1"]["inputText"].value;
if(form <0 && form >= 6) {
alert('value should must be between 0 to 5');
return false;
}
}
// create an empty array
var myArr = [];
function pushData() {
// get value from the input text
var inputText = document.getElementById('inputText').value;
// append data to the array
myArr.push(inputText);
var pval = "";
for(i = 0; i < myArr.length; i++) {
pval = pval + myArr[i];
}
// display array data
document.getElementById('pText').innerHTML = "Grades: " + pval ;
}
Try
if (form <0 || form >= 6)
I think it may work better if you reorganize where the functions are being bound.
Event propagation order:
The button is clicked, and the value is pushed into the array.
The form's submit event triggers, and validates the values, but it's too late.
There are many ways to approach this one, but the simplest would be to call pushData at the end of your validateForm.
Adjusted the condition, because there's no way for a number to
be less than 0 AND greater than or equal to 6 at the same time.
Also added event.preventDefault to stop form submission.
JavaScript
function validateForm (event) {
event.preventDefault();
var form = document.forms["form1"]["inputText"].value;
if (form < 0 || form > 5) {
alert('value should must be between 0 to 5');
return false;
}
pushData();
}
HTML
<form name="form1" onsubmit="validateForm(event)">
<input type="number" id="inputText" />
<button type="submit">Insert</button>
<p id="pText"></p>
</form>
JSFiddle
Note that per the MDN:
A number input is considered valid when empty and when a single number
is entered, but is otherwise invalid.
With this particular form element you may add min and max attributes so that the user must enter a value within a specified range. Therefore, the current contents of the OP's validateForm() function are superfluous. Additionally, that function has a problematic line of code:
if(form <0 && form >= 6) {
You cannot have a value that is both less than zero and greater than or equal to six. Use instead a logical OR, i.e. "||" operator for the logic to work.
The following code allows for a user to select numeric values in the range that the OP specifies and then it displays them in a comma-separated format, as follows:
var d = document;
d.g = d.getElementById;
var pText = d.g('pText');
pText.innerHTML = "Grades: ";
var inputText = d.g("inputText");
var myArr = [];
function pushData() {
var notrailingcomma = "";
myArr.push(inputText.value);
if (myArr.length > 1) {
notrailingcomma = myArr.join(", ").trim().replace(/,$/g,"");
pText.innerHTML = "Grades: " + notrailingcomma;
}
else
{
pText.innerHTML += inputText.value;
}
}
d.forms["form1"].onsubmit = function(event) {
event.preventDefault();
pushData();
};
p {
padding: 1em;
margin:1em;
background:#eeeeff;
color: #009;
}
<form name="form1">
<input type="number" id="inputText" name="inputText" min=0 max=5 value=0>
<button type="submit">Insert</button>
</form>
<p id="pText"></p>
A couple of points with respect to the form:
The OP's HTML has an error in the input field: it has two names. I dropped the one with a name of "text".
I like what #thgaskell recommends with respect to changing "Insert" into a submit button, preventing the default action of submitting the form, and associating pushData with the form's onsubmit event. So, I've modified the code accordingly.

javascript function retrieve input[type=number] and filter them based on the value

I have several input fields of type number, which users have to fill in. I need a script that will display a new page only once users have at least one non-zero value for these fields. So I need a function that checks that at least one input of type number is larger than zero.
Below is the function, in the script, that I wrote to attempt to implement this conditional page-switching (it calls another function which works and I am not showing here). The issue is with var filledValue. It returns undefined. I would like it to get all input elements of type number that have a raw value larger than 0 and return the id of that element. If the resulting variable is non-empty, then move on.
function NextTrial() {
var filledValue = $("input[type=number].val()>0",
"#page" + order[currentTrial]).id;
if (filledValue) {
$("#page" + order[currentTrial]).hide();
currentTrial++;
ShowTrial(currentTrial);
} else {
alert('Please answer the question before moving on!');
}
}
A sufficient excerpt of the HTML is:
<div id="answercol1">
<p><big>Government:</big></p>
<div class="fieldEntry"><label for="gvt">federal (USA)</label> <input id="fedgvt" min="0" name="fedgvt" size="4" type="number" value="0"></div>
<div class="fieldEntry"><label for="gvt">state or local</label> <input id="stategvt" min="0" name="stategvt" size="4" type="number" value="0"></div>
<div class="fieldEntry"><label for="tribalgvt">tribal</label> <input id="tribalgvt" min="0" name="tribalgvt" type="number" value="0"></div>
</div>
The function that I ended up using is:
function NextTrial() {
var answers = 0;
$("input[type=number]").each(function(){
if ($(this).val()>0) {
answers++
}
})
if (answers>0){
$("#page" + order[currentTrial]).hide();
currentTrial++;
ShowTrial(currentTrial);
} else {
alert('Please answer the question before moving on!');
}
}
You have an invalid code and it's not clear what you're trying to achieve,I'm not sure if that really what you want but try the following :
function NextTrial() {
//"#page" + order[currentTrial]).id; //Not sure what this line is used for
var currentTrial = 0;
$("input[type=number]").each(function(){
if ($(this).val()>0) {
$("#page" + order[currentTrial]).hide();
currentTrial++;
ShowTrial(currentTrial);
} else {
alert('Please answer the question before moving on!');
}
})
}
That will loop through all the fields with type number and check if the value of everyone is >0.
Hope this helps.
var ids = ['fedgvt', 'stategvt', 'tribalgvt'];
function GetValidInputs(inputIds){
//ids to return
var rets = [];
//loop through given inputs
inputIds.each(function(id){
//get input value of each based on their id
var val = ("#"+id).val() > 0;
//ternary: if value is > 0 push it to array GetValidInputs returns
//else do nothing
val > 0 ? rets.push(val) : 0;
};
//return desired ids
return rets;
};
//call it and see if it works
GetValidInputs(ids);
Something like the above would work if i'm understanding your question.
edit: added comments for clarity

calculation based on input field for a result on the fly

This is an extension to this thread.
My situation:
I need a user to enter a decimal value (ie 0.05) and show a simple calculation on the fly as the user types (or pastes). The example shown works for whole numbers but not when a decimal is entered into the input field.
I need to display the result in multiple places. I assumed I could just update getElementById to getElementByClass but that didn't work.
My Code:
<input type="text" name="capname" id="numberField" value="0.07" maxlength="5" />
<span name="mpd" id="mpdresult" class="mpdresult" ></span>
<span class="mpdresult" ></span> (second display)
<script>
window.onload = function() {
var base = 500;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('mpdresult').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('mpdresult').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
</script>
please use
var number = parseFloat(this.value);
instead of
var number = parseInt(this.value);
use ParseFolat for Decimal Numbers
document.write(parseFloat("10.33") + "<br>");
ParseFloatSample
Use parseFloat instead of parseInt. http://jsfiddle.net/janCY/
there is no such function getElementByClass. There is getElementsByClassName, it returns array with elements. But why don't use JQuery?

always want to keep first digit of my textfield as 0

hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]

Categories

Resources