How to add an input and remove it if existed with javascript - javascript

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>

Related

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>

Javascript compare two text fields

I'm trying to compare two Textfields with Javascript. But one of them must have a bigger value then the other one, like 5 = 4.
I dont know why.
<script>
document.getElementById("text1").addEventListener("keydown", testpassword2);
function testpassword2() {
var text1 = document.getElementById("text1");
var text2 = document.getElementById("text2");
if(text1.value == text2.value){
text2.style.borderColor = "#2EFE2E";
}
else{
text2.style.borderColor = "red";
}}
</script>
Some issues with your code:
You only had an event listener on the first input. You'll need to add an event listener to the second input as well.
The value on keydown won't contain the same value as on keyup. You'll need to do keyup to keep up with user input.
Working fiddle here.
document.getElementById("text1").addEventListener("keyup", testpassword2);
document.getElementById("text2").addEventListener("keyup", testpassword2);
function testpassword2() {
var text1 = document.getElementById("text1");
var text2 = document.getElementById("text2");
if (text1.value == text2.value)
text2.style.borderColor = "#2EFE2E";
else
text2.style.borderColor = "red";
}
<body>
<input type="text" id="text1" size="30">
<input type="text" id="text2" size="30">
</body>

Javascript 'innerHTML' Method Overwriting Checkbox Selection

I have a form, id="myForm" or document.forms[0], with checkbox inputs, which I am writing dynamically with the help of Javascript functions and another HTML form, id="addForm" or document.forms[1], which has a text box and a clickable button.
The myForm is:
<form id="myForm" action="Save.php" method="post">
<div id="skillSet"></div>
<input type="submit">
</form>
My addForm is:
<form id="addForm"><input id="skillAdd" type="text" name="newSkillName">
<input class="button" type="button" value="Add" onClick="addSkill(document.forms[1].newSkillName.value)">
</form>
and my javascript function addSkill() is:
function addSkill(newSkill)
{
if(newSkill.length > 0)
{
var inner = document.getElementById("skillSet").innerHTML;
var newSkillDefinition = ('<div class="skillName"><label><input type="checkbox" checked name="skill[]" value="' + newSkill + '" title="Toggle Selection">' + newSkill + '</label></div>');
document.getElementById("skillSet").innerHTML = inner + newSkillDefinition;
}
}
All right, so I'll give you guys a scenario:
Using addForm, i've added 5 checkbox items to myForm, all 5 are checked by default of course, because of the checkbox "checked" attribute. But i decide to uncheck 3 of them. After this, I add another checkbox item. As soon as i do that, ALL of my previous checkbox items get checked automatically. So my previous selection has all vanished!
I know this definitely has something to do with the "checked" attribute and also innerHTML that I am using.
It's been a real headache. Is there any fix or way around this problem?
You can avoid that hassle by using the JavaScript appendChild method, instead of replacing the whole HTML. Something like that:
function addSkill(newSkill)
{
if(newSkill.length > 0)
{
var skillSet = document.getElementById("skillSet"),
skill = document.createElement('div'),
label = document.createElement('label'),
input = document.createElement('input');
input.type = "checkbox";
input.checked = "true";
input.name = "skill[]";
input.value = newSkill;
input.title = "Toggle Selection";
label.appendChild(input);
skill.appendChild(label);
skill.className = "skillName";
skillSet.appendChild(skill);
}
}
Add a node instead of using innerHTML:
var skillSet = document.getElementById("skillSet")
//Create elements
var div = document.createElement('div'),
var label = document.createElement('label');
var input = document.createElement('input');
var newSkill = "This is a new skill";
//Setup input
input.type = "checkbox";
input.checked = true;
input.name = "skill[]";
input.val = newSkill;
input.title = "Toggle Selection";
//Append new elements to div
var text = document.createTextNode(newSkill);
label.appendChild(text);
label.appendChild(input);
div.appendChild(label);
//Append div to original skillSet
skillSet.appendChild(div);
OUTPUT
<div>
<label>This is a new skill
<input type="checkbox" name="skill[]" title="Toggle Selection">
</label>
</div>
InnerHTML will "causes the destruction of all child elements, even if you're trying to append". Both of the solutions from raam86 and Rotem Harel should help you, as you should be using the appendChild method for this problem.
See this answer

Multiple dynamic input text javascript

Im having trouble creating multiple input texts with javascript.
My point is create a new input text everytime the input before is completed. (parent?)
Ive some code for comboboxs, but this time I need just input text box.
How can I do that ?
I've found this code:
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"text\" />";
}
</script>
<input type="button" onmousedown="addInput();" />
<div id="inputs"></div>
But for my problem button is obsolete.
I think my event trigger will be something arround this "when user click in an input text box and it is != blank it creates a new one".
I migth need some ID to identify every input text box.
Cheers.
JSBIn Demo
Guess this helps:
<div id="myDiv">
<input type="text" id="txt_1" onkeydown="newTextBox(this)" />
</div>
<script type="text/javascript">
function newTextBox(element){
if(!element.value){
element.parentNode.removeChild( element.nextElementSibling);
return;
}
else if(element.nextElementSibling)
return;
var newTxt = element.cloneNode();
newTxt.id = 'txt_'+( parseInt( element.id.substring(element.id.indexOf('_')+1)) + 1);
newTxt.value='';
element.parentNode.appendChild(newTxt);
}
</script>
HTML code:
<div id="inputcontainer">
<input type="text" name="input0" id="input0" onkeyup="addInput();" />
</div>
And Javascript:
var currentindex = 0;
function addInput(){
var lastinput = document.getElementById('input'+currentindex);
if(lastinput.value != ''){
var container = document.getElementById('inputcontainer');
var newinput = document.createElement('input');
currentindex++;
newinput.type = "text";
newinput.name = 'input'+currentindex;
newinput.id = 'input'+currentindex;
newinput.onkeyup = addInput;
container.appendChild(newinput);
}
}
This will add a new input to the list only when the last input is not empty.
http://jsfiddle.net/HJbgS/
Have a look at the onchange event on your text input field. You can use it, like you use onmousedown on your button.
See http://www.w3schools.com/jsref/event_onchange.asp for an example.
In your addInput() function you should then check if the input of the previous textfield is != "".

Categories

Resources