Add and remove item in li on div without refresh page - javascript

I'm new in javascript and i need some help.
I have div tag inside a form tag who has his own submit button. Inside this div tag i have a combox with some names, and two button, one to add an item in a list (li) e other to remove it.
My problem is when i choose a name and press the add button, i call javascript function that do it, but also it refresh my html page. I don't want that.
How can i do it?
Without the form tag it works just fine.
Best regards
Here is the code:
<#s.form action="confuserpermission" theme="simple">
<#s.hidden name="saveuserpermission" value="true"/>
<div style="float: left; margin-top: 0.8em;">
<h5 style="color: #1E1E1E;">Login Utilizador:</h5>
<div class="input">
<#s.textfield name="confUserBean.name" label="Nome" cssClass="input"/>
</div>
<div style="display: inline">
<h5 style="color: #1E1E1E; display: inline">Escolhe e Adiciona uma Entidade</h5>
<select id="entityList">
<option value="default">-----Select-----</option>
<#s.iterator value="listaEntidades">
<option value="<#s.property />"><#s.property /></option>
</#s.iterator>
</select>
<button class="submit" onclick="adicionaEntidade()">Adicionar</button> <button class="submit" onclick="removaEntidade()">Remover</button>
<ul id="myList"></ul>
</div>
<script>
function isInArray(value, array) {
return array.indexOf(value) > -1 ? true : false;
}
function checkIfEntityIsAlreadyInList(entidade) {
var texts = [], lis = document.getElementById("myList").childNodes;
for (var i = 0, im = lis.length; im > i; i++) {
texts.push(lis[i].firstChild.nodeValue);
}
return isInArray(entidade, texts);
}
function adicionaEntidade()
{
var e = document.getElementById("entityList");
var entidade = e.options[e.selectedIndex].value;
if (entidade !== "default" && !checkIfEntityIsAlreadyInList(entidade)) {
var node = document.createElement("LI");
var textnode = document.createTextNode(entidade);
var fileTypeNode = document.createElement("UL");
var optionArray = ["PSX", "PS2", "XLS"];
for (var option in optionArray) {
if (optionArray.hasOwnProperty(option)) {
var pair = optionArray[option];
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = pair;
checkbox.value = pair;
fileTypeNode.appendChild(checkbox);
var label = document.createElement('label');
label.htmlFor = pair;
label.appendChild(document.createTextNode(pair));
fileTypeNode.appendChild(label);
//fileTypeNode.appendChild(document.createElement("br"));
}
}
node.appendChild(textnode);
node.appendChild(fileTypeNode);
document.getElementById("myList").appendChild(node);
}
}
function removaEntidade()
{
var e = document.getElementById("entityList");
var entidade = e.options[e.selectedIndex].value;
if (entidade !== "default" && checkIfEntityIsAlreadyInList(entidade)) {
var lis = document.getElementById("myList").childNodes;
var indexOfChildToRemove = -1;
for (var i = 0, im = lis.length; im > i; i++) {
if(lis[i].firstChild.nodeValue === entidade){
indexOfChildToRemove = i;
break;
}
}
if(indexOfChildToRemove>-1){
document.getElementById("myList").childNodes[indexOfChildToRemove].remove(indexOfChildToRemove);
}
}
}
</script>
<div class="submit">
<#s.submit theme="xhtml" value="Guardar"/>
</div>

Replace
<button class="submit" onclick="adicionaEntidade()">Adicionar</button> <button class="submit" onclick="removaEntidade()">Remover</button>
By
<button class="submit" onclick="adicionaEntidade()">Adicionar</button> <button class="submit" onclick="removaEntidade(); return false">Remover</button>
The thing is that this button submits the form, and so reloads the page. Making a return false into onclick function prevent form from being submitted.

You can modify the button with input type="button" as follows which will not submit the form:
<input type="button" class="submit" onclick="adicionaEntidade()" value="Adicionar"/>
<input type="button" class="submit" onclick="removaEntidade()" value="Remover"/>

Related

Regardless of what I choose in the drop-down box, it only gives the same font whenever I press Enter

What is the problem? I keep getting green fonts regardless of whether I choose "Pass", "Fail" or "Borderline". I hope someone can help me fix it so that whenever I choose Pass I get the name and green font in the list, Fail will give me the name and a red font while Borderline will give me the name and the orange font, thanks!
<html>
<body>
<form id="form">
Enter Student Name <input type="text" id="name">
Grade <select id="gradism">
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
<option value="Borderline">Borderline</option>
</select>
<button type="button" id="enter" onclick="myFunction()">Enter</button>
</form>
<h1>Students</h1>
<ul id="list"></ul>
<script>
selected = document.getElementById("gradism").value
if (selected == "Pass") {
function myFunction() {
var text = "";
var userName = document.getElementById("name").value;
document.getElementById("list").style.color = "#00FF00";
var li = document.createElement("li");
var node = document.createTextNode(userName);
li.appendChild(node);
if (userName.trim().length > 0) {
document.getElementById("list").appendChild(li);
document.getElementById("form").reset()
}
}
}
else if (selected == "Fail") {
function myFunction() {
var text = "";
var userName = document.getElementById("name").value;
document.getElementById("list").style.color = "#FF0000";
var li = document.createElement("li");
var node = document.createTextNode(userName);
li.appendChild(node);
if (userName.trim().length > 0) {
document.getElementById("list").appendChild(li);
document.getElementById("form").reset()
}
}
}
else if (selected == "Borderline") {
function myFunction() {
var text = "";
var userName = document.getElementById("name").value;
document.getElementById("list").style.color = "#FFA500";
var li = document.createElement("li");
var node = document.createTextNode(userName);
li.appendChild(node);
if (userName.trim().length > 0) {
document.getElementById("list").appendChild(li);
document.getElementById("form").reset()
}
}
}
</script>
</body>
</html>```
The reason your code is failing is this: when the page loads your logic gets evaluated. Immediately your conditional runs and the page decides which of the functions it will use. It's never changing because it all evaluates once when the page loads
When you want to test for a conditional, do it inside a single function, rather than create multiple functions for each outcome. In this case it also means we won't test for the value of the pulldown UNTIL the function is run. Also, since you're changing the style of your elements, lets use classes. Much easier to work with and more scalable. We can simply pass the value of the pulldown directly to the new element as a class with li.classList.add(color.toLowerCase())
function myFunction() {
var text = "";
var userName = document.getElementById("name").value;
let color = document.getElementById("gradism").value
var li = document.createElement("li");
li.classList.add(color.toLowerCase())
var node = document.createTextNode(userName);
li.appendChild(node);
if (userName.trim().length > 0) {
document.getElementById("list").appendChild(li);
document.getElementById("form").reset()
}
}
.pass {
color: #00FF00;
}
.borderline {
color: #FFA500;
}
.fail {
color: #FF0000;
}
<form id="form">
Enter Student Name <input type="text" id="name"> Grade
<select id="gradism">
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
<option value="Borderline">Borderline</option>
</select>
<button type="button" id="enter" onclick="myFunction()">Enter</button>
</form>
<h1>Students</h1>
<ul id="list"></ul>

how to remove textfield using dom

I have a form that permits to user to add textfield whenever he click on a button
I want to add link below every added textfield that allow to remove it
here is the script
<script>
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var input = document.createElement("input");
var del = document.createElement("button");
var div = document.createElement("div");
del.className = "del"
del.innerText = "X"
div.appendChild(input)
div.appendChild(del)
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
wrapper.appendChild(div)
}
document.getElementById("dynamic-question").addEventListener("click",function(e) {
if (e.target.className=="del") {
e.target.closest("div").remove()
}
})
</script>
and here the html code
<form id="myForm" method="POST" action="./gett">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="text" name="ans1" id="ans1" value=""><br><br>
<input type="text" name="ans2" id="ans2" value=""><br><br>
<div id="dynamic-question"></div>
<button type="button" onclick="myFunction()">Add proposition</button> <br><br>
<input type="submit" value="submit">
</form>
type=button on the add
e.preventDefault() on the button to delete OR make type=button too
Use a container for the input, the BRs and the delete to get rid of them all in one go
Then call remove
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var input = document.createElement("input");
var del = document.createElement("button");
var div = document.createElement("div");
del.className = "del";
del.innerText = "X";
del.type="button";
div.appendChild(input);
div.appendChild(del);
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
wrapper.appendChild(div);
}
document.getElementById("dynamic-question").addEventListener("click",function(e) {
if (e.target.className=="del") {
e.preventDefault();
e.target.closest("div").remove();
}
})
<button type="button" onclick="myFunction()">Add</button>
<div id="dynamic-question"></div>
Individually like this - all nearest siblings needs to be removed including the BRs
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var input = document.createElement("input");
var del = document.createElement("button");
del.className = "del";
del.type="buttpn"
del.innerText = "X";
wrapper.appendChild(input);
wrapper.appendChild(del);
wrapper.appendChild(document.createElement("br"));
wrapper.appendChild(document.createElement("br"));
}
document.getElementById("dynamic-question").addEventListener("click",function(e) {
if (e.target.className=="del") {
e.preventDefault();
e.target.previousElementSibling.remove(); // remove field
e.target.nextElementSibling.remove(); // remove br
e.target.nextElementSibling.remove(); // remove br
e.target.remove();
}
})
<button type="button" onclick="myFunction()">Add</button>
<div id="dynamic-question"></div>
You can try creating link like button, you can attach a function to that button to remove like the following way:
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var form = document.getElementById("myForm");
var input = document.createElement("input");
var btn = document.createElement("button");
btn.textContent = "Remove";
btn.addEventListener('click', remove);
wrapper.appendChild(input);
wrapper.appendChild(btn);
wrapper.appendChild(document.createElement("br"));
wrapper.appendChild(document.createElement("br"));
}
function remove(){
this.previousSibling.remove(); //Remove the input
this.nextSibling.remove(); //Remove the first br
this.nextSibling.remove(); //Remove the second br
this.remove(); //Remove the button
}
button:not(:first-child) {
background:none!important;
color:inherit;
border:none;
padding:0!important;
font: inherit;
border-bottom:1px solid #444;
cursor: pointer;
}
<button type="button" onclick="myFunction()">Create</button>
<div id="dynamic-question"></div>
You can remove an element from the DOM like so:
To remove a specified element without having to specify its parent node:
function removeEl(id) {
let node = document.getElementById(id);
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
MDN Docs
So, in your case, you may want to add an ID when you are creating the textfield, so you are able to find it again and then remove it:
<script>
function myFunction() {
let wrapper = document.getElementById("dynamic-question");
var form = document.getElementById("myForm");
var input = document.createElement("input");
// Add id here
input.id = "[id_here]"
wrapper.appendChild(input)
wrapper.appendChild(document.createElement("br"));
wrapper.appendChild(document.createElement("br"));
}
</script>
Then you can call the function above like so:
removeEl("[id_here]")
Try this:
For each element you dynamically add, create a div and add a remove link with some class, then add a listener that when user clicks on the remove link, it removes the element, and the parent element (the div that the link and the input are inside).
//annonymous function
var btnAddField = document.getElementById("btnAddField");
var wrapper = document.getElementById("wrapper");
btnAddField.onclick = function() {
var div = document.createElement('div');
var input = document.createElement("input");
var removeLink = document.createElement("a");
removeLink.innerHTML = 'Remove input';
removeLink.className = "btn-remove";
div.append(input);
div.append(removeLink)
wrapper.append(div);
};
document.addEventListener('click',function(e){
if(e.target && e.target.className == 'btn-remove'){
e.target.parentNode.remove();
}
});
<div id="wrapper">
<button id="btnAddField">
Add input field
</button>
</div>

how to cross out the text when clicking checkBox javascript

I'm trying to cross out text next to the checkbox button when the checkbox is clicked by the user. But when I test it, for some reason nothing is happening. I want to check if the box is checked. If it is then I want to to cross that item next to that check box. This function, however does not work. Can someone please explain what I'm doing wrong? thanks.
function myFunction() {
var editButton = document.createElement("button");
//button.delete
var deleteButton = document.createElement("button");
var item = document.getElementById("todoInput").value
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "checkbox"
var text = document.createTextNode(item)
var newItem = document.createElement("li")
newItem.className = "addedClass"
newItem.appendChild(text)
if (item === "") {
alert("please fill in the blanks");
} else {
var crap = document.getElementById("todoList")
crap.appendChild(newItem)
var addhere = document.getElementById("todoList")
addhere.appendChild(checkBox);
}
function updateItem() {
if (document.getElementById(checkbox).checked) {
document.getElementById(todoList).style.textDecoration = "line-through"
}
}
}
<form name="myForm" id="todoForm">
<input id="todoInput" name="fname" required>
<button type="button" onclick="myFunction()">OK</button>
</form>
<ol id="todoList"></ol>
first handle event and call the update function and this snippet for you need to add event to checkbox. i hope it should help you thanks.
function myFunction()
{
var item=document.getElementById("todoInput").value
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id="checkbox"
checkBox.onchange=updateItem
var text=document.createTextNode(item)
var newItem=document.createElement("li")
newItem.className="addedClass"
newItem.appendChild(text)
if (item === "")
{
alert("please fill in the blanks");
}
else
{
var crap=document.getElementById("todoList")
crap.appendChild(newItem)
var addhere=document.getElementById("todoList")
addhere.appendChild(checkBox);
}
function updateItem()
{
if (document.getElementById("checkbox").checked)
{
document.getElementById("todoList").style.textDecoration="line-through"
}
}
}
<html>
<form name="myForm" id="todoForm">
<input id="todoInput" name="fname" required >
<button type="button" onclick="myFunction()">OK</button>
</form>
<ol id ="todoList">
</ol>
</html>
you can use other wise HTML5 element for the same purpose.
<strike>not yet available!</strike>
Your code has lot of issues,
Some of the fixes / improvements I have done,
You are missing } or closed inappropriately in your code for myFunction().
Always try to use id for element on which you are going to process. I have added an id on li. (The text node)
function myFunction()
{
var item=document.getElementById("todoInput").value
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id="checkbox"
var text=document.createTextNode(item)
var newItem=document.createElement("li")
newItem.id = "textEl";
newItem.className="addedClass"
newItem.appendChild(text)
if (item === "") {
alert("please fill in the blanks");
}
else{
var crap=document.getElementById("todoList")
crap.appendChild(newItem)
var addhere=document.getElementById("todoList")
addhere.appendChild(checkBox);
document.addEventListener('change', function (e) {
updateItem();
});
}
}
function updateItem()
{
if (document.getElementById("checkbox").checked)
{
document.getElementById("textEl").innerHTML = document.getElementById("textEl").innerHTML.strike();
}
}
<html>
<form name="myForm" id="todoForm">
<input id="todoInput" name="fname" required >
<button type="button" onclick="myFunction()">OK</button>
</form>
<ol id ="todoList">
</ol>
</html>

Mouseover function on dynamically created list items

I'm working on a simple user input form that has users input their ID, first name, and last name into 3 separate input boxes. My main objective is to get the data input by user, add it to the "person" object, and display to an unordered list. I've figured that much out.
What I'm trying to do now, is somehow style the content of the list item that was dynamically created, using a mouseover function. I have been trying simple color changes, but I'm super rusty with javascript, and must do this without any jQuery. Any help is appreciated. Just need a push in the right direction, can't get mouseover to work at all for some reason.
Here's what I've got so far:
<form>
ID Number:<br>
<input type="text" id="idNumber">
<br>
First name:<br>
<input type="text" name="firstName" id="fName">
<br>
Last name:<br>
<input type="text" name="lastName" id="lName">
</form>
<br>
<button type ="submit" onclick="myFunction(list)">Submit</button>
<div id = "container">
<ul id="list"></ul>
</div>
<script>
function myFunction(list){
var text = "";
var person = {idNo:"", firstName:"", lastName:""};
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
idNo = inputs[0].value;
firstName = inputs[1].value;
lastName = inputs[2].value;
text = " "+idNo+" "+firstName+" "+lastName;
}
var li = document.createElement("li");
li.addEventListener("mouseover", mouseOver, false);
li.addEventListener("click", mouseClick, false);
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
function mouseOver(){
li.style.backgroundColor="red";
}
</script>
li is not defined in the function mouseover use this instead -> this.style.backgroundColor = "red";
Variables are defined at function scope therefore var li is available in myFunction but not in mouseover function.
Try this sinppet:
function myFunction(list) {
var text = "";
var person = {
idNo: "",
firstName: "",
lastName: ""
};
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
idNo = inputs[0].value;
firstName = inputs[1].value;
lastName = inputs[2].value;
text = " " + idNo + " " + firstName + " " + lastName;
}
var li = document.createElement("li");
li.addEventListener("mouseover", mouseOver, false);
//li.addEventListener("click", mouseClick, false);
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
function mouseOver() {
this.style.backgroundColor = "red";
}
<form>
ID Number:
<br>
<input type="text" id="idNumber">
<br>First name:
<br>
<input type="text" name="firstName" id="fName">
<br>Last name:
<br>
<input type="text" name="lastName" id="lName">
</form>
<br>
<button type="submit" onclick="myFunction(list)">Submit</button>
<div id="container">
<ul id="list"></ul>
</div>
Why use JS when you can use CSS?
JavaScript:
var li = document.createElement("li");
li.classList.add('my-li-class')
CSS:
.my-li-class:hover {
background-color: red;
}
Anyway if you want to know why your JS doesn't work it's because the li variable is defined outside the mouseOver function scope, do this instead:
function mouseOver() {
this.style.backgroundColor = 'red'
}
Or event this (may not work if li has children):
function mouseOver(evt) {
evt.target.backgroundColor = 'red'
}

JavaScript - Get text in div by class

I am trying to get just the content/text of div by class name using javascript. The outcome isn't what i have expected. I did try to push it into array but it does not seems to be working. Please help!
What i have done so far :
JavaScript:
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year= document.getElementById("year");
for (i=0;i<elements.length;i++)
{
var Entry = document.createElement("option");
Entry.text = elements[i];
year.add(Entry ,null);
}
}
Html:
<form>
<select id="year">
</select>
</form>
<input type="submit" value="Submit">
<div class="headline-bar">2015</div>
<div class="headline-bar">2014</div>
Output:
Desire outcome:
Use Node.textContent, The Node.textContent property represents the text content of a node and its descendants
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year = document.getElementById("year");
for (i = 0; i < elements.length; i++) {
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry, null);
}
}
<form>
<select id="year">
</select>
</form>
<input type="submit" value="Submit">
<div class="headline-bar">2015</div>
<div class="headline-bar">2014</div>

Categories

Resources