How to add fields to activeform with js/jQuery in

2020-03-30 04:45发布

问题:

Hi I have a user form and I want to add a button so that the user can add more contacts dynamically.

<form id="user-form">
<div id='dynamicInput'>
    <div><input type='text' placeholder='name'></div>
    <div><input type='text' placeholder='email'></div>
</div>
<input type='button' id='btnadd' value="add contact">
<input type='submit'>
</form>

If I wasn't using the Framework I would do something like this http://jsfiddle.net/3t06fL3f/ (this is based on very old code) :)

But using Yii2 I'm not sure how to accomplish this, I'm new to yii2 and frameworks in general.

Thank you in advance. :)

回答1:

You can do it like below:

Write the following code into your view:

 $this->registerJs('$("#btnadd").on("click",function(){'
    . '$("#dynamicInput").append(\''
    . Html::tag("div",  Html::textInput("name","",['placeholder'=>"name"]))
    . Html::tag("div",  Html::textInput("email","",['placeholder'=>"email"]))
    . '\');'
    . '})');

Please note that you need to have:

use yii\helpers\Html;

at top of your page. Otherwise, you should write yii\helpers\Html:: instead of Html::