Accessing and manipulating HTML input using JavaScript - javascript

I'm an new amateur programmer that is having trouble using HTML and JavaScript together. We were tasked to make a simple program that asks us what's the maximum number, I made the logic but still having trouble with this case.
Currently this is the progress with my code
var num1;
var num2;
var num3;
var max;
if (num1 < num2) {
if (num2 < num3) {
num3 = max;
} else if (num2 > num3) {
num2 = max;
}
} else if (num1 > num2) {
if (num1 > num3) {
num1 = max;
} else if (num1 < num2) {
num2 = max;
}
}
alert("The maximum number is: " + max);
<h1>Laboratory 06</h1>
<p>2. Write a JavaScript program to determine the maximum number using 3 input box.</p>
<blockquote>
<label for=num1>First number:</label><br>
<input type="text" id="a" name=num1><br><br>
<label for=num2>Second number:</label><br>
<input type="text" id="b" name=num2><br><br>
<label for=num3>Third number:</label><br>
<input type="text" id="c" name=num3><br><br>
<button type="button">Enter</button>
</blockquote>

The main problem with your code is that it runs straight away, long before a user has entered any number. The next problem with it is that you never read the values from the inputs.
What you instead want is for the code to wait until an event occurs - which, in your case is the event, that the user clicks the Enter button.
For reacting to user actions (and more), Javascript has the concept of eventListeners, which you can add to any element. There is many different types of events; the one you care about here is the click event.
To add it to the button, you first need your Javascript to learn where your button element is. To find it in the page, Javascript offers the document.querySelector() method.
Once you have found it, you can call the addEventListener() method on the element (all HTML elements have this method built-in).
For an explanation of the rest, check the source code comments (lines that begin with //):
// first we need to find the button in the page,
// so we can access it in our Javascript
// the following finds the first <button> element in the page.
const button = document.querySelector('button');
// every HTML element has a addEventListener method
// that takes two arguments:
// the first is the name of the event you want to listen to (String),
// the second is a function that will be executed every time
// the event occurs.
button.addEventListener('click', function() {
// when the user clicks the button, we read what is in the inputs.
// to do that, we first need our JS to find the inputs.
// in this case this is especially easy because each of them has a
// unique identifier (id), so we can use
// document.getElementById(id)
// to find it.
// Once found, we immediately read the value from the input.
let aValue = document.getElementById('a').value;
let bValue = document.getElementById('b').value;
let cValue = document.getElementById('c').value;
// because the value of any input element is always a String,
// we now convert it to a Number.
aValue = parseFloat(aValue);
bValue = parseFloat(bValue);
cValue = parseFloat(cValue);
// now we use another built-in object, Math, and on it, the
// Math.max function, to find the largest number.
const maxValue = Math.max(aValue, bValue, cValue);
// to output the maxValue, we use console.log rather than
// alert. To see the output in the browser, open the browser's
// developer tools (F12 on Windows), and click the "Console" tab.
// To make sure not to output anything if no number was entered
// before the button was clicked, we check if maxValue is a proper
// number. Javascript has the NaN datatype (Not a Number),
// and you can check for it using isNaN(variable)
if (!isNaN(maxValue)) { // if maxValue is not "Not a number"
console.log("The maximum number is: " + maxValue);
}
})
<h1>Laboratory 06</h1>
<p>2. Write a JavaScript program to determine the maximum number using 3 input box.</p>
<blockquote>
<label for=num1>First number:</label><br>
<input type="text" id="a" name=num1><br><br>
<label for=num2>Second number:</label><br>
<input type="text" id="b" name=num2><br><br>
<label for=num3>Third number:</label><br>
<input type="text" id="c" name=num3><br><br>
<button type="button">Enter</button>
</blockquote>

Related

Error with Javascript TypeError code, variable undefined

I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.

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();">

How to calculate the total value of a dynamic number of fields using javascript?

My page shows some forms with content loaded from a database. Every row will get his own <input>. The ID of this input is equal for every row, except for the number that is attached to it, to make it unique. To make it more clear; this is how the form looks like when it loads 3 rows from the database:
<form>
<input id="Amount1" value="<?php echo $databaseValue; ?>" >
<input id="Amount2" value="<?php echo $databaseValue; ?>" >
<input id="Amount3" value="<?php echo $databaseValue; ?>" >
<input type="hidden" name="numberOfRows">
<input id="finalResult">
</form>
This is all done with the mysqli_array function. The value of numberOfRows is based on numRows function.
What I'd like to achieve is that javascript calculates the value of each existing input and put the result in finalResult, regardless the number of forms (because this may vary). If I make some changes to one of the values, the finalResult should update real-time.
What I've tried so far:
formnum contains the number of fields.
var a is created at the beginning, starting at 0. Inside it's function I create an ID, matching the fields on the page. All fields are named "Amount" + number. If this number equals the number of fields, the function will stop. This way the script won't be looking for fields that doesn't excist.
Then it gets the value of this field and adds the value to var b. var b is just created to store the value temporary, untill the function's over.
At the end the total is divided to 15. This is something extra I need. Nothing special on this line.
My code:
<script type='text/javascript'>
$(document).ready(function(){
var formnum = $("#numberOfRows").val();
var a;
var b = 0;
var formname = '#Amount';
for (a = 0; a < formnum; a++) {
var complete = formname.concat(a);
var completeContent = $(complete).val();
b = b + completeContent;
};
b = b.toFixed(2);
});
$(document).mousemove(function(event){
var formula_finalResult = b / 15;
var total_finalResult = Math.floor(formula_finalResult);
$("#finalResult").val(total_finalResult);
});
</script>
This doesn't do anything. It doesn't change the value. What's going wrong?
Make it simple:
$(function(){
var sum = 0;
// Selector to select all input whose id starts with Amount
$("input[id*='Amount']").each(function(){
sum += +$(this).val(); // Parsing as int and adding it to sum
});
$("#finalResult").val(Math.floor(sum/15)); // Storing the values
})
Assuming that all of the fields always have Amount at the beginning of their id attribute, you could use jQuery's ID selector to achieve this, without the need for any of the internal counters, etc.
I'm not entirely sure why you need to hook into the mousemove event, since the data should never change on the page (since it's being generated by PHP when the page is first loaded). The following code should achieve what you're looking for:
$(function() {
var total = 0;
$('input[id*="Amount"]').each(function() { total+= parseFloat( $(this).val() ); });
$('#finalResult').val( Math.floor( total / 15 ) );
});
Your code has an error Uncaught ReferenceError: b is not defined
see it in action here: http://jsfiddle.net/ca9vascj/
There's no reason to bring the mousemove event into this, I'm not even sure what that was needed for.
Like the above answers, here's a much simplified version. But instead of a partial ID selection, let's just give the form an ID, and then give all the needed elements inside that form a class that we can select by. We also no longer need to have the numberOfRows form element.
<form id="theForm">
<input class="formAmmount" value="5" />
<input class="formAmmount" value="10" />
<input class="formAmmount" value="27.5" />
<input class="formAmmount" value="4" />
<input class="formAmmount" value="9" />
<hr />
<input id="finalResult" />
</form>
And then our jQuery code can be reduced to this:
$(function(){
var total = 0;
$("#theForm .formAmmount").each(function(){
total += parseFloat(this.value, 10);
});
var final = Math.floor(total.toFixed(2) / 15);
$("#finalResult").val(final);
});
See it in action here: http://jsfiddle.net/ca9vascj/1/
You dont'need jQuery. The simplest way to do this is document.getElementsByTagName:
var inputs = document.getElementById('my-form').getElementsByTagName('input')
That's it. inputs.length will always get an actual count of inputs in your form. That's because getElementsByTagName() returns a NodeList object, containing a live view of the matching elements. This object is mutable; it will change in response to DOM mutations.
So if you need to get sum from all of the inputs:
function sum() {
var result = 0;
[].slice.call(inputs).forEach(function(input){
result += parseFloat(input.value)
});
return result;
}
If you are able to change the generated Html-Source I would suggest to give a new class to your InputElements.
<input id="Amount1" class="ElementToCount" value="<?php echo $databaseValue; ?>" >
Then you can calculate like that
var getSumOfElements = function() {
var Elements = $('.ElementToCount')
var sum=0
if (Elements && Elements.length>0) {
for (var i=0; i<Elements.length; i++) {
sum += Elements[i].val();
}
}
return sum
}
And to update the field you could register to the 'change'-Event
$('.ElementToCount).on('change', function() {
$('#finalResult').val(getSumOfElements());
})

How to take absolute value in math function in javascript

I am trying to minus the value of "f1" from "f2" it works fine. However i want it just once but when i click the submit more more button it reduces every time the value of f1 from f2. How can it be done only once. It works well when i put value instead of when i call it from script.
<form name=bills>
<p><input type="text" name="f1" size="20">
<input type="text" name="f2" size="20" value="30"></p>
<input type="button" value="Submit" onclick="cbs(this.form)" name="B1">
<Script>
function cbs(form)
{
form.f2.value = (([document.bills.f2.value] * 1) - (document.bills.f1.value * 1))
}
pls help
The absulute value in math function in JavaScript is Math.abs();
Math.abs(6-10) = 4;
Not sure exactly what you're trying to do, but to calculate absolute value use Math.abs().
If you want the function to only work once, you can have something like this:
hasBeenRun = false; //have this variable outside the function
if(!hasBeenRun) {
hasBeenRun = true;
//Run your code
}
Your question seems to be asking how to only subtract f1 from f2 only once, no matter how many times the submit button is clicked. One way to do it would be to have a variable that tracks if the function has been called already, and don't do the calculation if it has. As for the title mentioning absolute value, this is called by Math.abs(value)
<Script>
var alreadyDone = false;
function cbs(form)
{
if (alreadyDone) return;
// this one takes the absolute value of each value and subtracts them
form.f2.value = (Math.abs(document.bills.f2.value) - Math.abs(document.bills.f1.value));
// this one takes the absolute value of the result of subtracting the two
form.f2.value = (Math.abs(document.bills.f2.value - document.bills.f1.value));
alreadyDone = true;
}
In order to get the function to be able to work again when the value of f1 changes, simply change the variable alreadyDone back to false when f1 changes
<input type="text" name="f1" onChange="alreadyDone=false;" size="20">

In Javascript, Value not comming instead the variable name is displayed

function ProvideValue(){
Values = document.getElementById('HiddenValue').value;
FirstCut = Values.split("###"); // This will return the array ID#-#VALUE#-#TYPE
var CtrlId;
for (i = 0; i < FirstCut.length - 1; i++) {
Strings = FirstCut[i];
SecondCut = Strings.split("#-#");
if(SecondCut[2].match("TEXT")) {
CtrlId = "" + SecondCut[0];
document.getElementById(CtrlId).value = SecondCut[1];
}
}
}
This is my code instead of the Id, which i can print it.But CtrlId is not replaced by the actual value. Am getting error document.getElementById(CtrlId).value is NULL. I tried to hard code the ID then its working fine but i cannot hard code the controlsID because there are 1000s of control and everytime the ID changes.
Your code seems fine (apart from implied globals1), you must have some other problem in your HTML document... I'm also not sure why you're leaving out the last value from the first cut since you're interating to length - 2, because i is less than length - 1 (not less than or equal) which means that it goes all the way to value length - 2 and then breaks the loop.
Here's a JSFiddle I created that uses your code and displays some additional console messages and actually applies values to inputs as provided by the hidden input.
1Important
I applied var to your variables so they're not implied globals which should be avoided at all times because they're nothing but evil friend of hidden bugs.
The code I used
HTML is super simple but I do have both elements with IDs that are being addressed in the compound value of the hidden field:
<input type="hidden" id="hidden" value="me#-#Rob#-#text###you#-#Mike#-#text" />
<input id="me" value="name" />
<input id="you" value="name" />​
Script is simple as well (runs on DOM ready for JSFiddle simplicity reasons):
var vals = document.getElementById('hidden').value;
var firstCut = vals.split("###");
for(var i = 0; i < firstCut.length; i++) {
var ctrl = firstCut[i].split("#-#");
if (ctrl[2].match("text")) {
var id = ctrl[0];
document.getElementById(id).value = ctrl[1];
}
}​

Categories