开发者

Dynamically add/remove new input to form

开发者 https://www.devze.com 2023-02-18 20:21 出处:网络
So I am a beginner and as the title says I want to be able to; on the click of a button, allow the user to add another input field to my form. I would also like to be able to remove this.

So I am a beginner and as the title says I want to be able to; on the click of a button, allow the user to add another input field to my form. I would also like to be able to remove this.

The use of the form is adding students to a student group, which I will then be storing in my database.

my form exampl开发者_Go百科e:

<form name="addstudents" id="addstudents" method="post" action="add_students.php">
<table><tr><td>Student:</td><td>
<input type='text' name="1" size='20'></td><td><input type="button" id="add" value="+">    
</td><td><input type="button" id="remove" value="-"></td>
</table></form>

However from what I have been looking at there are different suggestions such as using a clone() function or Jquery appendto().

which is the best method for doing so?

thanks


$('form').append('<input ...'); //take care of appending valid DOM elements


//Create the input element
var $el = $('<input>')//Set the attribute that you want
                      .attr('id','inputID')
                      .attr('readonly',true);
//And append it to the form
$('#addstudents').append($el);


Remember you also can remove any DOM from your form just find the appropiate jquery selector

$('form > input:last').remove(); // to remove last input

check this working sample that a made on jsfiddle.net to help you with this


I would use JavaScript, I already answered this question here. Just uses plain JavaScript to edit the HTML of the page. Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消