asking numbers in html, adding in js, printing in html - javascript

here you can see my code im stuck with
trying to input 2 numbers by user in html
calling function then adding those 2 in js
then printing in html
html.
<html>
<head>
<meta charset="utf-8">
<title> JavaScript | Basics</title>
<script src="basics.js" charset="utf-8"></script>
</head>
<body>
<!-- <input type="number" name="a" value="0" id="a">
<input type="number" name="b" value="0" id="b">
<button type="button" onsubmit="window.alert(a+b)" name="button">j</button>
< Start JavaScript Here -->
<form onsubmit='sum(a,b)'>
<label for="a">Input number a</label>
<input type="number" name="a" value="0" id='a'>
<br>
<label for="a">Input number b</label>
<input type="number" name="b" value="0" id='b'>
<button type="submit" name="submit">Submit</button>
<output id="total"></output>
</form>
</body>
</html>
js
// 34343
// window.alert()
function sum(a, b) {
console.log('hello world');
var c;
c.value = parseInt(a) + parseInt(b);
console.log(c.value);
window.alert(c.value);
document.getElementById('total').innerHTML = 'The value of s ' + c.value;
}
// </script>
help please

If you only want to sum the two values there is no need to use Form tag.
The Form tag is usually used to send data to a server for processing.
You can read more about Form tag here https://www.w3schools.com/html/html_forms.asp
Using plain JS your code would be something like this:
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript | Basics</title>
<script src="basics.js" charset="utf-8"></script>
</head>
<body>
<div> <!-- Remove Form-->
<label for="a">Input number a</label>
<input type="number" name="a" value="0" id="a" />
<br />
<label for="a">Input number b</label>
<input type="number" name="b" value="0" id="b" />
<button onclick="sum()" name="submit">Submit</button> <!-- on click calls sum function-->
<output id="total"></output>
</div>
</body>
<script>
function sum() {
let a = document.getElementById('a').value; // get value from 'a' input
let b = document.getElementById('b').value; // get value from 'b' input
console.log('hello world');
let c = parseInt(a) + parseInt(b); // sum value into 'c' variable
document.getElementById('total').innerHTML = 'The value of s ' + c; // adding innerHtml with value of 'c'
}
</script>
</html>

Related

Radio Button failed sometimes to get value

$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm">
<label>True</label>
<input type="radio" id="rbOwner" value="1" name="IsOccupant" required="" />
<label>False</label>
<input type="radio" id="rbOccupant" value="2" name="IsOccupant" required="" />
</form>
<button id="btn">Click Me</button>
I am wondering why sometime my code upon publish failed to determine the checkbox value(Checked checkbox). But when I manually debug it it returns the correct value. Does anyone knows the reason for this?.
Wrap your code inside
$(document).ready(function(){
// Your code goes here
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
})
This will ensure your JavaScript executes only when the document is fully loaded.
To take the values from an input tag kind is necessary to use the .value function instead of .val
Is something similar to this:
<!DOCTYPE html>
<html>
<head>
<title>
Get value of selected
radio button
</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>

Radio Button selected value; choice of 3 options

Using HTML and JavaScript only, I am trying to get the first name, surname details and then a choice of favourite colour from three radio buttons. I can get the first name and surname to work, but cannot do the radio buttons?
HTML file:
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:<input type="text" id="firstName"><br>
Last Name:<input type="text" id="lastName"><br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red">Red<br>
<input type="radio" name="colour" value="Blue">Blue<br>
<input type="radio" name="colour" value="Green">Green<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
JavaScript file:
function display(){
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
alert(firstName + " " + lastName);
}
I have no idea how to implement the radio buttons? I have seen some people using jQuery, but I want to stick to just JavaScript here as I am fairly new.
Thanks.
Js:
var colour=document.querySelector('input[name="colour"]:checked').value;
alert(colour);
Steps:
Add a class to all your input tags named check_in.
Use javascript to find all tags with this class
Iterate through each tag to determine which of them is checked. If a tag is checked add it to the variable named results.
Finally get First name and Last name from input box and add these values to your variable named results
function display() {
results = {}
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var all_input = document.getElementsByClassName('check_in');
for (var i = 0; i < all_input.length; ++i) {
if (all_input[i].checked == true) {
results['option'] = all_input[i].value;
}
}
results['firstname'] = firstName;
results['lastname'] = lastName;
console.log(results);
alert('firstname:' + results['firstname'] + ' lastname: ' + results['lastname'] + ' option: ' + results['option']);
}
margin:50px auto auto;
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:
<input type="text" id="firstName">
<br>Last Name:
<input type="text" id="lastName">
<br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red" class="check_in">Red
<br>
<input type="radio" name="colour" value="Blue" class="check_in">Blue
<br>
<input type="radio" name="colour" value="Green" class="check_in">Green
<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>

Using javascript functions in HTML

I am creating a small webpage that will add two input fields together and place the result in another input field. This is what I have:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function add(){
var num1 = parseInt(document.calc.num1.value);
var num2 = parseInt(document.calc.num2.value);
var answer = (num1+num2);
document.getElementById('res').value = answer;
}
</script>
</HEAD>
<BODY>
<FORM NAME="calc">
<INPUT TYPE ="button" NAME="add" Value="+" onClick="add()">
<hr/>
<INPUT TYPE ="text" NAME="num1" Value="">
<INPUT TYPE ="text" NAME="num2" Value="">
<hr/>
<INPUT TYPE ="text" ID="res" NAME="result" VALUE="">
</FORM>
</BODY>
</HTML>
And I am getting the following error when I press the + button.
Uncaught TypeError: object is not a function
Try changing the function name from add to addNumbers or something like that.
onclick is the right attribute to handle click
onClick="add()"
Switch this bit to
onclick="add()"
The problem is the name of the function "add()", change the name and you will see that it will works!
HTML
<p>
<label for="field1">Field 1</label>
<input type="number" id="field1"/>
</p>
<p>
<label for="field2">Field 2</label>
<input type="number" id="field2"/>
</p>
<p>
<label for="total">Total</label>
<input readonly type="number" id="total"/>
</p>
<p>
<input type="button" id="calc" value="Calculate"/>
</p>
Javascript
Goes in a script tag in head.
function sumFields(fields) {
var total = 0;
// goes through each field and adds them to the total
for(var i=0,l=fields.length; i<l; i++)
{ total += parseInt(document.getElementById(fields[i]).value); }
document.getElementById('total').value = total;
}
function calc_click() {
// runs when the button is clicked
sumFields(['field1','field2']);
}
// main function
function init() {
// add button functionality
document.getElementById('calc').addEventListener('click',calc_click,false);
}
// fires when the DOM is loaded
document.addEventListener('DOMContentLoaded',init,false);

js wont show result of calculation

Quick newbie question, i'm sure it is simple to you, but i cant get my head around to figure out why my code wont work. Checked online, seems that i'm doing everything fine, but still wont work... All i'm trying to do, is to make simple calc and display that in diff field. I have tryed external and internal JS.
Here's my code:
<script type="text/javascript">
function calculate(){
var a = document.calculate.first.value;
var b = document.calculate.second.value;
var c = parseInt(a) + parseInt(b);
document.calculate.result.value = c;
}
</script>
<body>
<form name="calculate">
<input type="text" name="first" size="5">
<input type="text" name="second" size="5">
<input type="button" onclick="calculate()">
<input type="text" name="result" id="result" size="5">
</form>
</body>
Chrome says:
Uncaught TypeError: object is not a function (onclick)
Give a different name to the form and the onclick handler! Here is a test.
Here is the corrected code :
<html>
<head>
<script type="text/javascript">
function calculate(){
var a = document.getElementById('first').value;
var b = document.getElementById('second').value;
var c = parseInt(a) + parseInt(b);
document.getElementById('result').value = c;
}
</script>
</head>
<body>
<form name="calculateform">
<input type="text" id="first" size="5">
<input type="text" id="second" size="5">
<input type="button" onclick="calculate()">
<input type="text" id="result" id="result" size="5">
</form>
</body>
</html>
Its probably because you are using the same name for the form as for your js function.
Working example:
<html>
<head>
<script type="text/javascript">
function calculate(){
alert(document.calculatex.first.value);
var a = document.calculatex.first.value;
var b = document.calculatex.first.value;
var c = parseInt(a) + parseInt(b);
document.calculatex.result.value= c;
}
</script>
</head>
<body>
<form name="calculatex">
<input type="text" name="first" size="5"/>
<input type="text" name="second" size="5"/>
<input type="button" value="calculate" onclick="calculate();"/>
<input type="text" name="result" id="result" size="5"/>
</form>
</body>
Have a look into JQuery library (convenient for getting/setting field values).

getElementById(element).innerHTML cache?

This is my page code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Marketing Tracking</title>
</head>
<body>
<form action="#" id="form" method="post">
<div id="namevalues">
<span id="span:1">
<input type="text" id="name:1" onchange="changed(this)" style="width:300px;"/>
<input id="value:1" type="number" min="0" value="0" /><br /></span>
</div>
<input type="button" id="add" value="Add 1" />
<br />
<textarea name="talk" style="width:500px;height:175px;"></textarea>
<br />
<input type="button" id="update" value="Update"/>
</form>
<script>
function get(a){return document.getElementById(a);}
up=get("update");
up.onclick = function(){
get("form").submit();
}
get("name:1").onchange = function(){changed(this)};
get("add").onclick = function(){add()};<% z=2 %>
function changed(ele){
id=ele.id;
val=ele.value;
id=id.split(":")[1];
get("value:"+id).name=get("name:"+id).value;
}
function add(){
document.getElementById("namevalues").innerHTML+='<span id="span:'+z+'"><input type="text" id="name:'+z+'" onchange="changed(this)" style="width:300px;"/><input id="value:'+z+'" type="number" min="0" value="0" /><br /></span>';
}
</script>
</body>
</html>
I am very confused as to why when I press the Add 1 button enter some text and then press the Add 1 button again the text that I just entered disappears!
If anyone could give some insight to this it would be greatly appreciated.
The reason your other values disappear is because when you do something.innerHTML += something it will rewrite the HTML for that zone (meaning what was there before is gone and will be replaced with fresh new HTML). What you probably want to do is something along this :
function add(){
var div = document.createElement("div");
div.innerHTML = '<span id="span [... the rest of the code ...]<br /></span>';
document.getElementById("namevalues").appendChild(div);
}
Using appendChild won't alter the other element that are already in the div namevalues.
Just a small thing but try using
<script type="text/javascript">
When I was using inner.document stuff I had all kinds of problems until I added that code.

Categories

Resources