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>
Related
So how do I require the input field in my form not to be empty when clicking on the submit button? I don't want to use the HTML attribute require. My HTML and JS code are below if someone is interested in taking a look
JS:
let form = document.getElementById("addForm");
// Form submit event
form.addEventListener("submit", addItem);
// Add item
function addItem(e){
e.preventDefault();
console.log(e);
// Get input value
let newItem = document.getElementById("item").value;
// Create new li
let newLI = document.createElement("li");
// Add class
newLI.className = "list-group-item";
// Add text node with input
newLI.textContent = newItem;
//Delete button
let button = document.createElement("button");
button.className = "btn btn-danger btn-sm float-right delete";
button.textContent = "X";
newLI.appendChild(button);
itemList.appendChild(newLI);
document.getElementById("item").value = "";
}
HTML:
<form id="addForm" class="form-inline mb-3">
<input type="text" class="form-control mr-2" id="item">
<input type="submit" class="btn btn-dark" value="Submit">
</form>
In your code you can check if newItem is empty before preventing the submition. Like this:
let newItem = document.getElementById("item").value;
if(newItem === "")
{
e.preventDefault();
}
You have to change your HTML like this:
<form id="addForm" class="form-inline mb-3">
<input type="text" class="form-control mr-2" id="item" required>
<input type="submit" class="btn btn-dark" value="Submit">
</form>
function addItem(e){
//e.preventDefault();
console.log(e);
// Get input value
let newItem = document.getElementById("item").value;
if (newItem === ""){
e.preventDefault()
}
else {
// Create new li
let newLI = document.createElement("li");
// Add class
newLI.className = "list-group-item";
// Add text node with input
newLI.textContent = newItem;
//Delete button
let button = document.createElement("button");
button.className = "btn btn-danger btn-sm float-right delete";
button.textContent = "X";
newLI.appendChild(button);
itemList.appendChild(newLI);
document.getElementById("item").value = "";
}
}
You will need to select your form input field in JavaScript -
const formInput = document.querySelector('#item');
And then in addItem function you can check something like below -
if (formInput.value === '') {
console.log('No Input Entered!');
}
I have a form and I want to add new input in that and if this input existed remove that or prevent from being added.
In my code just added one input and when I try to add another different input first input cleans
Body :
<input type="text" id="member" name="member" value="">name<br />
add
<div id="container"/>
footer:
<script type='text/javascript'>
function addFields(){
var name = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<1;i++){
container.appendChild(document.createTextNode(name+ (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = name;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
container.appendChild(document.createElement("br"));
}
}
</script>
You can use querySelector('#member') to check if the input exists or not.
function addFields() {
var container = document.getElementById("container");
if (!container.querySelector('#member')) {
container.innerHTML = `<input type="text" id="member" name="member" value="">name`;
console.log('input added');
}
}
add
<div id="container">
</div>
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>
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'
}
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"/>