Reputation: 19
I created an input text dynamically using JS, but what if I want to remove the input field one by one dynamically using a button by calling "removeTextField()
" from the JS?
Here is the JS:
<script type="text/javascript">
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
}
</script>
...
<input type = "button" class="button2" value = "Add Time" onclick = "addTextField()"/>
Upvotes: 0
Views: 151
Reputation: 195982
id
and this means that when adding more than one, you will end with multiple elements with the same id
?(which is invalid and prone to errors when accessing the DOM)I would use something like this
html
<input type="button" class="button2 addField" value="Add Time" />
<input type="button" class="button2 removeField" value="Remove Time" />
script
$(function(){
$('.addField').on('click', function(){
$('<input type="text">', {
name: 'i[]',
value: '',
'class': 'daters'
}).appendTo('#dispTime');
});
$('.removeField').on('click', function(){
$('#dispTime .daters').last().remove();
});
});
If you are not using jQuery then the way to remove an element
function removeTextField(){
var elements = document.getElementById('dispTime').getElementByClassName('i[]'),
last = elements[elements.length-1];
last.parentNode.removeChild(last);
}
Upvotes: 2
Reputation: 5992
you can use $.remove() for this..
refer: http://api.jquery.com/remove/
Suggestion: instead of creating elements like the one you did, create like this.
$('body').append("<input name='i[]' value='' class='daters' id='timepicker_7' />");
$('#timepicker_7').remove();
if you are creating elements on demand and want to use this element multiple times. now you have a function which can be used as many times you want, anywhere on the page
function GetTextField() {
var field = "<input name='i[]' value='' class='daters' id='timepicker_7' />";
return field;
}
var field = GetTextField();
$('body').append(field);
Upvotes: 1
Reputation: 44889
function removeTextField() {
var timepicker = document.getElementByID("timepicker_7");
timepicker.parentElement.removeChild(timepicker);
}
Upvotes: 1
Reputation: 3965
This is my idea(not tested):
Every time you add an input, just push it in a array, so you can remove it after:
<script type="text/javascript">
var inputStack = new Array();
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
inputStack.push(element);
}
// Now if you want to remove, just do this
inputStack[0].remove(); // I think it'll work for example
</script>
Upvotes: 0