Output/Displaying the value in the HTML - javascript

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>

Related

disable button if the input field is empty and enable if there is text

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>

How to calculate avg dynamically and flexibly in html+js?

I want to receive data from the user.
I want to make it possible for the user to add or delete buttons.
And I want to average the results entered by the user.
How can I know how many buttons a user has created?
How do I know the average of the values entered by the user?
<form>
<div id="box">
<input type="text" class="sj"> <input type="button" value="add" onclick="add_textbox()">
</div>
</form>
<script>
const add_textbox = () => {
const box = document.getElementById("box");
const newP = document.createElement('p');
newP.innerHTML = "<input type='text'> <input type='button' value='delete' onclick='remove(this)'>";
box.appendChild(newP);
}
const remove = (obj) => {
document.getElementById('box').removeChild(obj.parentNode);
}
</script>
const add_textbox = () => {
const box = document.getElementById("box");
const newP = document.createElement('p');
newP.innerHTML = "<input type='number' class='sj'> <input type='button' value='delete' onclick='remove(this)'>";
box.appendChild(newP);
}
const remove = (obj) => {
document.getElementById('box').removeChild(obj.parentNode);
}
const resultButton = document.querySelector('[data-button-result]');
const getResult = () => {
const result = [...document.querySelectorAll('.sj')].reduce((acc, input) => {
if (input.valueAsNumber)
return acc += input.valueAsNumber
else return acc
}, 0)
const resultElement = document.querySelector('[data-result]');
resultElement.innerText = result
}
resultButton.addEventListener('click', getResult)
<form>
<div id="box">
<input type="number" class="sj"> <input type="button" value="add" onclick="add_textbox()">
</div>
</form>
<button data-button-result>Get results</button>
<div data-result></div>

Typing in the firt input without focusing

I have an Virtual keyboard with Javascript the keyboard is typing in two inputs after reached maxlength it is focusing to second input. my problem is when i want to type in first input i should clicked to first input to focus it than typing with keyboard numbers
My question is How i can typing using this keyboard without clicking inside input, the first input should start typing immediately after i clicked on the buttons numbers
const maxLength = 7;
const firstInput = document.querySelector("#pin");
const secondInput = document.querySelector("#key");
const changedEvent = new Event("change")
let activeInput;
firstInput.addEventListener("focus", (event) => {
activeInput = event.target;
});
firstInput.addEventListener("change", (event) => {
console.log("i'm changing!");
if (firstInput.value.length >= maxLength) {
activeInput = secondInput;
secondInput.focus();
}
});
secondInput.addEventListener("focus", (event) => {
activeInput = event.target;
});
function resetNumber() {
if (!activeInput) {
console.log("pin");
return;
}
activeInput.value = "";
}
function setNumber(number) {
if (!activeInput) {
console.log("pin");
return;
}
activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
// manually tell the input that it has changed, so that the event listener defined above gets called. this usually only will happen with actual keyboard input
activeInput.dispatchEvent(changedEvent);
}
<button onclick="resetNumber()">Reset</button>
<button onclick="setNumber(0)">0</button>
<button onclick="setNumber(1)">1</button>
<button onclick="setNumber(2)">2</button>
<button onclick="setNumber(3)">3</button>
<button onclick="setNumber(4)">4</button>
<button onclick="setNumber(5)">5</button>
<button onclick="setNumber(6)">6</button>
<button onclick="setNumber(7)">7</button>
<button onclick="setNumber(8)">8</button>
<button onclick="setNumber(9)">9</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />
<button id="reset" onclick="resetNumber()">Reset</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />
<script>
const maxLength = 7;
const firstInput = document.querySelector('#pin');
const secondInput = document.querySelector('#key');
const resetBtn = document.querySelector('#reset');
for (let i = 9; i >= 0; i--) {
const numBtn = document.createElement('button');
numBtn.className = 'number';
numBtn.innerText = i;
resetBtn.parentElement.insertBefore(numBtn, resetBtn.nextSibling);
}
const numberBtns = document.querySelectorAll('.number');
const resetNumber = () => {
firstInput.setAttribute('value', '');
secondInput.setAttribute('value', '');
};
const setVal = (e) => {
const num = parseInt(e.target.innerText, 10);
if (firstInput.value.length <= maxLength) return firstInput.setAttribute('value', firstInput.value + num);
secondInput.setAttribute('value', secondInput.value + num);
};
numberBtns.forEach((btn) => btn.addEventListener('click', setVal));
</script>

Element text not changing when passing selected textContent and new value to an update function

I'm creating a CRUD page where the user can add, delete and edit text, but I have an issue in updating the text after I select it for edit.
In editText function when I click the edit button the text that was added will pop up inside the input field. When I click on the update button (triggering the updateText function), I can see the text in console log but the corresponding html is not updated.
HTML
<div class="main">
<form>
<input type="text" placeholder="search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">update</button>
</div>
</div>
Javascript
const inputsearch = document.querySelector('form input');
const addInputBtn = document.querySelector('#add');
const update = document.querySelector('#update');
addInputBtn.addEventListener('click', addtext);
function addtext(){
let li = document.createElement('li');
let inputadd = document.querySelector('.add-text');
let addedtext = inputadd.value;
let h1Tag = '<h1 id="text">'+addedtext+'</h1>';
let tags = h1Tag + '<button id="delete">Delete</button><button id="edit">Edit</button>';
if(addedtext == ''){
alert('please add some text');
return;
}else{
li.innerHTML = tags;
document.querySelector('ul').appendChild(li);
}
li.querySelectorAll('#delete')[0].addEventListener('click', deleteText);
li.querySelectorAll('#edit')[0].addEventListener('click', editText);
getlist(li, h1Tag);
inputadd.value = '';
}
function deleteText(e) {
e.target.parentNode.remove();
document.querySelector('.add-text').value = '';
}
function editText(e) {
let currentText = e.target.parentNode.firstChild.textContent;
let currentValue = document.querySelector('.add-text');
currentValue.value = currentText;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText = currentValue.value
console.log(currentText = currentValue.value);
}
}
function getlist(li, h1Tag) {
inputsearch.addEventListener('keyup', serchText);
function serchText(e) {
let typetext = e.target.value.toLowerCase();
if(h1Tag.toLowerCase().indexOf(typetext) != -1){
li.style.display = 'block';
}else{
li.style.display = 'none';
}
}
}
To solve the issue without changing your overall approach, your edit button click needs to get the corresponding element (not just its textContent) and pass it to your getupdate() function to be updated when your update button is clicked. Relatively minor changes to your current functions:
function editText(e) {
const currentText = e.target.parentNode.firstChild;
const currentValue = document.querySelector('.add-text');
currentValue.value = currentText.textContent;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText.textContent = currentValue.value;
}
}
There are some other issues with your code, particularly the creation of multiple elements with the same id (which is malformed and will likely become problematic as you add additional features). Following is a snippet that addresses that issue as well as simplifying some of your functions and fixing the search.
const search = document.querySelector('form input');
const input = document.querySelector('.add-text');
const container = document.querySelector('ul');
let items = null;
let currentItem = null;
const searchItems = (event) => {
if (items) {
const s = event.currentTarget.value.toLowerCase();
for (const item of items) {
if (item.firstChild.textContent.toLowerCase().indexOf(s) !== -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
}
};
const deleteItem = (event) => {
currentItem = null;
event.currentTarget.parentNode.remove();
};
const editItem = (event) => {
currentItem = event.currentTarget.parentNode.firstChild;
input.value = currentItem.textContent;
};
const updateItem = () => {
if (currentItem) {
currentItem.textContent = input.value;
}
};
const addItem = () => {
let val = input.value
if (val) {
const li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
li.innerHTML = inner;
container.appendChild(li);
val = '';
currentItem = li.firstChild;
items = document.querySelectorAll('li');
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
};
search.addEventListener('keyup', searchItems);
document.querySelector('#add').addEventListener('click', addItem);
document.querySelector('#update').addEventListener('click', updateItem);
<div class="main">
<form>
<input type="text" placeholder="Search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">Update</button>
</div>
</div>

Adding an event listener using an object’s property

What I want to have is a working button and input form for my code which is a block in an object literal. My form shows fine when I run the code, but doesn’t output a value. Why not?
<input class="number" type="number" placeholder="Enter some number...">
<button>enter</button>
<p id="output"></p>
<script>
var input = document.querySelector("#number");
var output = document.querySelector("#output");
var button = document.querySelector("button");
add.button.addEventListener("click", add.number, false);
button.style.cursor = "pointer";
var add = {
number: function () {
amount = parseInt(input.value);
if (amount == 5) {
output.innerHTML = alert("true");
} else {
output.innerHTML = alert("false");
}
}
};
</script>
You have to define the function before you can pass it to addEventListener otherwise you are just passing undefined.
<input class="number" type="number" placeholder="Enter some number..." id="number">
<button id="button">enter</button>
<p id="output"></p>
var input = document.getElementById("number");
var output = document.getElementById("output");
var add = {
number: function () {
amount = parseInt(input.value, 10);
if (amount === "5") {
alert("true");
output.innerHTML = true;
} else {
alert("false");
output.innerHTML = false;
}
}
};
var button = document.getElementById("button");
button.addEventListener("click", add.number, false);
button.style.cursor = "pointer";
See: http://jsfiddle.net/zw7e7q72/

Categories