Mike Ross
Mike Ross

Reputation: 2972

Create input field dynamically using javascript

I am using yii2 framkework and on based of input provided by user I want to create input fields. Using some online documents like this I tried to do it but the problem is my button click event is not picking up the jquery

Here is a jsfiddle for it. Not able to replicate my problem exactly but what i want is if user enters 3 in the input field than 3 field should be generated on button click.

Here is my view code

<div class="event-form">

<?php $form = ActiveForm::begin(['id'=>'form-event']); ?>  

<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

<div class="row">
    <div class="col-lg-4 col-sm-4 col-xs-4">
        <?= $form->field($model, 'start_date')->widget(
            DatePicker::className(), [
            'name' => 'start_date',
            'options' => ['placeholder' => 'Select Event start date ...'],
            'convertFormat' => true,
            'pluginOptions' => [
                'orientation' => 'bottom left',
                'format' => 'MM/dd/yyyy',
                'startDate' => date('dd-MM-yyyy'),
                'autoclose' => true,
                'todayHighlight' => true
            ]
        ])
        ?>
    </div>
    <div class="col-lg-4 col-sm-4 col-xs-4">
        <?= $form->field($model, 'end_date')->widget(
            DatePicker::className(), [
            'name' => 'end_date',
            'options' => ['placeholder' => 'Select Event end date...'],
            'convertFormat' => true,
            'pluginOptions' => [
                'orientation' => 'bottom left',
                'format' => 'MM/dd/yyyy',
                'startDate' => date('dd-MM-yyyy'),
                'autoclose' => true,
                'todayHighlight' => true
            ]
        ])
        ?>
    </div>
    <div class="col-lg-4 col-sm-4 col-xs-4">
        <button type="button" id="setdates" class="btn btn-default btn-set-dates">Set Dates</button>
    </div>
</div>

<p></p>

<p></p>
<div class="form-group hide" id="optionTemplate">
    <div class="col-xs-offset-3 col-xs-5">
        <input class="form-control" type="text" name="option[]" />
    </div>
</div>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-danger' : 'btn btn-primary']) ?>
</div>

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

Here is the javascript i am using

$('#setdates').click(function() {
startDate = new Date(document.getElementById('event-start_date').value);
endDate = new Date(document.getElementById('event-end_date').value);
var dates = [],
    currentDate = startDate,
    addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    };
while (currentDate <= endDate) {
    dates.push(currentDate);
    currentDate = addDays.call(currentDate, 1);
  }
});

$(document).ready(function() {
  var MAX_OPTIONS = 5;
  $('#form-event')

    .on('click', '.setdates', function() {
        var $template = $('#optionTemplate'),
            $clone    = $template
                .clone()
                .removeClass('hide')
                .removeAttr('id')
                .insertBefore($template),
            $option   = $clone.find('[name="option[]"]');

    })
    // Called after adding new field
    .on('added.field.fv', function(e, data) {
        if (data.field === 'option[]') {
            if ($('#event-form').find(':visible[name="option[]"]').length >= MAX_OPTIONS) {
            }
        }
    })

});

So I have to generate input fields for the dates times.

Upvotes: 1

Views: 276

Answers (3)

Suyog
Suyog

Reputation: 2482

I am posting sample code which may help you. You might have to modify it according to your need to use.

The HTML

<input type="text" id="numPpl" name="numPpl">
<br><br>
<div id="demo">

</div>

The JQuery

<script>
    $('#numPpl').blur(function()
    {
        for(i=1; i<=$('#numPpl').val(); i++)
        {
            $('#demo').append('<input type="text"><br><input type="text"><br><br>');
        }
    });
</script>

Fiddle

Upvotes: 1

Santosh
Santosh

Reputation: 381

might be you document is not ready when your js file will laod. replace "#form-event" with "document" make sure ".setdates" this class you will not use for other dom if you use this class this click will occur for every dom which has ".setdates" class and #setdates

$(document).on('click','#setdates',(function() {});


 $(document)
    .on('click', '.setdates', function() {
        var $template = $('#optionTemplate'),
            $clone    = $template
                .clone()
                .removeClass('hide')
                .removeAttr('id')
                .insertBefore($template),
            $option   = $clone.find('[name="option[]"]');

    })

Upvotes: 1

Waqas Shahid
Waqas Shahid

Reputation: 1060

HTML:

<a id="add">Add More</a>

JavaScript:

var i = 1;
$("#add").click(function(){
                var appendFields = '<tr>';
                appendFields += '<td><select id="dropdown_'+i+'" name="dropdown_name[]"><option value="1">One</option></select></td>';
                appendFields += '<td><a style="color: red; cursor: pointer;" class="remCF">Remove</a></td>';
                appendFields += '</tr>';
                $("#table_id").append(appendFields);
                i++;
            });
            $("#table_id").on('click','.remCF',function(){
                $(this).parent().parent().remove();
            });

        });

Upvotes: 1

Related Questions