What am doing wrong in here? - javascript

Input value always gets into if condition first even am parsing it to parseInt() and when page refreshed with a number it gets into else condition, like its not registering the inputValue at first place, also if i add a submit event rather an click one event doesnt fires up.
HTML
<div class="addHere"></div>
<div class="inputs">
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:"/>
<button class="btn">+</button>
</div>
javaScript
// this line was modified
const inputValue = parseInt(document.querySelector(".inputValue").value);
const div = document.querySelector(".addHere");
document.querySelector(".btn").addEventListener("click", addInputs);
fucntion addInputs() {
if(isNaN(inputValue)) {
alert("Wrong input");
} else {
for ( let i = 1; i <= inputValue; i++) {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
const input1 = document.createElement("input");
input1.type = "text";
input1.maxLength = "12";
input1.className = "factor";
input1.required = true;
const input2 = document.createElement("input");
input2.type = "text";
input2.maxLength = "1";
input2.className = "priority";
input2.required = true;
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(input1);
form.appendChild(input2);
form.appendChild(br.cloneNode());
div.appendChild(form);
}
const sub = document.createElement("button");
sub.type = "submit";
sub.value = "Submit";
sub.className = "subButton";
sub.textContent = "Submit";
div.appendChild(sub);
}
}

const inputValue = parseInt(document.querySelector(".inputValue").value);
Is being executed once, so every time you click on + button it won't read value of the tag. You have to move this statement inside you click handler, like this:
function addInputs() {
// this should be here, so every time you click on + button, actuall values is being read
const inputValue = parseInt(document.querySelector(".inputValue").value);
if (isNaN(inputValue)) {
alert("Wrong input");
} else {
for (let i = 1; i <= inputValue; i++) {
const form = document.createElement("form");
...
Also here:
const div = document.querySelector(".addHere");
I could not find div with such class in your HTML, so you have to add it like this, I think:
<div class="inputs">
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:" />
<button class="btn">+</button>
</div>
<div class="addHere"> </div>

You're recording the value of the input on page load, so at first it is empty.
Move this line
const inputValue = parseInt(document.querySelector(".inputValue").value);
to be the first line of your function that runs after clicking your button.
function addInputs() {
const inputValue = parseInt(document.querySelector(".inputValue").value);
Also it is probably best to use ID's for those elements and select them by their ID's rather than a class. ID's are unique so there can only be one of them on the page.
I also corrected typos in those lines, missing " and misspelled function.

You forgot an " in the first line in javascript code.
const inputValue = parseInt(document.querySelector(".inputValue").value);

const div = document.querySelector(".addHere");
document.querySelector(".btn").addEventListener("click", addInputs);
function addInputs() {
const inputValue = parseInt(document.querySelector(".inputValue").value);
for (let i = 1; i <= inputValue; i++) {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
const input1 = document.createElement("input");
input1.type = "text";
input1.maxLength = "12";
input1.className = "factor";
input1.required = true;
const input2 = document.createElement("input");
input2.type = "text";
input2.maxLength = "1";
input2.className = "priority";
input2.required = true;
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(input1);
form.appendChild(input2);
form.appendChild(br.cloneNode());
div.appendChild(form);
}
const sub = document.createElement("button");
sub.type = "submit";
sub.value = "Submit";
sub.className = "subButton";
sub.textContent = "Submit";
div.appendChild(sub);
}
<div class="addHere"></div>
<div class="inputs">
<input type="number" min="0" max="9" class="inputValue" placeholder="insert numbers:" />
<button class="btn">+</button>
</div>

Related

How to set focus on next input when the button "Enter" is pressed? (javascript)

I need some advice.
I have created a function where when spacebar is pressed, it'll create a new input field. What i would like to know is how to set focus on the input field that has been created when spacebar is pressed.
Thanks in advance.
Here is my code: (HTML included)
<div id="paper">
<div id="content">
<input type="text" class="input1">
</div>
</div>
Javascript:
'use strict';
const input1 = document.querySelector('.input1');
const add = input1.addEventListener('keydown', function(e){
if((e.keyCode === 13)){
return mover();
}
});
const mover = function(){
const mega = document.createElement('input');
const content = document.getElementById('content');
content.appendChild(mega);
mega.style.border = "0px solid";
mega.style.marginTop = "75px";
mega.style.width = "600px";
}
Something like this, could do the trick.
const container = document.getElementById("inputs-container");
let inputs = document.getElementsByTagName("input");
// Add input on press Enter
document.onkeyup = (evt) => {
if (evt.keyCode == 32) {
let input = document.createElement("input");
input.type = "text";
input.placeholder = "Input...";
input.onkeyup = inputOnEnter;
container.appendChild(input);
inputs = document.getElementsByTagName("input");
}
};
// Focus next input on Space
const inputOnEnter = (evt) => {
if (evt.keyCode == 13) {
let index = Object.keys(inputs).filter(a => inputs[a] === evt.target);
let nextIndex = parseInt(index) + 1;
if (inputs[nextIndex]) inputs[nextIndex].focus();
}
};
for (let i = 0; i < inputs.length;i++) {
inputs[i].onkeyup = inputOnEnter;
}
<div id="inputs-container">
<input type="text" placeholder="Input..." />
</div>

HTML Javascript dynamically add and remove textboxes

I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}

Add and Remove button JavaScript [duplicate]

This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 5 years ago.
I need make button to add and remove that adds and removes inputs.
Did I write normal script or adding button should be another?
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
I made some modifications to Anu's answer, but this should do the trick.
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
var t = document.createTextNode("X");
btn.id = i;
btn.appendChild(t);
btn.onclick = function() {
$('#' + i).remove();
$('#' + i).remove();
i = i - 1;
};
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
const addButton = document.getElementById("add");
const hobbyWrapper = document.getElementById("hobby");
let i = 0
addButton.addEventListener("click", add);
function add (){
i = i + 1
const inputWrapper = document.createElement('div');
inputWrapper.id = `inputWrapper-${i}` ;
const input = document.createElement('input');
input.placeholder = "More hobbies";
inputWrapper.appendChild(input)
const removeButton = document.createElement('button');
removeButton.innerHTML = 'X';
removeButton.onclick = () => {
hobbyWrapper.removeChild(inputWrapper)
}
inputWrapper.appendChild(removeButton);
hobbyWrapper.appendChild(inputWrapper);
}
<div id="hobby">
<div id="inputWrapper">
<input placeHolder="Type your hobby">
<button>X</button>
</div>
</div>
<button id="add">Add hobby</button>
var div = document.getElementById('hobby');
function addHobby() {
var input = document.createElement('input'),
button = document.createElement('button');
input.placeholder = "More hobbies";
button.innerHTML = 'X';
// attach onlick event handler to remove button
button.onclick = removeHobby;
div.appendChild(input);
div.appendChild(button);
}
function removeHobby() {
// remove this button and its input
div.removeChild(this.previousElementSibling);
div.removeChild(this);
}
// attach onclick event handler to add button
document.getElementById('add').addEventListener('click', addHobby);
// attach onclick event handler to 1st remove button
document.getElementById('remove').addEventListener('click', removeHobby);
<div id="hobby">
<input placeHolder="Type your hobby" />
<button id="remove">X</button>
</div>
<button id="add">Add hobby</button>
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function(){
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
var button = document. createElement("button");
button. innerHTML = "X";
button.id=i;
button.onclick = function() {
div.removeChild(document.getElementById(button.id));
div.removeChild(button)
}
div.appendChild(button);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
I think I see where you are going with this, add and remove hobbies.
Note for simplicity I wrap each group in a span, then add/remove that span.
I did NOT put a remove on the first one, you might do that IF you wanted to make it removable.
const addHobby = document.getElementById("add");
var i = 0;
const hobbydiv = document.getElementById("hobby");
addHobby.addEventListener("click", function() {
i++;
const newspan = document.createElement('span');
newspan.className = "groupthing";
const removeButton = document.createElement('button');
removeButton.addEventListener('click', function(e) {
e.target.closest(".groupthing").remove();
});
removeButton.className = "deleteus";
removeButton.innerHTML = "X";
const editInput = document.createElement('input');
editInput.id = i;
editInput.placeholder = "More hobbies";
newspan.appendChild(editInput);
newspan.appendChild(removeButton);
hobbydiv.appendChild(newspan);
});
.deleteus{color:red;}
<div id="hobby">
<span class="groupthing">
<input placeHolder="Type your hobby" />
<button class="deleteus">X</button>
</span>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
To add button,
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function () {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
btn.id = i;
var t = document.createTextNode("X");
btn.appendChild(t);
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
btn.addEventListener("click", function () {
div.removeChild(document.getElementById(btn.id));
div.removeChild(btn);
});
});

innerHTML not showing up when added input element dynamically

I am trying to add an <input> element using Javascript. However, the innerHTML is not showing up. Below is my code:
function addElements()
{
container = document.getElementById("duration"); //a div container
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
input1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
input2.innerHTML = "months";
container.appendChild(input1);
container.appendChild(input2);
}
The result of this code only produces two number input fields without the innerHTML. Is there anything wrong with my code?
Input elements don't have inner content you can set with innerHTML. Instead set value property:
input1.value = "years";
However, it seems that in your case you want to set placeholder:
input1.setAttribute("placeholder", "years");
or you can set corresponding property as well:
input1.placeholder = "years";
I think what you try to achieve is [label][input] in this case you have to add 2 new more elements on page.
function addElements()
{
container = document.getElementById("duration"); //a div container
var label1 = document.createElement("label");
var input1 = document.createElement("input");
var label2 = document.createElement("label");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
label1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
label2.innerHTML = "months";
container.appendChild(label1);
container.appendChild(input1);
container.appendChild(label2);
container.appendChild(input2);
}
addElements();
<div id="duration" />

Removing the corresponding textbox of the anchor tag

I have created a simple application in javascript. The application is that a value is selected from a dropdown list and if the button next to it is clicked then the specified number of texboxes selected in the dropdown are added to the DOM with a a to their right sides.
Here's the HTML:
<form>
<select style="width: 250px;" id="numMembers" <!--onchange="addMembers();" -->>
<option value="0">Add More Members...</option>
<script>
for (var i = 1; i <= 10; i++) {
document.write('<option value=' + i + '>' + i + '</option>');
};
</script>
</select>
<button onclick="addMembers();" type="button">Add</button>
<div style="margin-top: 10px; border: 1px solid #eee; padding: 10px;">
<input type="text" />
<br/>
<input type="text" />
<br/>
<input type="text" />
<br/>
</div>
<div id="extras"></div>
</form>
And here's the script:
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function () {
document.removeChild(this);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
How can I remove the textbox on the left of the anchor tag which is when clicked. For example:
[XXXXXXX] Remove(x)
[XXXXXXX] Remove(x)
If the last "Remove(x)" is clicked then the last textbox should be removed hence the one to the left of it.
How can I do it?
Note: No JQuery solutions please! I could do that even myself :P.
You can pass the id on anchorTag and can pass same id with some addition for input text, like
If you pass the id input1 for a then use the id input1Text for relative text box,
So you when you click on particular link, you will get a with input1 and get relative input text with 'input1Text'.
This would be apply for input2, input3, ... Something like this.
DEMO
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.id = "input"+i+"Text"; //give the id with Text
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
//when you click on this link you will get relative textbox by "input"+i+"Text";
removeHref.id = "input"+i;
removeHref.onclick = function () {
var removeNodeText = document.getElementById(this.id+"Text");
removeNodeText.parentNode.removeChild(removeNodeText);
var removeNodeLink = document.getElementById(this.id);
removeNodeLink.parentNode.removeChild(removeNodeLink);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
Try This
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.id = "text_"+i;
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.id = "href_"+i;
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function(){
var id= this.id.split('_')[1];
console.log(id)
document.getElementById("extras").removeChild(document.getElementById('text_'+id));
document.getElementById("extras").removeChild(this);
}
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}

Categories