Cloning and renaming form elements with jQuery

后端 未结 3 1423
失恋的感觉
失恋的感觉 2021-02-04 03:51

I am looking for an effective way to either clone/rename or re-create address fields to offer ability to submit multiple addresses on the same page. So with form example like th

3条回答
  •  礼貌的吻别
    2021-02-04 04:39

    It's much less verbose if you write it sanely :-) I would likely just use clone and append. However, you'll get duplicate names. This isn't a big deal if your back-end can correctly handle "address[].street", but it may not and in such a case you'd need to cleanup after the clone. Thus I'd recommend "hiding it in a tidy builder function".

    function createAddress (index) {
      return jQuery(replace('\
        
    \ \ \ \ \
    \ ', {i: index})) }

    Where replace is some tidy function which understands a simple interpolation mapping. I prefer to "keep markup in something that looks like markup".

    Worrying about performance here is likely not warranted.

提交回复
热议问题