如何在 Yii2 中使用 js/jQuery 将字段添加到 activeform


How to add fields to activeform with js/jQuery in Yii2?

嗨,我有一个用户表单,我想添加一个按钮,以便用户可以动态添加更多联系人。

<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>

如果我不使用框架,我会做这样的事情 http://jsfiddle.net/3t06fL3f/(这是基于非常古老的代码):)

但是使用 Yii2 我不确定如何做到这一点,我是 yii2 和一般框架的新手。

提前谢谢你。:)

你可以像下面这样做:

将以下代码写入视图中:

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

请注意,您需要具备:

use yii'helpers'Html;

在页面顶部。否则,您应该编写yii'helpers'Html::而不是Html::