Why does my simple unit converter function display undefined? - javascript

I'm learning JS and creating this simple kitchen unit converter as an exercise in function writing. I've written what I think is correct syntax, but when I hit submit, the alert box shows an undefined value:
Screenshot: After clicking submit, the alert box shows undefined instead of the expected value calculated by the function.
Since writing the code, I've spent a few hours reading up on undefined values, function syntax, returns, and similar projects, and haven't found the issue yet. I've used this simple HTML structure (The different unit buttons in the drop-down don't do anything yet, but that's for another time.):
<body>
<h1>Kitchen Calculator</h1>
<form action="/script.js">
<input type="text" id="input-1" name="First Amount">
<div class="dropdown">
<button class="dropbtn">Units</button>
<div class="dropdown-content">
<button>Teaspoon</button>
<button onclick="">Tablespoon</button>
<button onclick="">Cup</button>
<button onclick="">Quart</button>
<button onclick="">Pint</button>
<button onclick="">Liter</button>
<button onclick="">Dash</button>
<button onclick="">Pinch</button>
</div>
</div>
=
<input type="text" id="input-2" name="Second Amount">
<div class="dropdown">
<button class="dropbtn">Units</button>
<div class="dropdown-content">
<button onclick="">Teaspoon</button>
<button onclick="">Tablespoon</button>
<button onclick="">Cup</button>
<button onclick="">Quart</button>
<button onclick="">Pint</button>
<button onclick="">Liter</button>
<button onclick="">Dash</button>
<button onclick="">Pinch</button>
</div>
</div>
<input type="submit" value="Submit" onclick="convertUnits(unit1, unit2)">
</form>
<script src="script.js"></script>
</script>
</body>
And here's my JS. I've just created two variables to hold the user input and added them together in an arrow function, so I'm not sure where the mistake is. I'm sure it's a noob sort of mistake though. I'm at that stage in my journey:
// Select the input element and get its value
let unit1 = document.getElementById("input-1").value;
let unit2 = document.getElementById("input-2").value;
let convertUnits = (unit1, unit2) => {
let conversion = unit1 + unit2;
// Display the value
alert(conversion.value);
};
Any help is very much appreciated.

You read the element value when the code is evaluated. You need to read the value when the user clicks the button.
const unit1 = document.getElementById("input-1");
const unit2 = document.getElementById("input-2");
const convertUnits = (evt) => {
evt.preventDefault();
const conversion = Number(unit1.value) + Number(unit2.value);
alert(conversion);
};
document.querySelector('#btnCalc').addEventListener("click", convertUnits);
<input id="input-1" />
<input id="input-2" />
<button type="button" id="btnCalc">Click me</button>

let btn = document.querySelector(".click");
btn.addEventListener("click", function () {
let unit1 = Number(document.querySelector(".unit1").value);
let unit2 = Number(document.querySelector(".unit2").value);
let conversion = unit1 + unit2;
alert(conversion);
});
Blockquote

Related

showing the result of multiply two input value in a div called result

I just want to show the result in this div ,i tried to use nodeValue instead value and call the finalCalc fun in js file but it show nothing when i click on the button.
var billValue=document.getElementById("dollars").value,
peopleValue=document.getElementById("people").value,
theResult=document.getElementById("result"),
calculateButton=document.getElementById("calculateButton");
function calculateTip(x,y){
var reso=x*y;
theResult.innerHTML=reso;
}
function finalCalc() {
calculateTip(billValue,peopleValue);
}
<form>
<label>how much was your bill?</label>
<label for ="dollars">$</label>
<input value ="0" type="text" id="dollars" placeholder="Bill Amount ">
<br>
<label for="people">How many people are sharing the bill?</label>
<input value ="0" type="text" id="people">
<button type="button" id="calculateButton" onclick()="finalCalc()">CALCULATE</button>
<div id="result"></div>
</form>
onClick is written as onClick="" instead of onclick()="", reworked your code a little, hope this helps.
var billValue = document.getElementById("dollars").value,
peopleValue = document.getElementById("people").value,
theResult = document.getElementById("result"),
calculateButton = document.getElementById("calculateButton");
function calculateTip(x, y) {
return x * y;
}
function finalCalc() {
theResult.innerHTML = calculateTip(billValue, peopleValue);
}
<button type="button" id="calculateButton" onClick="finalCalc()">CALCULATE</button>

Create HTML text in an HTML form and open up the text in a Javascript alert box

I'm new to coding and need to create HTML text in an HTML form on a page and open up the text in a Javascript alert box. I've tried various code to no success. Here is what I've come up with so far which does not create a pop up alert box:
Here is the HTML and the JS:
Function myfunction1()
{
Let myfun1 = document.getElementById('sec1-input').value;
Alert(myfun1);
}
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
I'm not sure what do you want, but I'll show you how to make an alert window exactly as you're asking.
First of all you must consider several mistakes that you are making. JavaScript does not recognize the word Function because it is capitalized. The function keyword must be lowercase.
Here I leave you a referring link with JavaScript reserved words: https://www.w3schools.com/js/js_reserved.asp
On the other hand, I see that you are not using the form tag, which leads to two problems: technical and semantic. Here I leave you another link with reference to forms: https://www.w3schools.com/html/html_forms.asp
Finally, to achieve what you want you need to work with events, especially with the click event. Here I will leave you a reference link and the solution you want:
let button = document.querySelector('#sec1-btn1');
button.addEventListener('click', function(e) {
let val = document.querySelector('#sec1-input').value;
alert(val);
});
<form>
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input" />
</div>
<button id="sec1-btn1" type="button" class="btn btn-primary">
Alert Me!
</button>
</form>
You have not called the function anywhere. For it to work you need to use a listener.
<div class="form-group">
<label for="sec1-input"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button onclick="myfunction1()" id="sec1-btn1" type="button" class="btn btn-primary">Alert Me!</button>
<script>
function myfunction1() {
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1)
}
</script>
I added the onClick listener to button and now it works.
javaScript is case sensitive
function myfunction1()
{
let myfun1 = document.getElementById('sec1-input').value;
alert(myfun1);
}
<div class="form-group">
<label for="sec1-label"><strong>Enter Alert Text: </strong></label>
<input type="text" class="form-control" id="sec1-input">
</div>
<button id="sec1-btn1" type="button" onClick="myfunction1()" class="btn btn-primary">Alert Me!</button>
also IDs of elements should not be the same , to assign same selector , use class and you also need to give your function to your element's event listener
You should not start javascript functions like alert with capital letters.
Put this piece of code instead of your button:
<button id="sec1-btn1" type="button" class="btn btn-primary" onclick="myfunction1()">Alert Me!</button>

How can I call a function multiple times from different buttons?

I am building a quiz page using javascript, and want the user to select from a multiple choice and then hit 'Go' to check their answer. Here is the html for the first question:
<p class="question">What is the name of Joey's bedtime penguin pal?</p>
<div class="radio">
<div>
<input type="radio" class="wrong" name="q1">Maurice
</div>
<div>
<input type="radio" class="wrong" name="q1">Clunkers
</div>
<div>
<input type="radio" class="right" name="q1">Hugsy
</div>
<div class="button">
<button type="button" class="go">Go</button>
</div>
<div>
<img src="images/hugsy.jpg" class="image" style="display: none;"
</div>
I have created a function which is called by the Go button which informs the user if they are right or not. Here is the javascript:
let go = document.querySelector('.go');
let correct = document.querySelector('.right');
let showPic = document.querySelector('img');
let remGo = document.querySelector('button');
let choices = document.querySelector('.radio');
let score = 0;
go.addEventListener('click', checkAnswer);
function checkAnswer() {
if (correct.checked) {
showPic.classList.remove('image');
remGo.remove();
choices.innerHTML = '<h2 style="color: green;">Correct!</h2>';
score++;
} else {
remGo.remove();
choices.innerHTML = '<h2 style="color: red;">Incorrect</h2>';
}
}
This code works the way I want it to but only for the first question. When I try to call the function again by clicking 'Go' on question 2 nothing happens.
Is there a way to call a function multiple times using different buttons?
document.querySelector('.go');
only selects the first matching element.
To select all elements with the .go class you need to use querySelectorAll
Then you'll need to assign your event listener to all elements returned.
Here is a minimal example:
let buttons = document.querySelectorAll('.go');
for (const button of buttons) {
button.addEventListener('click', checkAnswer);
}
function checkAnswer() {
console.log("checkingAnswer...")
}
<div class="button">
<button type="button" class="go">Go</button>
</div>
<div class="button">
<button type="button" class="go">Go</button>
</div>
<div class="button">
<button type="button" class="go">Go</button>
</div>
Thanks to those who helped. I have solved my issue now using jquery. This was the code I used:
$(".container").on("click", "button", function (e) {
var container = $(e.target).closest(".container");
if ($(container).find("input:checked").hasClass("right")) {
$(container).find("img").show();
$(container).find("button").remove();
$(container).find(".radio").html('<h2 style="color: green;">Correct!</h2>');
score++;
} else {
$(container).find(".radio").html('<h2 style="color: red;">Incorrect</h2>');
}
});

Display input value in a button

I have an input field and a button next to it, what i want to do is whatever i type in the input field then click on the button next to it, the result gets displayed in another button, here is what i tried so far:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
document.getElementById("btnresult").value = result;
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
https://jsfiddle.net/sheriffderek/p2LoLcv3/
I think this is what you are describing...
Some simplified markup
<div class="parent">
<input type='button' value='Add' rel='action' /><br>
<input type='text' rel='text-input' />
</div>
<ul class='button-list' rel='button-list'>
<!-- you need to put the buttons somewhere, right? -->
</ul>
jQuery was one of the tags, so I used it
// just caching some thing that will be reused (I like using rel)
var $parent = $('.parent'); // whatever - to keep some scope
var $addButton = $parent.find('[rel="action"]');
var $textInput = $parent.find('[rel="text-input"]');
var $buttonList = $('[rel="button-list"]');
$addButton.on('click', function() { // on click...
var currentInputValue = $textInput.val(); // get the value from input...
$buttonList.append('<li><button>' + currentInputValue + '</button></li>'); // append a new button...
$textInput.val(''); // clear input
});
You're almost there, you have to unhide the button you've hidden in the first place, and not set a value for a button, but rather the innerHTML property. Since a button doesn't hold a value, but displays the content between the tags as text.
I've commented my changes:
function add_keyword() {
var keyword_value = (document.getElementById("keyword").value);
var result = keyword_value;
// Changed from .value to .innerHTML
document.getElementById("btnresult").innerHTML = result;
// Changed style from to 'block'
document.getElementById("btnresult").style.display = "block"
}
#btnresult{
display: none;
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>
<button type="button" id="btnresult" class="btn btn-default">input value should be here</button>
In addition, there are several aspects of your code that could use improvement, I described them below:
function add_keyword() {
// No need for parentheses around the document.getElement function.
var keyword_value = document.getElementById("keyword").value;
// There's no need to place the value in a new variable, it is useful to place the element you wish to replace in a variable, since we'll be re-using it's instance.
var btn = document.getElementById("btnresult");
btn.innerHTML = keyword_value;
btn.style.display = "block"
}
EDIT: Since OP's goal was to create a new button with the content, this is an updated version that generates a new button for every new input.
function add_keyword() {
var keyword_value = document.getElementById("keyword").value;
// Create a new button element.
var btn = document.createElement("button");
// Set it's content to the keyword from the input.
btn.innerHTML = keyword_value
// Append it to the body.
document.body.appendChild(btn);
}
<button type="button" class="btn btn-default" name="clickbtn" value="Add Keyword" onclick="add_keyword()">Add</button>
<div class="input-group">
<input type="text" class="form-control" id="keyword" name="keywordbox"/>
</div>

Javascript does not write innerHTML of element but flashes result?

In this simple program, the script does not write result id="result" just flashes the resultant value. Can anybody take a look and show why this behavior? What am I doing wrong?
function multiplication() {
var product,
no1 = document.getElementById('no1').value,
no2 = document.getElementById('no2').value;
product = no1 * no2;
document.getElementById("result").innerHTML = product;
}
function division() {
var divis,
no1 = document.getElementById('no1').value,
no2 = document.getElementById('no2').value;
divis = no1 / no2;
document.getElementById("result").innerHTML = divis;
}
<h2>Write a JavaScript program to calculate multiplication and division of two numbers ?</h2>
<h3>Sample Form</h3>
<form name="sample" method="POST">
1st Number:
<input type="text" id="no1" name="firstno" /> 2nd Number:
<input type="text" id="no2" name="secondno" />
<button id="mul" onclick="multiplication();">Multiply</button>
<button id="div" onclick="division();">Division</button>
</form>
<p id="result"></p>
The submit button is clicked
The JavaScript runs
The form is submitted
A new page is loaded
The new page doesn't have the DOM changes that were on the old page.
Either prevent the default behaviour of the submit button or bind your event handler to a different kind of control.
Your JS is working but when the user clicks a submit button the form is also submitted, because that's the default action.
Prevent the form from submitting.
<form onsubmit="event.preventDefault();" name="sample" method="POST">
<button type="button" id="mul" onclick="multiplication();">Multiply</button>
<button type="button" id="div" onclick="division();">Division</button>
This might help you.

Categories