如何在Yii2中使用js / jQuery向activeform添加字段? [英] How to add fields to activeform with js/jQuery in Yii2?

查看:428
本文介绍了如何在Yii2中使用js / jQuery向activeform添加字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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

但是使用Yii2我不知道如何实现这一点,我是yii2和框架的新手。

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

谢谢提前。 :)

推荐答案

你可以这样做:

写以下代码进入您的视图:

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"]))
    . '\');'
    . '})');

请注意,您需要:

use yii\helpers\Html;

位于页面顶部。否则,你应该写 yii\helpers\Html :: 而不是 Html ::

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

这篇关于如何在Yii2中使用js / jQuery向activeform添加字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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