document.createElement flashes up with what I want. Then it disappears - javascript

I'm having a small issue with my code. I want the user's input to appear on the screen, like a chatbot. However, it is not doing this. What it's doing instead is flashing up with what I want. Then it is disappearing. Just the message, not the entire thing, but that sometimes happens as well. What has happened and how can I fix it?
function executeNewMessage() {
var messagecontainer = document.getElementById("message");
var message = messagecontainer.value;
var newmessagediv = document.createElement("DIV");
newmessagediv.innerHTML = message;
document.getElementById("bodymessages").appendChild(newmessagediv);
}
<div id="site">
<div id="head">
Chatbot
</div>
<div id="body">
<div id="bodymessages"></div>
<span id="bottom"></span>
</div>
<div id="foot">
<form>
<label for="message">Type your message here</label>
<input id="message" type="text" />
<a href="#bottom">
<button id="submit" onclick="executeNewMessage()">→</button>
</a>
</form>
</div>
</div>

The reason that this is happening is because you are using HTML form. The default behavior for form is that they try to submit to the server. That's why you only see the change for a short duration and the page reloads again. Hence, you need to use preventDefault() method.
So, your function should look like this:
function executeNewMessage(e) { //Here e is the event object
var messagecontainer = document.getElementById("message");
var message = messagecontainer.value;
var newmessagediv = document.createElement("DIV");
newmessagediv.innerHTML = message;
document.getElementById("bodymessages").appendChild(newmessagediv);
e.preventDefault();
}
So, what the preventDefault() does is that it prevents the default action of an event.
https://www.w3schools.com/jsref/event_preventdefault.asp

Related

Update DOM of popup.html after clicking button

I am making a chrome extension. I want to update a h3 element in popup.html with some text after click a submit button with id submit.
<!-- popup.html -->
<div class="row">
<h3 id="status"></h3>
</div>
// popup.js
function saveClass() {
var status = document.getElementById('status')
status.innerText = 'success';
}
document.getElementById("submit").addEventListener("click", saveClass);
The function populates the element with the text, and I see the text, but it disappears immediately, within some microseconds. Where I am going wrong ?
For me its' working fine. You can refer the following code snippet
<html>
<body>
<!-- popup.html -->
<div class="row">
<h3 id="status"></h3>
</div>
<button id="submit">Submit</button>
<!-- popup.js -->
<script>
function saveClass() {
var status = document.getElementById('status')
status.innerText = 'success';
}
document.getElementById("submit").addEventListener("click", saveClass);
</script>
</body>
</html>
The form refreshes the page by default upon submission, due to which the populated text vanishes. Just add an event listener to disable it, which keeps the DOM intact.
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);

I'm can't append a div created in js file inside a <section>, whitch is inside a grid, in my index.html

I'm trying to create a to-do list and use html/css/js to do it.
I've created a button, and a text input on HTML.
Created a function in JS.
Got both by their id.
Created a div in JS.
inserted the the text that I got from text input inside the var that holds the div.
and tryied to append this div into the section using appenddChild.
When I click the button I can see the div apearing for less than a second inside the section, and it desapears.
function addTask() {
let userInput = document.getElementById("add-field").value;
let task = document.createElement("div");
task.innerText = userInput;
taskList = document.getElementById("list");
task.className = "task-bar";
document.querySelector('#list').appendChild(task);
}
<main id="container">
<section id="entrance">
<h1>TASKS</h1>
</section>
<section id="adding">
<form id="adding-items">
<input id="add-field" type="text">
<button id="send-btn" value="ADD" onclick="addTask()">ADD</button>
</form>
</section>
<section id="list">
</section>
</main>
You are using a form element.
So if you click the button, it would refresh the page.
To prevent it, you can use onSubmit="return false;".
<form onSubmit="return false;" id="adding-items">
Its because you're using a <form> element. Forms have a default behavior that when it contains a button, that button will be used to submit the form, unless the type of the button is other than submit.
You'll need to stop the default behavior of the form from happening. You do this by preventing the default behavior of the submit event.
You do this with Event.preventDefault() inside the event handler.
const form = document.querySelector('#adding-items');
const taskList = document.querySelector('#list');
const userInput = document.getElementById("add-field")
function addTask() {
let userInputValue = userInput.value;
let task = document.createElement("div");
task.innerText = userInputValue;
task.className = "task-bar";
taskList.appendChild(task);
}
form.addEventListener('submit', event => {
event.preventDefault(); // Stop the default behavior.
addTask();
});
<main id="container">
<section id="entrance">
<h1>TASKS</h1>
</section>
<section id="adding">
<form id="adding-items">
<input id="add-field" type="text">
<button id="send-btn" value="ADD">ADD</button>
</form>
</section>
<section id="list">
</section>
</main>

How to add active element id to url

I was trying to add the id value of active element into a url. Then using a button to redirect to the url.
HTML
<div class="icon" tabindex="0" id="company">
<img src="company.png">
</div>
<button type="submit" onclick="myFunction()">jump</button>
Javascript
function myFunction(){
var x = document.activeElement.id;
location.href = "apps-online.html?page=" + x;
}
My expectations was: when I click the button, it will redirect to page
"apps-online.html?page=company"
However, the url of the new page is
"apps-online.html?page="
I was wondering why the value of x hasn't been added to the url.
Hi, everyone. For now I have understood why this problem happened. Because every time when I click the button, the button became the last active element.
So is there any way to achieve my goal?
Do check the value of x whether it is empty or not if it is empty the value of x will be passed as empty so there is no value in the url .try debugging the code or use console.log
function myFunction(){
var x = document.activeElement.id;
console.log(x);
location.href = "apps-online.html?page=" + x;
}
this gives the value of x in the console check this.
Your button does not have an id.
Give id="company" to button element.
<div class="icon" tabindex="0">
<img src="company.png">
</div>
<button id="company" type="submit" onclick="myFunction()">jump</button>
When you click on the button, the active element is button itself. I am assuming you have several divs and you need to pass the id of the highlighted element. You need to send the id to the function in some way.
Take a look below. This can be one of the many possible solutions.
HTML
<div class="icon" tabindex="0" id="company">
<img src="company.png">
</div>
<div class="icon" tabindex="1" id="something">
<img src="something.png">
</div>
<button type="submit" onclick="myFunction()">jump</button>
JS
let tabID = null;
let icons = document.getElementsByClassName('icon');
for (icon of icons)
{
icon.onclick = function()
{
tabID = document.activeElement.id;
}
}
function myFunction()
{
window.open("apps-online.html?page=" + tabID);
}

Hw do I clck the add btn and it display the info in the input field and display it n a <p> created with JS. (no inline JS)

Im trying to take the user input and add it to the page with the click of the button and add it to the page in a new paragraph element created thru javascript, I didn't want to use any inline javascript and I wanted to use as little html as possible and do it mainly thru javascript.
<body>
<div class="input">
<form>
<input id="input" type="text" placeholder="Enter task to do..." />
<button id="add_btn">Add</button>
</form>
</div>
<div class="task_list">
<ul id="todo">
<li></li>
</ul>
</div>
<script>
//take user input and add it to the page as a task to do
let div = document.querySelector('.task_list');
let input = document.querySelector('#input')
let pElement = document.createElement('p');
let add = document.getElementById('add_btn');
div.appendChild(pElement);
add.addEventListener(onclick, function (){
input.value;
pElement.innerHTML = input;
console.log(add);
});
</script>
You've got some problems with your code:
You're wrongly binding the event listener. You should use 'click' instead of onclick (which isn't defined anyway).
You didn't define any button type, so the button is treated as submit button, by default. Add type="button" attribute so that the page doesn't refresh on clicking on it.
In the event listener, you should create a fresh p element always, and assign its textContent with input.value (unless you're dealing with HTML content, in which case, innerHTML would be appropriate).
The following snippet makes the code work. Not sure what end result should be like (e.g. you may want to append the list items in ul), but this can get you on track.
//take user input and add it to the page as a task to do
let div = document.querySelector('.task_list');
let input = document.querySelector('#input')
let add = document.getElementById('add_btn');
add.addEventListener('click', function() {
let pElement = document.createElement('p');
pElement.textContent = input.value;
div.appendChild(pElement);
});
<div class="input">
<form>
<input id="input" type="text" placeholder="Enter task to do...">
<button type="button" id="add_btn">Add</button>
</form>
</div>
<div class="task_list">
<ul id="todo">
<li></li>
</ul>
</div>

JavaScript event button onclick works only one time

I want to fire an onclick event from a button. The event is declared in a separate JavaScript file.
The code must reproduce a chat. If I send first text it works fine, but if I try to send something again (second text) it does not fire.
The html file contains:
var chatOutputDiv = document.getElementById("chatOutput");
chatSubmit.onclick = function () {
// Create a Json object with "displayname" being the display name and "messageText" the message.
// "displayname" is taken from URL, message from element chatInput.
//var chatMessage = { "displayname": getURLParameter("displayName"), "messageText": chatInput.value };
// We send data on the "chat", channel which is currently hard-coded
// in later versions we allow custom naming of channels.
//conference.sendData("chat", chatMessage);
// Send text in current chat
chatOutputDiv.innerHTML += "<br> user : message";
// Clear chat input
chatInput.value = "";
};
<div class="row">
<div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center">
<div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;">
<input type="text" id="chatInput"/>
<input id="chatSubmit" type="button" value="Send"/>
</div>
</div>
</div>
If you try this code, it works one time, but after that it doesn't work anymore. It seems that it doesn't fire the event.
It's because you are recreating the html inside .chatOutput when you click the button, so the HTML (which includes the button) is rewritten and the event is lost.
There are various ways around this. One would be to make the function a named function that you call, and adding chatSubmit = document.getElementById("chatSubmit"); chatSubmit.onclick = myFunctionName; to the end of your function.
However, I think a nicer way of doing it is to just use an extra div to store the response, like so:
<div class="row">
<div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center">
<div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;">
<input type="text" id="chatInput"/>
<input id="chatSubmit" type="button" value="Send"/>
<div id="chatResponse"></div>
</div>
</div>
</div>
var chatOutputDiv = document.getElementById("chatOutput")
var chatSubmit = document.getElementById("chatSubmit")
var chatResponse = document.getElementById("chatResponse");
var chatInput = document.getElementById("chatInput");
function foobar() {
chatResponse.innerHTML += "<br> user : " + chatInput.value;
chatInput.value = "";
}
chatSubmit.onclick = foobar;
Fiddle: https://jsfiddle.net/r0gm30mr/

Categories