Нажмите на кнопку и добавьте новые поля ввода Yii2

Я сомневаюсь. Каждый раз, когда я нажимаю кнопку, я хочу добавить еще два поля. Но поскольку я работаю с фреймворком yii2, у меня возникают трудности с реализацией кода javascript вместе с кодом форм, которые фреймворк создает автоматически.

Моя форма создана gii

<div class = "hotel-form">


<?php $form = ActiveForm::begin(); ?>
<center>
    <?= $form->field($model, 'nome')->textInput(['maxlength' => true, 'style'=>'width:500px', 'placeholder' => "Nome do hotel"])->label(false); ?>
    <!--
    <?= $form->field($model, 'userId')->textInput(['maxlength' => true,'style'=>'width:500px',  'placeholder' => "Proprietário"])->label(false); ?>
    -->
    <?= $form->field($model, 'descricao')->textarea(['maxlength' => true, 'style'=>'width:500px; resize: none;', 'rows' => 6, 'placeholder' => "Descrição"])->label(false); ?>

    <?= $form->field($model, 'contacto')->textInput([ 'maxlength' => 9, 'style'=>'width:500px','placeholder' => "Contacto"])->label(false); ?>

    <?= $form->field($model, 'website')->textInput(['maxlength' => true, 'style'=>'width:500px', 'placeholder' => "Website"])->label(false); ?>

    <?= $form->field($model, 'cp4')->textInput(['maxlength' => 4, 'style'=>'width:500px','placeholder' => "Código-postal (4 dígitos) "])->label(false); ?>

    <?= $form->field($model, 'cp3')->textInput(['maxlength' => 3, 'style'=>'width:500px', 'placeholder' => "Código-postal (3 dígitos)"])->label(false); ?>

    <?= $form->field($model, 'regiaoId')->dropDownList(ArrayHelper::map(RegiaoHotel::find()->orderBy(['nome' => SORT_ASC])->all(), 'id', 'nome'), ['style'=>'width:500px']) ?>

    <?= $form->field($model, 'morada')->textInput(['maxlength' => true, 'style'=>'width:500px', 'placeholder' => "Morada"])->label(false); ?>

    <?= $form->field($model, 'estado')->hiddenInput(['value'=> 2])->label(false);?>

    <?= $form->field($model, 'img')->fileInput() ?>


    //There are the fields i want do add each time i click button
    <?= $form->field($comHotel, 'descricao')->textInput(['maxlength' => true, 'style'=>'width:500px', 'placeholder' => "Descricao comodidade"])->label(false);?>
    <?= $form->field($comHotel, 'preco')->textInput(['maxlength' => true, 'style'=>'width:500px', 'placeholder' => "Preço da comodidade"])->label(false);?>
    //

    <br>

    <div class = "form-group">
        <?= Html::submitButton('Registar', ['class' => 'btn btn-success']) ?>
    </div>


</center>
<?php ActiveForm::end(); ?>

И у меня есть код js, который я пытаюсь реализовать

<script>
var count = 1; // There are 4 questions already

function addQuestion()
{
    // Get the quiz form element
    var quiz = document.getElementById('quiz');

    // Good to do error checking, make sure we managed to get something
    if (quiz)
    {
        if (count)
        {
            // Create a new <p> element
            var newP = document.createElement('p');
            newP.innerHTML = 'Question ' + (count + 1);

            // Create the new text box
            var newInput = document.createElement('input');
            newInput.type = 'text';
            newInput.name = 'descricao';
            var newInput1 = document.createElement('input');
            newInput1.type = 'number';
            newInput1.name = 'preco';

            // Good practice to do error checking
            if (newInput && newInput1 && newP)
            {
                // Add the new elements to the form
                quiz.appendChild(newP);
                quiz.appendChild(newInput);
                quiz.appendChild(newInput1);
                // Increment the count
                count++;
            }

        }
        else
        {
            alert('Question limit reached');
        }
    }
}
<form id = "quiz" action = "" method = "POST">
   <input type = "button" value = "Add question" onclick = "javascript: 
   addQuestion();"/>

   <p>Question 1</p>
   <input type = "text" name = "descricao"/>
   <input type = "text" name = "preco"/>
   <p></p>
</form>

🤔 А знаете ли вы, что...
JavaScript имеет множество встроенных объектов, таких как Array, Date и Math.


1
1 043
1

Ответ:

Решено

вот ваше идеальное решение для динамического добавления или удаления полей с прекрасным примером

yii2-динамическая форма