javascript puts out NaN and i dont know why - javascript

Well, I got this problem with my Javascript homework. I need to make a binary translator and well Javascript does not really want me to...
It works but not really as it should... If I declare the variable with a number, it works. But if I use document.getElementById to make it some kind of interactive, then it does not want to work. It just gives NaN. I know that it means not a number, but I use the parseInt() and well it works without the document.getElementById...
So here is the code how it works:
var input = 15;
function convertdec()
{
document.getElementById("output").innerHTML
= "binary number: " + parseInt(input).toString(2);
}
The output is 1111, which is correct, BUT this is how it should also work and how I want it to be:
var input = document.getElementById("input").value;
function convertdec()
{
document.getElementById("output").innerHTML
= "binary number: " + parseInt(input).toString(2);
}
Tthe output of this should also be 1111 if you fill in 15 but it says:
binary number: NaN
If any one could help me, it would be really great!
edit
ok, so there was asked for my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Binairy Converter</title>
<link type="text/css" href="global.css" rel="stylesheet" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div id="main">
<input type="text" name="text" id="input" />
<input type="button" id="conbin" onclick="convertbin()" value="bin to dec" />
<p id="output" ><p>
</div>
</body>
</html>
edit
yeah i fixed the problem by doing:
var input;
function convertdec()
{
input = document.getElementById("input").value;
document.getElementById("output").innerHTML = "binary number: " + parseInt(input).toString(2);
}
but thanks for your help anyway

You're doing well to fetch the DOM elements outside the function as this DOM parsing is expensive and the DOM doesn't change, but you do need to fetch the values inside the function to get their current values, not the values on page load. Try this:
var input = document.getElementById("input");
var output = document.getElementById("output");
function convertdec()
{
output.innerHTML = "binary number: " + parseInt(input.value, 10).toString(2);
}
Also note that parseInt() parses in octal if you have a leading zero, so asking it for "08" nets you "10". Fix that by using parseInt(num, 10). I've made that mod in the above example too.

This might be an artifact of how you displayed snippets... but it looks like you're setting input to whatever the value is when the page loads... you'd probably be better off doing
function convertdec()
{
var input = document.getElementById("input").value;
document.getElementById("output").innerHTML = "binary number: " + parseInt(input).toString(2);
}
so that the value gets set when the function gets called

Without seeing this in context, here's what I suspect is occurring:
// you're getting the value from the textbox as it exists
// when the page is rendered: ""
var input = document.getElementById("input").value;
// when you call this, it operates on value ... which is always ""
function convertdec()
{
document.getElementById("output").innerHTML
= "binary number: " + parseInt(input).toString(2);
}
One subtle change should fix it:
var input = document.getElementById("input");
function convertdec()
{
document.getElementById("output").innerHTML
= "binary number: " + parseInt(input.value).toString(2);
}
Addendum: As robrich notes in his answer, using parseInt(input.value, 10) will ensure the string in the textbox is interpreted as a base-10 number.

The most likely cause of the problem is that you aren't selecting the correct element and hence the actual value in input isn't the string "15". The use of input itself as the ID is suspicious as it's a tag type and typically not an ID
Can you show us the HTML which declares input?

Related

str.replace(/[^0-9]/g, " ") erases my whole string instead of just getting rid of non-numerical characters. How to make it work properly?

I'm trying to use str.replace in order to remove any non-numerical characters from a number imput field when someone uses copy-pastes something in it. However the function always seems to remove all characters instead of just removing the non-numerical ones.
Surprisingly the function is able to detect when my string is purely numerical and won't change it in those cases, but adding a single other character will cause the whole string to be ditched instead of just removing the wrong characters.
I tried to change the regexp of the function to /\D/, but it didn't amount much.
Here's a minimal reproducible example, which must be run on Firefox.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script src="../lib/jquery-3.3.1.js"></script>
<input type="number" id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function()
{
$(document).ready(function()
{
input.value = input.value.replace(/[^0-9]/g, "");
});
}
</script>
</body>
</html>
I expect an output such as "34a01 2" to be "34012", but the actual output is "" (nothing). Is there something wrong in my regexp ?
let input = document.getElementById("inp");
input.onblur = function() {
$(document).ready(function() {
input.value = input.value.replace(/[^0-9]/g, "");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="inp"></input>
This looks to be a Firefox issue (or bug). Whenever a numeric input has non-numeric characters anywhere, the .value of the field will be the empty string:
setInterval(() => {
console.log(input.value);
}, 400);
<input id="input" type="number">
It's unfortunate, but you may have to simply remove the type="number" for the .value to be retrieved and replaced as desired:
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]/g, "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inp"></input>
Either that, or keep type="number" and tell the user that the value they attempted to paste is invalid, and prevent it (because you have no way of retrieving and replacing it).
(also: only call $(document).ready once, when you're adding the listeners, if at all - your current code is adding a new listener every time the field is blurred)
I've read your comments about Firefox and I've prepared a new version.
Not including the "number" type seems to work.
Using "number" type is not causing any issue in Chrome so I guess that Firefox is not behaving in the same way.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
<input id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]+/g, "");
}
</script>
</body>
</html>

Beginning Javascript form validation

this is my first time posting.
I'm in a beginner Javascript class with the following assignment:
"Students are required to enter into a text box their course information in the following format:
AAA.111#2222_aa-1234
Your Web page will ask the user to type their information in a text box. The user will then click a form button named validate. If the format is correct a message will be generated below the button that reads "Correct Format". If the format is incorrect a message will be generated that reads "Incorrect Format". "
After my first attempt, I got the following feedback:
"You do not need a form for this assignment .You only need a text box and a button. Place your function on your button (onClick event). You only need one function for this assignment.  Your function should include getting the users input from the text box. You can use getElementById() and .value it should also include the regular expression, and what to so if it is correct or wrong."
So far I have the following:
function isValid(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return (myRegExp.test(text);
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src = "registerFourth.js"></script>
</body>
</html>
So sorry if I am not posting this correctly. My code is telling me I have a "Parsing Error: Unexpected Token" and when I fill in the text box and click Validate nothing happens. Thank you!
There are multiple issues in your approach.
1. Your isValid method expects text parameter which is not required
2. Your isValid method is recursive, I don't see why that is needed.
Please check below if it works for you.
function isValid() {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
var text = document.getElementById("course").value;
var match = myRegExp.test(text);
if(match) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format";
}
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
You had a few syntax errors:
return (myRegExp.test(text); should be return myRegExp.test(text);
isValid(document.getElementById("course".value) should be isValid(document.getElementById("course").value)
And finally, putting the return statemenet before the rest of your code defeats the whole purpose of the rest of your code. return breaks out of your current function, which means the if else statement is rendered useless.
function isValid(text) {
var myRegExp = "/([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/";
return myRegExp.test(text);
if (isValid(document.getElementById("course").value)) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type="text" name="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src="registerFourth.js"></script>
</body>
</html>
There are a couple of syntax as well as function construction issues with this.
You have a missing ) in 2 lines -
return (myRegExp.test(text);
and
if (isValid(document.getElementById("course".value) line
You are also returning the value before the conditional statement. So the block below, will never run. Returning a function value ends the function execution
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
Think about functions in terms of inputs and outputs and what function it performs.
For example,
/// this function only takes a string and tests if it matches the regex
/// input: string
/// output: true / false (boolean)
function testRegex(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return myRegExp.test(text)
}
/// this function runs when the button is clicked, calls the testRegex fn
/// and handles setting the output element
/// note: read about ternary conditional operators if confused about ?:
function isValid() {
const outputEL = document.getElementById("output")
const courseEl = document.getElementById("course")
outputEl.innerHTML = testRegex(courseEl.value) ? "Correct Format" : "Incorrect Format";
}
If you want to understand how the code is being executed -
the script tags loads your registerFourth.js which will contain the two functions I defined above - isValid and testRegex. Note that the functions are just defined and not executed yet
when you click the button, the isValid function starts executing
the isValid function gets the output element and course element
isValid then calls testRegex with the value of course element
now, testRegex runs with the value provided to it and returns (to the calling function, isValid is this case) a boolean value, based on if the value is valid
isValid is back in power and depending on the value testRegex sent it, it sets outputEl to CorrectFormat / Incorrect Format
isValid ends!
You miss a few closed brackets.
See updated RegExp .
Change document.getElementById("course".value) to document.getElementById("course").value
You use of return incorrectly, in my code no need return .
see full code :
function isValid() {
var text = document.getElementById("course").value;
var myRegExp = /^([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa|aa)-\d{4}$/;
document.getElementById("output").innerHTML = myRegExp.test(text) ? "Correct Format" : "Incorrect Format" ;
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
this line is invalid
return (myRegExp.test(text);
If you want to return if the test is true
if (myRegExp.test(text)) return;
You also need to close the () here with 2 more )
if (isValid(document.getElementById("course").value))
That should solve your syntax issues. Not your logic though...

In JS validation - trying to remove spaces from text-box, but getting undefined value

I want to remove leading and trailing spaces from the values provided in a text box. For that I am using JavaScript validation. In that I have declared two variables and when I tried to check the values assigned to these variables, I am getting undefined as value. Can you please let me know where I am wrong?
function trim(StringtoTrim){
StringtoTrim.replace(/^\s\s*/, '');
}
function validate()
{
alert("in validate ");
var value1 = myform.fname.value;
alert(value1.value);
var value2 = trim(value);
alert(value2.value);
if(value2.length != value1.length)
{
document.getElementById('errfn').innerHTML="please remove leading and trailing spaces ";
return false;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="myform" onsubmit="return validate();">
First_Name
<input type="text" name="fname"/><span id="errfn"></span>
<br> <br>
<input type="submit"/>
</form>
</body>
you are trying to get value of value
var value1 = myform.fname;
alert(value1.value);
and second value is not defined
var value2 = trim(value);
it should be value1 but still the script is more problems than that. See below
function validate()
{
alert("in validate ");
var value1 = myform.fname.value;
alert(value1);
var value2 = value1.trim();
alert(value2);
if(value2.length != value1.length)
{
document.getElementById('errfn').innerHTML="please remove leading and trailing spaces ";
return false;
}
}
Your own made trim function is broken, it leaves the trailing spaces.
String has a built in trim() function.
This removes all leading and trailing spaces but leaves the spaces inside the word.
" de mo ".trim()
Will result in:
"de mo"
In the validate function there are other problems, you try to access
in alert(value1.value) you try to access myform.fname.value.value which is invalid, this should be alert(value1)
var value2 = trim(value), here value is undefined and should be var value2 = trim(value1)

Why does "greater than" comparison of numbers give unexpected result

There is an input field, like this,
<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />
Dynamically, a value is assigned to the input tag, like this,
document.getElementById('quantity').value = qu; //var qu=11 lets say
Now, what i want is, if the user manually inputs a value greater than "qu", then the value would automatically change itself to "qu".
What i did for this is something like,
document.getElementById('quantity').addEventListener("change", function() {
var qc = this.value;
if(qc>qu) {
this.value = qu;
}
});
The strange thing that is happening is if i input any value from 2 to infinity, it is changing all of them to 11. Only value it does not change are 0,1,10,100,1000,10000 and so on..
I am completely confused. Please help.
Its simple, use parseInt to get actual number value of your text-area.
You are getting string by default.
this.value is giving you '11'
parseInt(this.value) is giving you 11.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />
</body>
<script>
var qu = 11;
document.getElementById('quantity').value = qu;
document.getElementById('quantity').addEventListener("change", function() {
var qc = parseInt(this.value);
if(qc>qu) {
this.value = qu;
}
});
</script>
</html>
Use parseInt
var qc = parseInt(this.value)

how do I know user info submited?

This is what i have http://jsfiddle.net/bd9wv/... what i am trying to do is have boxes users can input numbers in, and be able to comment back based on the numbers they gave..what i have works for one only...if someone would not mind telling me...what holds the input, i think it's var val? i think i should be able to add more boxes. exp... var al id="number1" type="text"/> ...and then in js..... msg = 'Thank you for the wonderful number: ' + (val+al); but that does not work for me. i would like maybe 10 boxes..but 2-3 is good for me to see how it is done. what i am not understanding is what holds the input and how to use it...explaning a little would be great, i think the submit might be getting me. but if you have an example i can look at it an figure it out,i will be very thankful!!
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Keeping much of your code in place you can make this work. I changed your ID's to classes, since there will be multiple similar elements. I modified a piece of your JS to the following:
var val = $(this).prev(".number").val();
var $outputDiv = $(this).next().next(".feedback");
Using this you can find the closest elements to the input the user was typing.
And your HTML:
Enter number: <input class="number" type="text"/>
<button class="btnNumber">Submit</button>
<br/>
Feedback: <div class="feedback"></div>
Demo: http://jsfiddle.net/bd9wv/1/
I could not understand clearly; but please try whether this work for you or no http://jsfiddle.net/bd9wv/2/
Example:
var val = $(this).parent().find('.number').val();
Here I have used class and have surround the html block with another div

Categories