Learning Javascript: adding 2 numbers - javascript

I am learning javascript and trying to complete a simple excercise: add 2 numbers that are entered in 2 separate entry field and show the sum on a page. The script below is executed when you press a button. The problem I'm somehow unable to solve is that the result of the addition is always zero. What I am doing wrong here?
var inputA = document.getElementById("numberA");
var convertA = +inputA;
var inputB = document.getElementById("numberB");
var convertB = +inputB;
function myFunction() {
document.getElementById("result").innerHTML = convertA + convertB;
}

You need to take the value of the text input .
var inputA = document.getElementById("numberA").value;
// ^^^^^^
Please move the variables inside into the function, because the value property returns a string and not a referece to the object.
function myFunction() {
var inputA = document.getElementById("numberA").value;
var inputB = document.getElementById("numberB").value;
var convertA = +inputA;
var convertB = +inputB;
document.getElementById("result").innerHTML = convertA + convertB;
}
<input id="numberA" type="text">
<input id="numberB" type="text">
<button onclick="myFunction()">calc</button>
<div id="result"></div>

One example of this is to grab the values and then parse them into Integers before adding them together. Setting a value of 0 on the input prevents the user from getting a result of NaN. You could also remove these initial values and write an if statement to check for empty values.
Anyway here is what I came up with:
<!DOCTYPE html>
<html>
<head>
<title>Test Function</title>
</head>
<body>
<!-- Create Inputs -->
<input id="numberA" type="number" value="0">
<input id="numberB" type="number" value="0">
<!-- Function Button -->
<button onclick="myFunction()">Add Numbers</button>
<!-- Display Result -->
<div id="result"></div>
<!-- Run Script -->
<script>
// Get Inputs by ID
var inputA = document.getElementById("numberA");
var inputB = document.getElementById("numberB");
// Parse Values and Add Integers
function myFunction() {
document.getElementById("result").innerHTML = parseInt(inputA.value) + parseInt(inputB.value);
}
</script>
</body>
</html>

before start coding on Javascript I think that you must be aware about how it interacts with elements in page: every single element, is represented by DOM (Domain Object Model) and Javascript can interact with elements querying this DOM for obtain them, but in the form of their virtual representation: a DOM Object.
That's what your trying to sum... two DOM objects that represents the input elements.
As objects, they have their own properties accessible by the dot sign, and for get the values of those fields, the answer of #Nina Scholz is the way.
So, when you get the element by Id, or elements by tag, by name etc, etc... you have to consider this.

Although not related. Base on Nina Scholz answer, You must take consider the type of input and change it to number so you will not end up with undefined or NaN result.

Related

How can I call functions using onkeypress-events in EJS file?

I'm trying to accomplish a live character counter for a text input field, but cannot seem to make it work. The onkeypress-function either go as undefined or is just called once when loading the page
Simply assigning the function with onkeypress=" " does not seem to work.
Additionally, I want to update the text of charcountLabel; which I cannot seem to do. Simply using 'document.getElementById' for updating its innerHTML does not work.
How do I correctly assign keypress-functions to html-elements in .ejs?
How do I access and update innerHTML of other elements?
See code below:
<input type="text" id="textContent" onkeypress="charcount">
// Should be live-updated with the length of input text above.
<span id="charcountLabel"> 0 </span>
<script>
function charcount() {
var characterCount = document.getElementById("textContent").innerText.length;
document.getElementById("charcountLabel").innerHTML = characterCount;
}
</script>
Here you are
<input type="text" id="textContent" onkeypress="charcount()">
<!-- Should be live-updated with the length of input text above. -->
<span id="charcountLabel">0</span>
<script>
function charcount() {
var characterCount = document.getElementById("textContent").value.length;
document.getElementById("charcountLabel").innerHTML = characterCount;
}
</script>
Use parenthesis () to call the function and replace innerText with value property.
Note that // is comment in Javascript, not in html where you should use <!-- your comment --> instead.
Last, it has nothing to do with ejs.

Problems when passing the text box input to another page - specifically first name and lastname in javascript and html

I am new to JavaScript coding with html and the things that's bugging me right now is passing a variable to another page in java script.
So my codes for the first page are:
<html>
<head><title>lol1</title></head>
<body>
<form action="lol2.html">
<input type="text" name ="firstname" placeholder="First Name">
<input type="text" name="lastname" placeholder="Last Name">
<input type="Submit" value="Submit" >
</form>
</body>
</html>
and second page are:
<html>
<head>
<title>
lol2
</title>
</head>
<body>
<script>
var queryString = decodeURIComponent(window.location.search);
var queries = queryString.split();
document.write(queries);
</script>
</body>
</html>
After I enter the value in the text box it takes me to the second page but the result is shown like this:
so how do i get rid of the "firstname=" and "Secondname="? or find an effective way to solve problem.
JavaScript has a built in method for this: URL() and searchParams
You can use it like:
let params = (new URL(document.location)).searchParams;
let firstname = params.get("firstname");
let lastname = params.get("lastname");
Your problem really doesn't have anything to do with textboxes or forms or passing data from one page to another. It's simply a matter of how you are attempting to extract the querystring.
You must pass a string to the .split() method for it to actually perform the split:
var queryString = "firstName=Scott&lastName=Marcus";
var queries = queryString.split("&"); // <-- You weren't passing a string to split on
// Get each name/value pair:
console.log(queries[0]);
console.log(queries[1]);
// Get just the values:
console.log(queries[0].split("=")[1]);
console.log(queries[1].split("=")[1]);
You can use URLSearchParams, specifically the URLSearchParams.values() method to get just the values. Just keep in mind browser compatibility if you are going to use this on the web.

Converting text to lowercase/uppercase with a pending a radio button

I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE

Perform a split on AttributeResource tag

I have a WCM HTML component, and the value stored inside [AttributeResource attributeName="myKey" separator=","] is a comma separated String.
When rendered on its own, I get the following output on my HTML page ..
8,9,10,10.5,11,11.5,12,13
However, when I try to split it on ,, it only gives me the first element i.e 8
How can I split this properly?
<script>
var keySplit = String([AttributeResource attributeName="myKey" separator=","]).split(',');
alert(keySplit);
</script>
Used a hidden input element to temporarily store values ..
<input type="hidden" id="myKeyTemp" value="[AttributeResource attributeName="myKey" separator=","]" />
<script>
var arrayOfValues = document.getElementById("myKeyTemp").value.split(',');
</script>

Abnormal behaviour of JavaScript with checkbox

I used the following code:
<html>
<head>
<script type="text/javascript" language="javascript">
function doit(page) {
var entry = page.entry;
var flag = false;
document.write(entry.length);
}
</script>
</head>
<body>
<span id="error_checkbox" style="color: blue;"> </span>
<form name="subscribeTablePage">
<input type="checkbox" id="entry" value="1"/> <label>1</label><br/>
<input type="button" value="Submit" onclick="doit(document.subscribeTablePage)"/>
</form>
</body>
</html>
Why is the value of entry.length undefined? At the same time when I tried with multiple checkboxes, the value of entry.length was the number of checkboxes used!
Use Case :
I am going to retrieve rows from Database and in that case I need to check the number of checkboxes checked to perform deletion operation !! Please give ur valuable comments to sort this problem
entry is id of your input
it should be name if you want to refer it in that way..
<input type="checkbox" name="entry" id="entry" value="1"/>
To access it form element by id you have to use
document.getElementById('idOfElement')
Also I dont find your objective for using length. you can get size of the input not length.
If you want to find number of checkboxes checked then probably in javascript you can check by writing a script as below
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true) {
count++;
}
}
You are trying to access the checkbox #entry. add the attribute name="entry" like so.
<input type="checkbox" id="entry" name="entry" value="1" />
Form objects are accessed by their name property.
As for the Javascript, you want value, not length.
document.write(entry.value);
length represents the length in characters of a given string.
Why is the value of entry.length undefined?
Because form.entry references the element, and the element doesn't have a length property. You want:
entry.value.length;
At the same time when I tried with multiple checkboxes, the value of entry.length was the number of checkboxes used!
Because if more than one form control has the same name, form.controlName references a collection of all the controls with the same name. HTML Collections have a length property that is the number of elements in the collection.
Also, the line:
> document.write(entry.length);
will clear the entire document, likely you want:
alert(entry.value.length);
// or
console.log(entry.value.length);
You may find it useful to read the entire section about forms in the HTML 5 specification, and also relevant parts of the HTML 4.01 standard.

Categories

Resources