创建一个动态的html表单 [英] Creating a dynamic html form

查看:157
本文介绍了创建一个动态的html表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个动态变化的表单。



我有一个用于创建项目的表单(具有以下字段:project_name,project_description ...),项目可以有任何数量(大于或等于0)的类别。



我想要的是显示一个按钮,给用户添加另一个类别字段的选项。此外,我还希望类别字段的选项被用户删除(如果他改变主意或犯了错误)。最好的方法是什么?我想要一个Ajax类型的解决方案。



我的解决方案到目前为止是在最后一个类别之下留下一个空的div,并在按钮上单击将另一个字段加载到另一个div,该div将被用于下一个div不要对这个解决方案感到满意,因为我现在要计算我有多少个字段,并给每个div自己的id,这使事情更加复杂化。



是否有更简单的解决方案?

解决方案

如果您正在尝试使用按钮动态添加字段,您可以通过执行以下操作轻松实现:



HTML:

 < form> 
< p>
< label>名称:< / label> < input type =text>
< label>年龄:< / label> < input type =text>
< span class =remove>删除< / span>
< / p>
< p>
< span class =add>添加字段< / span>
< / p>
< / form>

JS:



click(function(){
$(form> p:first-child)。clone(true).insertBefore (form> p:last-child);
return false;
});

$(。remove)。click(function(){
$(this).parent()。remove();
});

演示: http://jsfiddle.net/UeSsu/1/


I would like to create a form that changes dynamically.

I have a form for creating a project (with fields such as: project_name, project_description...) and the project can have any amount (bigger or equal to 0) of categories.

What i want is to display a button which would give the user the option to add another category field. In addition I would also like the option for category fields to be "deleteable" by the user (if he changes his mind or made a mistake). What would be the best way to do so. I would like an Ajax type solution.

My solution so far is to leave an empty div beneath the last category and onclick of the button to load another field into that div with yet another div which will be used for the next div. Not to happy with this solution since i now have to count how many fields I have and give each div it's own id which complicates the matter even more.

Is there a more simple solution to this?

解决方案

If you are trying to add fields dynamically with a button, you can easily do so by doing something like the following:

HTML:

<form>
    <p>
        <label>Name:</label> <input type="text">
        <label>Age:</label> <input type="text">
        <span class="remove">Remove</span>
    </p>
    <p>
        <span class="add">Add fields</span>
    </p>
</form>

JS:

$(".add").click(function() {
    $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
    return false;
});

$(".remove").click(function() {
    $(this).parent().remove();
});

Demo: http://jsfiddle.net/UeSsu/1/

这篇关于创建一个动态的html表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆