Outputs not showing in simple odd/even code - javascript

I've just started beginning to code in JavaScript (my first attempt at any so please be patient!), so have just set myself a simple project just to create a input box, and was hoping upon clicking the calculate button to generate a "Even" or "Odd" output that shows up below the box. But somehow I can't get anything to show up. Any ideas what I'm doing wrong?
function myFunction() {
// define var num
var num = document.getElementById("number").value;
//use of if function as number is odd or even (modulo = 0 or 1)
if (num % 2 === 0) {
document.writeIn("Even");
} else {
document.writeIn("Odd");
}
}
<table id="number">
Number: <input type="number" name="name">
<input type="button" onclick="myFunction()" value="Calculate"></table>

You need to take an input with type 'text' and an id of 'number'.
Then get this value of the input and assign to another element the result, because document.writeln does not work after the page is rendered by the user agent.
function myFunction() {
var num = document.getElementById("number").value;
document.getElementById("type").innerHTML = num % 2 ? "Odd": "Even";
}
Number: <input type="text" id="number">
<input type="button" onclick="myFunction()" value="Calculate">
<div id="type"></div>

Related

javascript enter number of seconds - not less than zero

i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.
how can a make the code logic?
function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds">
<button onclick="sec()">Click</button>
</form>
what should i do? anyone help me?
Add your expectation about the input value as attributes on your input:
Specifically required min="0" would meet your needs.
function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds" required min="0">
<button onclick="sec()">Click</button>
</form>
With JavaScript you can convert your user's input to a Number then check its value with an equality condition.
E.g. you could fill out your sec() function like this:
function sec() {
const seconds_str = document.getElementById("seconds").value;
const seconds_num = parseInt(seconds_str, 10); // note: you could use parseFloat for decimal fractions
let result = "";
if (seconds_num < 0) {
result = "Is less than zero :'(";
} else {
result = "Is NOT less than zero :)";
}
console.log("User input = " + seconds_str);
console.log("Converted to integer = " + seconds_num);
console.log(result);
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds">
<button onclick="sec()" type="button">Click</button>
</form>
It would be up to you what you do when you detect a number less than zero. E.g. prevent form submitting, show an error message etc...

Unable to test the value of a number in external javascript file

I am trying to send a number from a user to an external javascript file ie .js and determine if it is less than or greater than another number
function processFormData() {
var name_element = document.getElementById('txt_name');
var x = name_element;
var x = Number(+x);
if (x > 10) {
alert("large number");
} else {
alert ("small number");
}
}
<script src="demo2.js"></script>
<p>
<label for="name">Your Name: </label>
<input type="number" name="name" id="txt_name">
</p>
</label>
<input type="button" name="submit" value="submit"
onclick="processFormData();" >
I think you are doing some pointless things here, first of all, why do you create two variables that points to the same object?
The second line is totally unnecessary. You are good to go with name_element.
var name_element = document.getElementById('txt_name');
var x = name_element;
And the solution to your problem is, you are trying to convert a DOM element to the number. Instead you should access to textContent first.
var numericalValue = Number(name_element.textContent);
// If you are expecting that input from a input box
// then you need to use name_element.value
if (x > 10) {
alert("large number");
} else {
alert ("small number");
}
Your code attempts to convert the text field itself into a number, rather than the value of the text field.
NOTES:
There's no need to set a variable up for the text field and then another to the first.
You have an extra </label> tag in your code.
The for attribute of a label must point to the id of some form
field, not the name attribute value.
Don't give elements a name or an id of name as this often
causes problems with the Global name property of the window
object.
function processFormData() {
var name_element = document.getElementById('txt_name');
// Convert the value of the element by prepending + to it
var x = +name_element.value;
if (x > 10) {
alert("large number");
} else {
alert ("small number");
}
}
<script src="demo2.js"></script>
<p>
<label for="txt_name">Your Name: </label>
<input type="number" name="txt_name" id="txt_name">
</p>
<input type="button" name="submit" value="submit" onclick="processFormData();">

What step am I missing to check if value matches array element and print an alert using if/else

I'm trying to check user input against predetermined list of zipcodes. I've created one variable that represents the user input using document.getElementById("zipcode").value and set up my array of zipcodes to check against. This worked once but I think I had break; included in the if/else. What am I missing?
The input box translates to a string so I made my array elements string too. I'm so confused.
<h2>Zipcode checker</h2>
<input id="zipcode" name="address-4" type=text maxlength="5" value="" pattern="[0-9]" required/>`
<button id="btn" value="submit" type="submit" onclick="myStuff()">Register</button>
Script:
var btnInput = document.getElementById("zipcode").value;
var acceptedZip = ["85392", "85340", "85393", "85353", "85341"];
function myStuff() {
for (var i = 0; i < acceptedZip.length; i++) {
if (acceptedZip[i] === btnInput) {
alert("we got you boo");
}
else {
alert("sorry son");
}
}
}
The problem in your code is that you're storing the value of the input only once, which is when the code is runs for the first time, and the value at the first run is empty "" (if you don't set it in html).
You can do what you want with just this :
<h2>Zipcode checker</h2>
<input id="zipcode" name="address-4" type=text maxlength="5" value="" pattern="[0-9]" required/>`
<button id="btn" value="submit" type="submit" onclick="myStuff()">Register</button>
<script>
var btnInput = document.getElementById("zipcode"); // store the button outside
var acceptedZip = ["85392", "85340", "85393", "85353", "85341"];
function myStuff() {
var exists = acceptedZip.indexOf(btnInput.value)>-1 ; // get the value of the input inside (each time the button is pressed)
alert(exists ? "we got you boo" : "sorry son");
}
</script>
I'm using JavaScript's ternary operator, which is basically :
<cond 1> ? <act 1> : <cond 2> ? <act 2> : <act 3>
equivalent to :
if (<cond 1>) { act 1 } else if (<cond 2>) { <act 2> } else { <act 3> }

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Javascript calculation letters and numbers

<SCRIPT Language = JavaScript>
function calculate() {
a = 12
b = eval(document.form.number.value)
c = 5J7S
d = (a + b + c)
alert(d)
}
</SCRIPT>
<FORM NAME = form>
Phone: <INPUT TYPE = text SIZE = 3 value ="">
-
<INPUT TYPE = text name = number SIZE = 3 value ="">
-
<INPUT TYPE = text SIZE = 4 value ="">
<P>
<Input Type = Button NAME = b1 VALUE = "Grab Code" onClick = calculate()
</FORM>
5JG7S (Fixed Value)
5+7=12 (Added both numbers from Fixed Value)
Phone number 123-456-7890
4+5+6=15 (Prefix added together)
12+15=27 (Added numbers from the Fixed Value and the numbers that were added from the prefix)
27+5JG7S=275JG7S (Those numbers were added to the beginning of the orginal Fixed Value)
Now this Script that I have:
a is the added numbers from the Fixed Value
b is the input from the form(phone number)
c is the Fixed Value
d is adding each one up so they will display the code as an alert.
Now, if I take out c and just add a and b it performs the addition, if c is in there, it stops the process and produces nothing.
My question is, how do we add the calculated number and append it to the beginning of the fixed value?
Also, the addition works, but not the way I want it to, I want to add the 3 numbers together, the javascript adds 456+12= 468
I know this is very simple code, I am not familiar with Javascript programming and I pretty much pieced together what I found from searching.
I hope this makes sense, if this is not possible I understand.
Thanks!
using parseInt on the values should help with the math. your results are currently inaccurate because the form values are strings: rather than adding numbers you are concatenating strings.
i changed your 'number' input to have an ID attribute, so that you can select with getElementById and replaced the eval call with a call to parseInt.
the value of c in the calculate function needs to be corrected though, not sure what you meant but that will generate an error.
other various HTML tidyness issues (nothing that would break, just easier to read IMHO).
<script type="text/javascript">
function calculate() {
var a = 12;
var b = parseInt(document.getElementById("number").value);
// var c = 5J7S;
var d = (a + b + c);
alert(d);
}
</script>
<form name="form">
Phone: <input type="text" size="3" value=""/>
-
<input type="text" name="number" id="number" size="3" value=""/>
-
<input type="text" size="4" value=""/>
<p>
<input type="button" name="b1" value="Grab Code" onclick="calculate()">
</p>
</form>
hope that helps! cheers.

Categories