1

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

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

thanks that was almost what I wanted but I can handle the rest :) if you celebrate, Merry Christmas :)
How do you deal with model validation rules?
Example above just injects pure HTML element inside of ActiveForm. However, Active form has also handles validation rules and error messages. How to add those - means how to add dynamically field into ActiveForm so validation rules would apply?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.