将表单模板与Jquery相乘 [英] Multiplying Form Template with Jquery

查看:72
本文介绍了将表单模板与Jquery相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单模板:

<form>
  <select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  </select>
  <div id="template">
    <input type="text" name="info[name][]" />
    <input type="text" name="info[address][]" />
    <input type="text" name="info[gender][]" />
  </div>
</form>

我想在选择标记的值更改(例如,从1变为2)时,将ID为TEMPLATE的div乘以2,变成这样.

I want when the select tag's value is change (ex : from 1 into 2), the div with id TEMPLATE multiply into 2, Become like this.

<form>
  <select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  </select>
  <div id="template">
    <input type="text" name="info[name][]" />
    <input type="text" name="info[address][]" />
    <input type="text" name="info[gender][]" />
  </div>
  <div id="template">
    <input type="text" name="info[name][]" />
    <input type="text" name="info[address][]" />
    <input type="text" name="info[gender][]" />
  </div>
</form>

模板数量必须与选择值匹配,如果选择值为1,则只有1个模板div,如果为3,则将有3个模板div.

The number of template have to match with the select value, if the select value is 1, then there will only 1 template div, if 3, then there will be 3 template div.

有人知道如何使用jquery吗?

Anybody know how to do it with jquery ?

推荐答案

您可以将更改处理程序用于选择,如克隆

You can use a change handler for the select with cloning like

jQuery(function($) {
  var $template = $('#template').addClass('template');
  $('select').change(function() {
    //required number of copies
    var count = +this.value;
    var $templates = $('.template');
    //if there are more number copies remove them
    if ($templates.length > count) {
      $templates.slice(count).remove();
    } else {
      //add new copies if required
      for (var i = $templates.length; i < count; i++) {
        var $clone = $template.clone().insertAfter($templates.last());
        $clone.find('input').val('');
      }

    }
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  </select>
  <div id="template">
    <input type="text" name="info[name][]" />
    <input type="text" name="info[address][]" />
    <input type="text" name="info[gender][]" />
  </div>
</form>

这篇关于将表单模板与Jquery相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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