Removing Elements using DOM - javascript

I am attempting to create an appear and disappear effect with an input. When the radio button is "no", the item should appear. When the radio button is "yes", the item should disappear. I have got the item to appear so far, but cannot get it to be removed through DOM. I have included my example on how I can remove my email which i commented out, but can't seem to remove the innerHTML or the input.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : $";
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
alert("Added Text Box");
}
function myFunction2() {
alert("Removed Textbox and Input");
anchor = document.getElementById("label");
anchor.parentNode.removeChild(anchor);
anchor2 = document.getElementById("INPUT");
anchor2.parentNode.removeChild(anchor2);
//THIS WORKS TO REMOVE EMAIL.
//anchor3 = document.getElementById("emailP");
//anchor3.parentNode.removeChild(anchor3);
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" onclick="myFunction2()" />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<br>
<br>
<button>Submit</button>
</form>
</body>
</html>

It's not working, because the lines anchor = document.getElementById("label"); and anchor2 = document.getElementById("INPUT"); are looking for elements with the id label and input, but can't find them. Those are actually tag names.
You need to add an id to the elements you create in the first function:
label.setAttribute("id", "idForLabel");
x.setAttribute("id", "idForInput");
and then change the lines in the second function to:
anchor = document.getElementById("idForLabel");
anchor2 = document.getElementById("idForInput");

Related

Creating input elements and filling them with js script

I was trying to add some rows of input to my form so I will be able to post them to the back-end in one request, and also be able to add more of the same information type if need be
this is the code that I'm using:
<!DOCTYPE html>
<head>
</head>
<body>
<form action="#" method="post">
<input id="firstElement" type="text" name="firstElement" value="">
<button onClick="addRow()">add row</button><br>
<div id="container"></div>
<input type="submit" value="submit">
</form>
<script>
function addRow() {
var container = document.getElementById("container");
var myElement1 = document.getElementById("firstElement").value;
document.getElementById("firstElement").value = "";
var i = 0;
var input1 = document.createElement("input");
input1.type = "text";
input1.name= "myElement1"+ i;
input1.disabled = "true";
input1.value = myElement1;
container.appendChild(input1);
container.appendChild(document.createElement("br"));
i++;
}
</script>
</body>
this code shows the output for a second or less and then nothing...
The default type attribute of a button element is submit, so when you click the button you're actually submitting your form. Change that easily by specifying the type to be a button instead:
<button onClick="addRow()" type="button">add row</button>
jsFiddle example

Creating text fields according to user's input in JavaScript Function

I want to create text fields according to user's input and show the text fields through JavaScript function but this code is not working!
<html>
<head>
<title>Create text Fields according to the users choice!</title>
<script type="script/JavaScript">
function createTextField(){
var userInput = parseInt(document.form2.txtInput.view);
for(var i=0; i<=userInput;i++)
{
document.write('<input type="text">');
}
}
</script>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
Please Replace this line:
var userInput = parseInt(document.form2.txtInput.view);
To
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
function createTextField(){
// alert(document.getElementById('txtInput').value);
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
for(var i=0; i<userInput;i++)
{
document.write('<input type="text">');
}
}
<html>
<head>
<title>Create text Fields according to the users choice!</title>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput" id="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
You shouldn't use document.write. The correct way to do it is to append the inputs to a div.
Demo on Fiddle
HTML:
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>Input:
<input type="text" name="txtInput" />
<input type="button" name="btnInput" value="Create" />
<div></div>
</form>
JavaScript:
var btn = document.getElementsByTagName("input")[1];
btn.onclick = function () {
var userInput = parseInt(document.getElementsByTagName("input")[0].value, 10);
for (var i = 0; i <= userInput - 1; i++) {
document.getElementsByTagName("div")[0].innerHTML += "<input type='text' />"
}
};
Jquery is better option to add dynamic input/div's easy to manipulate DOM.
Check the following code
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});
Demo URl: http://jsfiddle.net/sathyanaga/75vbgesm/3/
Change:
var userInput = parseInt(document.form2.txtInput.view);
To:
var userInput = parseInt(document.getElementById("txtInput").value);
And give the input textbox an id (I used "txtInput", but it can be anything).
I believe you also need to change the loop from, when I typed "2" it created 3 inputs instead of 2.

Adding textbox on button click with javascript

I'm working on a web form with a textbox for pets and an "add pet" button. Each time the button is clicked, an additional textbox should be displayed below the original one.
I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.
Here is the code I have so far:
<html>
<head>
<title>Project 4</title>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Pets: <input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
<br>
</form>
<script type="text/javascript">
function makeCopy() {
var copy = <input type="text">;
return copy;
}
</script>
</body>
</html>
There are other pieces to this as well, but none of them affect this particular problem I am having so didn't see the need to include the full code as it's fairly long.
Any suggestions are greatly appreciated.
Update:
I realize after reading the answers that I should've included more of my code to give you guys a better idea of the actual layout of my page. I have several text fields in my form and need the additional textboxes to be displayed right below the original "pets" textbox. Here's a jfiddle I threw together to give you guys a better idea of the layout. http://jsfiddle.net/a5m8nqwk/
Something like this?
<form name="myForm" id="myForm" onsubmit="return validateForm()">
Pets: <br />
<input type="text" id="pets" />
<input type="button" id="addPet" value="Add Pet" />
<br/>
</form>
document.getElementById("addPet").onclick = function() {
var form = document.getElementById("myForm");
var input = document.createElement("input");
input.type = "text";
var br = document.createElement("br");
form.appendChild(input);
form.appendChild(br);
}
Edit: I'd suggest using a table to style the input boxes, keep them in line. FIDDLE
You could easily add elements to the DOM:
function createPetField() {
var input = document.createElement('input');
input.type = 'text';
input.name = 'pet[]';
return input;
}
var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
form.appendChild(createPetField());
});
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
var text = document.getElementById("textId");
//Append the element in page (in span).
text.appendChild(element);
}
h1 {
color: #0000ff;
}
<h1>KIAAT</h1>
<b>Adding textbox on button click with javascript</b>
<br><br>
<form>
<input placeholder="text" name="element" hidden> </input>
<input type="button" value="Click Me" onclick="add(document.forms[0].element.value)"/>
<span id="textId"> </span>
</form>

How to delete a check box using javascript

I'm working on this HTML Page where i can add a check-box along with the label by clicking the add button, is there anyway that i can have a delete button as well so that when i select a check-box and press the delete button the check-box along with the text box is deleted??Please find my code below!!
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function Add()
{
var checkbox=document.createElement('input');
var inps=document.createElement('input');
var output=document.getElementById('output');
checkbox.type='checkbox';
inps.type='text';
inps.name='textboxname';
checkbox.name='checkname';
output.appendChild(checkbox);
output.appendChild(inps);
output.appendChild(document.createElement('br'));
}
</script>
</head>
<body>
<form action="http://localhost:9990" method="post">
<span id="output"></span>
<input type="button" value="Add" onclick="Add()">
<center>
<p>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</center>
</form>
</body>
</html>
Give all of the check boxes that could potentially be deleted the same class. Additionally label all of the text boxes that could be deleted with their own class. My check boxes will be labeled with chk and my text boxes will be labeled with txt. As in:
<input type="checkbox" class = 'chk' /> and
<input type="text" class = 'txt' />
The following solution should work as long as check boxes and text fields are 1 to 1.
the function you will add to your delete button will loop through all of the check boxes and see if they are deleted and then delete the checked ones.
Heres the JS:
function delBoxes(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
for(var i = 0; i<boxes.length; i++){
box = boxes[i];
txt = texts[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
That will delete all of the checked check boxes, all you have to do now is make a button and add that function as an onclick.
<input type="button" value="Delete checked boxes" onclick = "delBoxes();" />
Sample HTML
<div>
<input type='checkbox' value='asd' id='test' name='test' />
<input type='checkbox' value='asd' id='tester' name='test' />
<input type='button' value='remove' id='rmvBtn' />
</div>
In pure javascript, you can do this,
var rmvBtn = document.getElementById('rmvBtn');
rmvBtn.addEventListener('click', function(){
var rmvCheckBoxes = document.getElementsByName('test');
for(var i = 0; i < rmvCheckBoxes.length; i++)
{
if(rmvCheckBoxes[i].checked)
{
removeElm(rmvCheckBoxes[i]);
}
}
});
function removeElm(elm){
elm.parentElement.removeChild(elm);
}
JS Fiddle
HTML
<input type="checkbox" id="checkboxid" name="checkboxname">
<button id="btnDeleteid" onclick="deleteCheckBox()" name="btnDeletename">Delete</button>
JavaScript
function deleteCheckBox(){
if (document.getElementById('checkboxid').checked){
var answer = confirm('Are you sure you want to delete this checkbox?');
if (answer)
{
$("#checkboxid").remove();
}
}else{
alert("Pls check the checkbox.");
}
}
I hope this will help.
Refer fiddle - http://jsfiddle.net/F8w8B/3/

Print values of selected radio buttons and check-boxes and exclude the submit button

In the script below, how do I get the values of only radio buttons and checkboxes that have been selected and not all (provided a radio button and checkbox were selected).
Right now it gives me the values of all, whether selected or not, and also the submit button (which i dont need).
How do i do this? There'll be more checkboxes and radio buttons, i've used only 2 sets for this question.
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += elem[i].value+"<br>";
}
document.getElementById('lblValues').innerHTML = str;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Add the following test:
if(elem[i].checked)
str += elem[i].value+"<br>";
Also, if you use jQuery, the whole script is even simpler:
function DisplayFormValues(){
$("input:checkbox:checked").add("input:radio:checked")
.each(function(){
$("div#lblValues").append(this.value + "<br>");
});
}

Categories