I have two text boxes and two buttons named add and remove. The requirement is to add more boxes along with the current boxes. i somehow managed to add boxes but the requirement of removing the boxes is not working. Please help to why this code is not working and if possible suggest a working solution.
function addFunction(){
var element = document.createElement("input");
var parent = document.getElementById("form1");
parent.appendChild(element);
}
function removeFunction(){
var child = document.getElementsByTagName("input");
var parent = document.getElementById("form1");
for (var i = 0; i > child.length; i++) {
parent.removeChild(child[i]);
};
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form1" style="margin-left: 40%; margin-top: 100px;">
<input type="text" id="one"><br><br><br>
<input type="text" id="two"><br>
<p id ="demo"> </p>
</form>
<button style="margin-left: 40%;" type="button" value="ADD" id="addButton" onclick="addFunction()">ADD</button>
<button style="margin-left:50px;" type="button" value="REMOVE" id="removeButton" onclick="removeFunction()">REMOVE</button>
</body>
</html>
for (var i = 0; i < child.length; i++) {
parent.removeChild(child[i]);
};
You have got wrong condition in your for loop. Your i is always 0 at start, and is lesser then length of array with node elements, so loop just can't start.
P.s. and you don't need var i before it
Your for-Loop is wrong:
for (var i = 0; i > child.length; i++) {
parent.removeChild(child[i]);
};
You need to change ">" to "<"
Replace your > condition in the for loop with <. You want the for loop to be executed until it reach child.length.
Related
I'm trying to create a JavaScript to modify the number in my input field.
Example:
<input value="0">
And then a simple button or div with a JavasSript click function.
<button>Add +10</button>
After clicking on the button:
<input value="10">
Does someone have a place I can read and learn to create this, or any tips to get me started. I know very little JavaScript, but I wish to learn.
Try this or fiddleLink.
ParseInt helps in converting the string value to numbers and add them instead of concatenating. Let me know if you still have some trouble.
var tag1Elem = document.getElementById("tag1");
// The callback function to increse the value.
function clickFN() {
tag1Elem.value = parseInt(tag1Elem.value, 10) + 10;
}
// Reset the value back to 0
function resetFN() {
tag1Elem.value = 0;
}
// Callbacks can be attached dynamically using addEventListener
document.getElementById("btn").addEventListener("click", clickFN);
document.getElementById("reset").addEventListener("click", resetFN);
#wrapper {
margin: 20px;
}
<p>This is a basic tag input:
<input id="tag1" value="0" />
<button type="button" id="btn">Add +10</button>
<button type="button" id="reset">Reset</button>
</p>
You can try this
<input value="0" id="id">
give a id to input field
on button click call a function
<button onclick="myFunction()">Add +10</button>
<script>
function myFunction() {
document.getElementById("id").value = parseInt(document.getElementById("id").value) +10;
}
</script>
You can use a click counter like this
and edit it replacing += 1 with += 10.
Here my code,
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.addEventListener("click", function()
{
clicks += 10;
input.value = clicks;
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Script</title>
</head>
<body>
<input id="valor" value="0">
<button id="buttonvalue">10</button>
</body>
</html>
Im trying to create new input tags based on the number the user enters. My code will create the correct amount of tags, but they get removed almost immediately. Why?
<form>
<input type='text' id='input' />
<button>Submit</button>
</form>
<div id="box">
</div>
<script>
$(document).ready(function() {
$('button').click(function() {
var x = $('#input').val();
for(var i=0 ; i < x; i++) {
$('<input type="text" /><br>').prependTo('#box');
};
});
});
</script>
call preventDefault on the event to stop the button action from firing
$('button').click(function(e) {
e.preventDefault();
var x = $('#input').val();
for(var i=0 ; i < x; i++) {
$('<input type="text" /><br>').prependTo('#box');
};
});
FIDDLE
Change your existing button to an input with an id and use the id in the JS. Your problem is the form is being submitted when you click button.
http://jsfiddle.net/Delorian/65gLvfdx/
<input type="button" id="update" value="Submit" />
The fieldset in now cloning without retaining data from the previous fieldset as I intended. Thank you RobG and ATOzTOA for all your help.
The only problem I'm having now is the calendar is nonfunctional in the cloned fieldsets.
I have looked through several threads where people have had the same problem as me and I apologize for creating another thread on the subject.
Script for calendar dropdown.
<!-- calendar dropdown -->
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
Script to clone the fieldset.
<!-- clone fieldset -->
<script>
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder").appendChild(oClone);
var inputs = oClone.getElementsByTagName('input');
for (var i=0, iLen=inputs.length;
i<iLen; i++) {
inputs[i].value = '';
}
}
</script>
Fieldset to be cloned.
<div id="placeholder">
<!-- template -->
<div id="template">
<!-- event fieldset -->
<fieldset>
<label class="field-first" required>Event: *<input type="text" name="event" value="" /></label>
<label class="field-first" required>Date: *<input type="text" id="datepicker" name="date" value="" /></label>
<label class="field-first" required>Net Request Amount: *<input type="text" name="request" value="" /></label>
<div class="description"><p>Please type a <strong><em>DETAILED</em></strong> description of the item/event/activity:<br /></p></div>
<textarea name="describe" cols="60" rows="10" required></textarea>
<!-- event fieldset -->
</fieldset>
<!-- template -->
</div>
<!-- placeholder -->
</div>
<!-- buttons -->
<button class="right-button" type="submit" name="submit" value="Submit">Submit</button>
<button class="left-button" "btn" type="button" name="Submit" onclick="Add();">Add New Event</button>
Presumably you are adding content to the labels. You can use getElementsByTagName to get the labels from the clone, then set their innerHTML to '' (empty string) to remove any child nodes (or loop over the child nodes and remove them, but setting the innerHTML property is simpler). While looping over the labels, you can modify any other properties that might need it.
If you just want to clear the value of the input elements, same strategy only use getElementsByTagName('input') and set their value property to `` (empty string).
Note that you have three input elements with a name of "first_name". It doesn't seem like a good idea to do that when none of them seems to be a first name. Use a name that represents the data they hold or the purpose to which it will be put. It also doesn't seem to be necessary to have one with an ID of "datepicker". Either remove the ID, or if you need it (unlikley), modify the value so it's unique to each cloned fragment.
Edit
To use getElementsByTagName to set the input values to "":
var inputs = oClone.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
inputs[i].value = '';
}
You will have to traverse through each element in the frameset and set text() to "".
var div = document.getElementById('template'):
var labels = div.getElementsByTagName('label');
for (var i = 0; i < divs.length; i += 1) {
code = labels[i].innerHTML;
// As there is a input element inside the label, we have to modify the HTML code
codeArray = code.split('<');
codeArray[0] = '';
code = codeArray.join('<');
labels[i] = code;
}
Here's what I want to do. Hopefully it's not too hard.
I need to create a table with a div inside each td which is created by clicking buttons... for example
Please select the number of rows in the table
Please select the number of columns in the table..
Result:
So if you clicked on 4 and 4 it would create a table 4 X 4. If you clicked 3 X 1, you would create a table 3 X 1, etc...
Any help would be greatly appreciated!!
Here's a jfiddle of something I'm trying to get working. I'm still looking over all your comments!
http://jsfiddle.net/irocmon/7WD8v/
I know I need to add in the Javascript how to get the element by id.
I would use 2 forms, 1 for the top row of numbers and one for the second row of numbers, where each number is a predefined value of the user input.
Assign the submit button to each of the numbers using javascript for each form and from there grab the results with javascript and perform the code/script that is required to complete the task in mind.
I would recommend using jquery for this.
Have fun...
you should be able to achieve this with some pretty simple if statements or a switch
if you have 2 variables rows & columns
//loop for number of rows
for "x" number of rows{
document.write("<tr>");
if(columns > 0)
{
switch statement to output column
1: document.write("<td></td>");
2: document.write("<td></td><td></td>");
}
document.write("</tr>");
}
the syntax is very very psuedo here, this code wont work but it might get you started, what are you actually wanting to do with the table once you have it?
Using javascript, have 2 local variables: width and height. Within each DIV, have an onclick function that assigns that value to the proper variable, then checks to see if both variables have been assigned (this way they can click on either height or width first). If both are, use these variables within a for loop to generate HTML code within javascript:
var HTML = '<table>';
for(var i = 0; i < height; i++)
{ HTML += '<tr>';
for(var j = 0; j < width; j++)
{ HTML += '<td>...</td>';}
HTML += '</tr>';}
document.getElementById('where_you_want_the_table').innerHTML = HTML;
This is tested and work of note it doesn't handle if they keep trying to build the tables over and over it will keep adding cols and rows but I will let you handle that. :)
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
var Rows = 0;
var ColString = "";
var TableBuilder;
$(document).ready(function () {
$("#Rows input").click(function () { Rows = $(this).val(); });
$("#Cols input").click(buildCols);
$("#Submit").click(CreateTable);
});
function buildCols() {
for (i = 0; i < $(this).val(); i++) {
ColString = ColString + "<td></td>";
}
return ColString;
}
function CreateTable() {
if (Rows == 0 || ColString == "") {
$("#PleaseSelect").removeClass("displayNone");
}
else {
for (i = 0; i < Rows; i++) {
TableBuilder = TableBuilder + "<tr>" + ColString + "</tr>";
}
$("#table tbody").html(TableBuilder);
}
}
</script>
<style type="text/css">
.displayNone { display: none; }
</style>
</head>
<body>
<table id="table" border="1">
<tbody>
</tbody>
</table>
<br><br>
How many Rows?
<div id="Rows">
<input type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
</div>
<br />
How Many Columns?
<div id="Cols">
<input type="button" value="1" >
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
</div>
<br />
<div id="PleaseSelect" class="displayNone">Please select both a column number and a row number.</div>
<input type="button" id="Submit" value="Build Table" />
</body>
</html>
I have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('q1_') == 0) {
eles.push(inputs[i]);
}
}
HTML DOM querySelectorAll() method seems apt here.
W3School Link given here
Syntax (As given in W3School)
document.querySelectorAll(CSS selectors)
So the answer.
document.querySelectorAll("[name^=q1_]")
Fiddle
Edit:
Considering FLX's suggestion adding link to MDN here
You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>
<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x = 0 ; x < inputs.length ; x++){
myname = inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert(myname);
// do more stuff here
}
}
</script>
</body>
</html>
Demo
Using pure java-script, here is a working code example
<input type="checkbox" name="fruit1" checked/>
<input type="checkbox" name="fruit2" checked />
<input type="checkbox" name="fruit3" checked />
<input type="checkbox" name="other1" checked />
<input type="checkbox" name="other2" checked />
<br>
<input type="button" name="check" value="count checked checkboxes name starts with fruit*" onClick="checkboxes();" />
<script>
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true &&
inputElems[i].name.indexOf('fruit') == 0)
{
count++;
}
}
alert(count);
}
</script>
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.