javaScript and HTML-Textarea Text not erasing [duplicate] - javascript

This question already has answers here:
How to clear text area with a button in html using javascript?
(5 answers)
Closed 7 days ago.
Html file with JavaScript functions
<html>
<head>
<title>Voice to Text</title>
<script>
function erasText(){
document.getElementById("name").innerHTML = "";
}
</script>
</head>
<body>
<form>
<label>Enter Text: </label>
<textarea placeholder="Enter text here for detection." id="name" name="name" class="result" >
</textarea>
</form>
<div class="options" style="display:none">
<div class="anguage" >
<p>Language</p>
<select name="input-language" id="language"></select>
</div>
</div>
<button class="btn record" id='myid'>
<p><b> Start Listening</b></p>
</button>
<div style="margin-top:-50px;" class="buttons">
<button class="btn clear" id='clr' style="margin-left:150px" onClick="erasText()">
<b>Clear</b>
</button>
</div>
<script>
myid.addEventListener('click',function(){
var speech = true;
window.SpeechRecognition = window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.interimResults = true;
recognition.addEventListener('result', e => {
const transcript = Array.from(e.results)
.map(result => result[0])
.map(result => result.transcript)
.join('')
document.getElementById("name").innerHTML = transcript;
console.log(transcript);
});
if (speech == true) {
recognition.start();
}
})
clr.addEventListener("click", () => {
document.getElementById("name").innerHTML = "";
})
</script>
</body>
</html>
When i click on clear button than the text on textarea is not erasing and when i press 'Start Listening' than this button works. i think 'erasText' function is not calling and only the following function is calling in the above code:
clr.addEventListener("click", () => {
document.getElementById("name").innerHTML = "";
})
I called erasText function on button click but i do not know why the erasText button is not calling. Is there a way to call this function?

The field you are actually looking for is value instead of innerText.
clr.addEventListener("click", () => {
document.getElementById("name").value = "";
});

Related

How do I target my class task for the event Listener to Handle?

My buttons for edit delete and save are not working and that is because the event listener is passing an element that has nothing in it, but I want to target the class <div class="task" date-id = "${id}"> for the event listener.
This is what is wrong:
elements.list.addEventListener('click',event => the elements.list is wrong as it is not holding anything. But I would like to target the <div class="task" date-id = "${id}"> for the eventEventListener.
Please see the full code so you have a better idea:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-do App</title>
<script src="js/main.js" defer></script>
<script src="js/dateTime.js" defer></script>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<div class="header">
<h1>To-Do List</h1>
<div class="time">
<div class="dateTime"></div>
<div class="day"></div>
</div>
</div>
<form id="new-task-form">
<div class="add-task">
<input type="text" name="new-task-input" id="new-task-input" placeholder="What do you have planned?" />
<input type="date" id="calendar">
</div>
<input type="submit" id="new-task-submit" value="Add task" />
</form>
</header>
<main>
<section class="task-list">
<h2>Tasks</h2>
<div id="tasks">
<!--<button class = "sort">Sort</button>
<div class="task">
<div class="content">
<input
type="text"
class="text"
value="A new task"
readonly>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div>-->
</div>
</section>
</main>
</body>
</html>
JS
/************************************
* creates objct of elements needed *
************************************/
const elements = {
form: document.querySelector("#new-task-form"),
input: document.querySelector("#new-task-input"),
list: document.querySelector("#tasks"),
cal: document.querySelector("#calendar")
}
/****************************
* Generates an ID for task *
****************************/
const createId = () => `${Math.floor(Math.random() * 10000)}-${new Date().getTime()}`
/**********************************************
* function that creates the HTML elements *
**********************************************/
const createTask = () => {
const id = createId()
const task = elements.input.value;
const date = elements.cal.value;
if(!task && !date) return alert("Please fill in task and select date");
if(!task) return alert("Please fill in task");
if(!date) return alert("Please select date");
const tasks = document.createElement("div");
tasks.innerHTML = `
<button class = "sort">Sort</button>
<div class="task" data-id = "${id}">
<div class="content">
<input type ="checkbox" class="tick">
<input type ="text" class = "text" id = "text" readonly>${task}
<label class = "due-date" for ="text">${date}</label>
<input type ="date" class = "date" id = "date">
</div>
<div class = "actions">
<button class="edit" data-id="${id}">Edit</button>
<button class="delete" data-id="${id}">Delete</button>
</div>
</div>
`
elements.list.appendChild(tasks)
return tasks
}
/**************************************************************
* Event that listens for the edit,save and delete buttons *
**************************************************************/
elements.list.addEventListener('click',event => {
const {target} = event
const {id} = target.dataset
const task = id ? document.querySelector('[data-id="${id}"]'):null;
const type = {
edit: event.target.classList.contains('edit'),
delete: event.target.classList.contains('delete')
}
const isFromSaveLabel = target.innerText.toLowerCase() === 'save'
if(task && type.edit && isFromSaveLabel){
const text = task.querySelector('.text')
target.innerText = 'Edit'
text.addAttribute('readonly')
return
};
if(task && type.edit){
const text = task.querySelector('.text')
target.innerText = 'save'
text.removeAttribute('readonly')
text.focus()
return
};
if(task && type.delete){
return
}
});
/*******************************************************************
* Submits the HTML elements to have the lists submitted and created*
*******************************************************************/
const submitHandler = (event) =>{
event.preventDefault();
createTask();
}
elements.form.addEventListener("submit", submitHandler);
I have been asking a lot about this on the platform, but I realized I have been asking the wrong question. As mentioned above I need the event listener to target the <div class="task" date-id = "${id}"> that has been created with const tasks = document.createElement("div");
The reason is when you click on add task it creates a new <div class="task" date-id = "${id}"> for example ```````
with the contents class and everything in there.
PS: Apologies for the long-winded code, it's necessary so that you get the full picture of the issue and question
Could it be beacause you used "date-id" on tasks.innerHTML, but use "data-id" on
const task = id ? document.querySelector('[data-id="${id}"]'):null;
Okay, I found some issues in the event listener:
the queryselector is not a template literal, so ${id} doesn't work.
"addAttribute" is wrong. "setAttribute" is the correct one.
Edit and save works after these are fixed.
/**************************************************************
* Event that listens for the edit,save and delete buttons *
**************************************************************/
elements.list.addEventListener('click',event => {
const {target} = event
const {id} = target.dataset
const task = id ? document.querySelector(`[data-id="${id}"]`):null;
const type = {
edit: event.target.classList.contains('edit'),
delete: event.target.classList.contains('delete')
}
const isFromSaveLabel = target.innerText.toLowerCase() === 'save'
if(task && type.edit && isFromSaveLabel){
const text = task.querySelector('.text')
target.innerText = 'Edit'
text.setAttribute('readonly', 'true')
return
};
if(task && type.edit){
const text = task.querySelector('.text')
target.innerText = 'save'
text.removeAttribute('readonly')
text.focus()
return
};
if(task && type.delete){
return
}
});
And for the error, it is probably a bug in the extension.

Why isn't my code adding a number with the input field (HTML/Javascript - Beginner)?

for practice as a beginner I am trying to take a number from a text field, have the user press a button that adds 2 to that number, and then displays it through HTML. However, for some reason I keep getting NaN when applying the code below.
//Setup
var num1 = document.querySelector(".input-box").value;
var btn = document.querySelector(".btn");
//Add
var sum = parseInt(num1) + 2;
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to move the num1 and sum the inside the event listener
//Setup
var btn = document.querySelector(".btn");
//Add
btn.addEventListener('click', (e) => {
e.preventDefault();
// get the number
var num1 = document.querySelector(".input-box").value;
// add 2
var sum = parseInt(num1) + 2;
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to calculate the sum inside the click function. Right now it is calculating before the butten is clicked, when the page loads, which means the input is empty.
as mentioned above you need to resolve after the button is clicked. you could change your variables to function variables.
//Setup
var num1 = function() {return document.querySelector(".input-box").value};
var btn = document.querySelector(".btn");
//Add
var sum = function() {return parseInt(num1()) + 2};
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum();
})
make the input type = number for better validation
make the button type = submit cause this is form and you need to submit
add submit event to the form cause you can't prevent default without submit event
select input inside the event and convert its value to number by adding + before it
// select from
var form = document.getElementById("form");
form.addEventListener('submit', (e) => {
e.preventDefault();
// select input and convert its value to number
var num1 = +document.querySelector(".input-box").value;
document.querySelector("#output").innerHTML = num1 + 2;
// wipe out form after submit
form.reset();
});
<div class="sign">
<h1>Calculate</h1>
<form id="form">
<input type="number" class="input-box" placeholder="Enter Number">
<input class="btn" type="submit" value="Add 2">
</form>
<h1 id="output"></h1>
</div>

My Submit Button does not save text from textarea

I have got problem with my button. Button is not save my text from textarea, and i do not know why.
I everything is conneted and a text shoud go properly to save.
I try look for some typo.
Console in Chrome does not show any mistakes.
I try check for some typo, but i do not find any.
terminal in VisualCode do not show any mistakes
let todoList = null;
let todoForm = null;
let todoSearch = null;
document.addEventListener('DOMContentLoaded', function() {
todoList = document.querySelector('#todoList');
todoForm = document.querySelector('#todoForm');
todoSearch = document.querySelector('#todoSearch');
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
const textarea = this.querySelector('textarea');
if (textarea.value !== ' ') {
addTask(textarea.value);
textarea.value = '';
}
});
});
function addTask(text) {
const todo = document.createElement('div');
todo.classList.add("task-element");
const todoBar = document.createElement('div');
todoBar.classList.add('task-bar');
const todoDate = document.createElement('div');
todoDate.classList.add('task-bar');
const date = new Date();
const dateText = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getHours() + ':' + date.getMinutes();
todoDate.inner = dateText;
const todoDelete = document.createElement('button');
todoDelete.classList.add('task-delete')
todoDelete.classList.add('button')
todoDelete.innerHTML = '<i class="fas fa-times-circle"></i>';
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
const todoText = document.createElement('div');
todoText.classList.add('task-text');
todoText.innerText = text;
todo.appendChild(todoBar);
todo.appendChild(todoText);
todoList.append(todp);
}
document.addEventListener('DOMContentLoaded', function() {
todoList.addEventListener('click', function(e) {
console.log(e.target)
});
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="todo-cnt">
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</form>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
<section class="list-cnt">
<header class="header-list">
<h2 class="text-list">
Lista Zadań
</h2>
<form class="list-form">
<input type="search" id="todoSearch" class="search-form">
</form>
</header>
</section>
<div class="task-element">
<div class="task-bar">
<h3 class="task-date">60-80-2019 11:87</h3>
<button class="task-delete" title="Usuń zadanie">
<i class="task-time"></i>
</div>
<div class="task-text" id="todoList">
<p>Przykładowy tekst zadan dla tasku</p>
</div>
</div>
<link rel="stylesheet"type="text/css"href="projekt2.css">
<script src="projekt2.js" async defer></script>
</body>
</html>
Button outside the form
other button not closed
form closed wrongly half inside a div anyway
Spelling of todp instead of todo
I added text to the <i> because I did not load the fontawesome
let todoList = null;
let todoForm = null;
let todoSearch = null;
document.addEventListener('DOMContentLoaded', function() {
todoList = document.querySelector('#todoList');
todoForm = document.querySelector('#todoForm');
todoSearch = document.querySelector('#todoSearch');
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
const textarea = this.querySelector('textarea');
if (textarea.value !== ' ') {
addTask(textarea.value);
textarea.value = '';
}
});
});
function addTask(text) {
const todo = document.createElement('div');
todo.classList.add("task-element");
const todoBar = document.createElement('div');
todoBar.classList.add('task-bar');
const todoDate = document.createElement('div');
todoDate.classList.add('task-bar');
const date = new Date();
const dateText = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getHours() + ':' + date.getMinutes();
todoDate.inner = dateText;
const todoDelete = document.createElement('button');
todoDelete.classList.add('task-delete')
todoDelete.classList.add('button')
todoDelete.innerHTML = '<i class="fas fa-times-circle">°</i>';
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
const todoText = document.createElement('div');
todoText.classList.add('task-text');
todoText.innerText = text;
todo.appendChild(todoBar);
todo.appendChild(todoText);
todoList.append(todo);
}
document.addEventListener('DOMContentLoaded', function() {
todoList.addEventListener('click', function(e) {
console.log(e.target)
});
});
<form class="formquest" id="todoForm">
<div class="todo-cnt">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
<section class="list-cnt">
<header class="header-list">
<h2 class="text-list">
Lista Zadań
</h2>
<form class="list-form">
<input type="search" id="todoSearch" class="search-form">
</form>
</header>
</section>
<div class="task-element">
<div class="task-bar">
<h3 class="task-date">60-80-2019 11:87</h3>
<button class="task-delete" title="Usuń zadanie"><i class="task-time">Task time</i></button>
<div class="task-text" id="todoList">
<p>Przykładowy tekst zadan dla tasku</p>
</div>
</div>
</div>
</div>
</form>
A submit button is supposed to be inside the form tag in order to work.
<div class="todo-cnt">
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
</div>
Remember whenever you are dealing with a submit button you must make sure that the submit button is within the form which you are submitting.
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="list-cnt">

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

How to get user text input and render it to an element on the page?

So I'm testing out this thing where I can write something in a text input, and then have that render to the page. I have a text input with the id user-text and a submit input with the id apply-button, and a target <p> tag where the entry should go. Essentially, you type in the entry into the text input and click the button, and it should render to the target. But that's not working for me. Here's my code.
let userInput = document.querySelector('#user-text');
const applyButton = document.querySelector('#apply-button');
let userTarget = document.querySelector('#user-target');
applyButton.addEventListener('click', () => {
userTarget.textContent = userInput.nodeValue;
});
<div>
<div>
<p><input type='text' id='user-text' placeholder="Type your day here."name='blogtext'><input type='submit' id='apply-button'value='Click to Apply'>
</div>
<div id='target'>
<p id='user-target'></p>
</div>
</div>
Let me know if you have any questions.
you can use userInput.value to get value from input field. Also your first <p> tag is not closed.
<body>
<div>
<div>
<p><input type='text' id='user-text' placeholder="Type your day here."name='blogtext'><input type='submit' id='apply-button'value='Click to Apply'>
</div>
<div id='target'>
<p id='user-target'></p>
</div>
</div>
<script type='text/javascript'>
let userInput = document.querySelector('#user-text');
const applyButton = document.querySelector('#apply-button');
let userTarget = document.querySelector('#user-target');
applyButton.addEventListener('click', () => {
userTarget.textContent = userInput.value;
});
</script>
</body>
when you performing click on function, "nodeValue" is coming null that why you trying to set value to html its not coming on UI.
<body>
<div>
<div>
<p><input type='text' id='user-text' placeholder="Type your day here."name='blogtext'><input type='submit' id='apply-button'value='Click to Apply'>
</div>
<div id='target'>
<p id='user-target'></p>
</div>
</div>
<script type='text/javascript'>
console.log('called');
let userInput = document.querySelector('#user-text');
const applyButton = document.querySelector('#apply-button');
let userTarget = document.querySelector('#user-target');
applyButton.addEventListener('click', () => {
userTarget.textContent = userInput.value;
});
</script>
</body>
let userInput = document.querySelector('#user-text');
const applyButton = document.querySelector('#apply-button');
let userTarget = document.querySelector('#user-target');
applyButton.addEventListener('click', () => {
userTarget.innerHTML = userInput.value;
});
<div>
<div>
<p><input type='text' id='user-text' placeholder="Type your day here."name='blogtext'><input type='submit' id='apply-button'value='Click to Apply'>
</div>
<div id='target'>
<p id='user-target'></p>
</div>
</div>
get textarea value and put it in your element using innerHTML.

Categories