开发者

Help with appendTo() jquery function on form

开发者 https://www.devze.com 2023-02-19 05:50 出处:网络
I am a beginner, so keep that in mind. so what I currently have working is my form successfully adds another input to the form, however it appears out of the form div. Basically I want it to appear w

I am a beginner, so keep that in mind.

so what I currently have working is my form successfully adds another input to the form, however it appears out of the form div. Basically I want it to appear within the div and above the submit button.

how do I do this?

here is m开发者_JAVA百科ain appendTo in my javascript:

var i = $('input').size() + 1; 
$('a#add').click(function() { 
    $('<input type="text" value="user' + i + '" />').appendTo('form'); 
    i++; 
});

here is the form html as on request.

<div id="stylized" class="myform">
<form name="addstudents" method="post" action="add_students.php">
<div id="formHeader">
    <h1>Add student(s)</h1>
    <p>Please enter student's HEMIS number</p>
</div>
<label>Student: <span class="small">Enter HEMIS number</span> </label>
<input type='text' name="user_1">
<input type="submit" class="Mybutton" id="mybutton" name="submit" value='Submit Student(s)'>
<div class="spacer"></div>
</form>
<a href="#" id="add">Add</a><a href="#" id="remove">Remove</a></div>

Any help would be greatly appreciated.

thanks

NEW PROBLEM: REMOVING!

here is my current remove JS, it simply removes the submit button first :(

$('a#remove').click(function() { 
if(i > 3) { 
    $('input:last').remove(); 
    i--; 
}
});
$('a.reset').click(function() {
while(i > 2) { 
    $('input:last').remove(); 
    i--;
}
});

Thanks again


You can use this snippet to insert the input before the button:

$('form #idofsubmitbutton').before($('<input type="text" value="user' + i + '" />'))

EDIT:

I played around with jsfiddle.com after your last edit and came upp with this:

var i = $('input').size() + 1;
$('a#add').click(function() {
    $('div#stylized form input:submit').before($('<input type="text" value="user' + i + '" />'))
    i++;
});

With the example html you posted this works. When I press the add link new inputs appear before the submit button.

If you still got problems you might have elements with duplicate ids.


var i = $('input').size() + 1; 
$('a#add').click(function() { 
    $('<input type="text" value="user' + i + '" />').appendTo('div#divId'); 
    i++; 
});


This is not a "PHP form", once it's on the client, it's just HTML/CSS/Javascript. PHP is on the server.

.appendTo('form'); appends to the form TAG, not a "form div". If you have a DIV named "form" you need to use .appendTo('#form');

0

精彩评论

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