I made a simple html with an input and h1
<body>
<input type="number" name="number">
<h1>Result</h1>
<button>Submit</button>
<script type="text/javascript" src="kalantzakisCalculator.js">
</script>
</body>
And a simple calculation .
const val = Number(document.getElementsByTagName('input')[0].value);
const h1 = document.querySelector('h1');
const button = document.querySelector('button');
button.addEventListener('click', function(val) {
let result = val + (val * 0.2);
h1.textContent = result;
});
The calculation is not showing properly on h1....
The val parameter is a MouseEvent interface object of the click event.
I've renamed (val to inputNumber) and moved it inside addEventListener.
Working code below:
<body>
<input type="number" name="number">
<h1>Result</h1>
<button>Submit</button>
<script type="text/javascript">
const h1 = document.querySelector('h1');
const button = document.querySelector('button');
// >>val<< is a MouseEvent
button.addEventListener('click', function(val) {
let inputNumber = Number(document.getElementsByTagName('input')[0].value);
let result = inputNumber + (inputNumber * 0.2);
h1.textContent = result;
});
</script>
</body>
Tip: In Chrome, use F12 for Debugging.
When the callback function is invoked by the event (click) the outside code of the function is not executed, only the code inside the function is executed.
Declare variable val inside the function:
const button = document.querySelector('button');
const h1 = document.querySelector('h1');
button.addEventListener('click', function() {
const val = Number(document.getElementsByTagName('input')[0].value);
let result = val + (val * 0.2);
h1.textContent = result;
});
<input type="number" name="number">
<h1>Result</h1>
<button>Submit</button>
Related
I am a new learner and I am facing a problem. I want to create a simple messaging app and I want that if there is no text inside the input field then the button should be disabled. Help me out.
Here is the code:
let sendMessage = document.getElementById("sendMessage");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
if (val.value === "") {
sendMessage.disabled = true;
} else {
sendMessage.disabled = false;
}
});
<div id="messages"></div>
<input type="text" id="val" />
<button id="sendMessage">Send</button>
You should use input event to set disabled to false or true. Set disabled to true by default and after button was clicked.
let sendMessage = document.getElementById("sendMessage");
let input = document.getElementById("val");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
sendMessage.disabled = true;
});
input.addEventListener("input", () => {
if(input.value.length > 0){
sendMessage.disabled = false;
} else {
sendMessage.disabled = true;
}
});
<body>
<div id="messages"></div>
<input type="text" id="val"/>
<button id="sendMessage" disabled>Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Simply create a disabled class for the button if you use custom button.
Then listen to the input change and toggle the class on button if the input have value.
With your code :
const button = document.getElementById('sendMessage');
const input = document.getElementById('message-input');
const messagesBox = document.getElementById('messages');
input.addEventListener('input', () => sendMessage.disabled = input.value === '');
button.addEventListener('click', () => {
let p = document.createElement('p');
let pTxt = document.createTextNode(input.value);
p.appendChild(pTxt);
messagesBox.appendChild(p);
});
<body>
<div id="messages"></div>
<input type="text" id="message-input" />
<button id="sendMessage" disabled >Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Set a keyup input handler for the input field and a click handler for the button. In the snippet event delegation is used.
document.addEventListener(`input`, handle);
document.addEventListener(`click`, handle);
function handle(evt) {
const isInput = evt.target.closest(`#val`);
const isBttn = evt.target.closest(`#sendMessage`);
if (isInput) {
document.querySelector(`#sendMessage`).disabled = !isInput.value.trim();
}
if (isBttn) {
isBttn.disabled = isBttn;
const inputField = document.querySelector(`#val`);
document.querySelector(`#messages`).insertAdjacentHTML(`beforeend`,
`<li>${inputField.value.trim()}</li>`);
inputField.value = ``;
inputField.focus();
}
}
<ul id="messages"></ul>
<input type="text" id="val" />
<button id="sendMessage" disabled>Send</button>
Like the title says, I would like to simplify this JavaScript so that I have one addAndSubtract function for the buttons.
I am quite new and I have no idea how to go about it.
Here is the code:
let add= document.querySelector("#add");
let subtract = document.querySelector("#subtract");
add.addEventListener("click",function(){
let output = document.querySelector("#output");
let result = Number(output.innerText) + 1;
if (result >10){
result = 10;
}
output.innerText = result;
});
subtract.addEventListener("click",function(){
let output = document.querySelector("#output")
let result = Number(output.innerText) - 1;
if (result<0){
result=0;
}
output.innerText = result;
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script defer src="script.js"></script>
<title>Counter</title>
</head>
<body>
<h1>Le Count!</h1>
<div class = "Counter_Container">
<button id="subtract">-</button><span id="output">0</span><button id="add">+</button>
</div>
</body>
</html>
You can read the ID of the button being clicked in the handler, and act accordingly. (The switch could be a series of ifs too.)
function handleClick(event) {
const action = event.target.id;
const output = document.querySelector("#output");
let value = parseInt(output.innerText);
switch (action) {
case "add":
value++;
break;
case "subtract":
value--;
break;
}
value = Math.min(10, Math.max(value, 0)); // clamp to 0..10
output.innerText = value;
}
document.querySelector("#subtract").addEventListener("click", handleClick);
document.querySelector("#add").addEventListener("click", handleClick);
<h1>Le Count!</h1>
<div class="Counter_Container">
<button id="subtract">-</button><span id="output">0</span><button id="add">+</button>
</div>
Create a single function which takes your result number and add/subtract as parameter.
function eventer(result_param, arithmat){
let output = document.querySelector("#output")
if(arithmat){
let result = Number(output.innerText) + 1;
}else{
let result = Number(output.innerText) - 1;
}
if (result<result_param){
result=0;
}
}
Always try to make your similar code converted to reusable functions and if_else to ternary operators.
You need to create a function as following
function operation(val,maxvalue,minvalue){
let output = document.querySelector("#output")
let result = Number(output.innerText) + val;
if (result<minvalue){
result=minvalue;
}
if (result>maxvalue){
result=maxvalue;
}
output.innerText = result;
}
And use as below
let subtract = document.querySelector("#subtract");
subtract.addEventListener("click",operation.bind(this,-1,10,0))
let add = document.querySelector("#add");
add.addEventListener("click",operation.bind(this,1,10,0))
Let me know if you face any issue
Just add a data attribute to each button that describes the operation that should be performed. Use the same click handler and check the attribute for which operation should be performed.
It's also easier to keep track of the value in a scoped variable too.
let value = 0;
const output = document.querySelector("#output");
const buttons = document.querySelectorAll(".operation");
const operations = {
add: () => value = Math.min(++value, 10),
subtract: () => value = Math.max(--value, 0)
};
const setOutput = () => {
output.innerText = value;
};
// set initial output value
setOutput();
[...buttons].forEach((button) => {
button.addEventListener('click', (e) => {
const operation = e.target.dataset.operation;
let func = operations[operation];
func && func();
setOutput();
});
});
<h1>Le Count!</h1>
<div class="Counter_Container">
<button id="subtract" class="operation" data-operation="subtract">-</button>
<span id="output"></span>
<button id="add" class="operation" data-operation="add">+</button>
<button id="multiply" class="operation" data-operation="multiply">*</button>
</div>
I wanted to add a Character counter to my website. Therefore I have a span with id="counter" and a input type="texture" with id="producttext". I started my Code with a :
document.addEventListener('keyup', function test() {
var textEntered, a;
textEntered = document.getElementById('producttext').value;
a = document.getElementById('counter');
a.innerHTML = textEntered;
});
But the output is not the count of the character. It is the content
How to solve this ?
I'd do something like:
const counter = document.querySelector("#counter");
const textEl = document.querySelector("#foo");
textEl.addEventListener("input", () => {
counter.textContent = textEl.value.length;
});
<input type="text" id="foo" />
<span id="counter">0</span>
So I am a newbie and I am just practice
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue() {
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
addBtn.addEventListener('click', addValue);
<form action="">
<input type="text" id="input-text">
<button id="add">add value</button>
</form>
<p>Data: <span id="output"></span></p>
my first lesson of JS is function and with .textcontent. So I wrote a code that will output the value/ number I entered on the input field after I click the add value button but somehow my code doesn't work.
DISCLAIMER> I HAVENT LEARN LOOPS< IF STATEMENTS OR WHATSOEVER I just want to practice my lesson.
You just need to e.preventDefault() to prevent the form from submission and reload the page. It is the default behavior, so you need to prevent this behavior.
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue(e) {
e.preventDefault();
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
addBtn.addEventListener("click", addValue);
<form action="">
<input type="text" id="input-text">
<button id="add">add value</button>
</form>
<p>Data: <span id="output"></span></p>
Like some other people already mentioned, it's the <form> that's being submitted.
I'd recommend removing the <form></form> since there no use for it now:
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue() {
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
addBtn.addEventListener('click', addValue);
<input type="text" id="input-text">
<button id="add">add value</button>
<p>Data: <span id="output"></span></p>
Small side-note:
function addValue() {
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
Can be simplified to just:
function addValue() {
displayOutput(getUserInput());
);
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue() {
displayOutput(getUserInput());
}
addBtn.addEventListener('click', addValue);
<input type="text" id="input-text">
<button id="add">add value</button>
<p>Data: <span id="output"></span></p>
I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}