Abdullah_Iftikhar's avatar

How to add input field using JS ?

I am 2 input fields.

i want to add 2 more but using js

like i add click button on view when i click on view the 2 more add and when i click on delete icon the remove both.

it's all using js.

Thanks.

0 likes
5 replies
rodrigo.pedra's avatar

Are you using any JS framework (Vue, React, Angular, ...) or it is a plain JavaScript (maybe JQuery) implementation?

Tray2's avatar

Something like

var form = document.querySelector('#form');
form.innerHTML += form.innerHTML + '<input type="text">';

Should work

1 like
rodrigo.pedra's avatar
Level 56

Give this a try:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>jQuery Dynamic Form</title>

    <script crossorigin="anonymous" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<h1>My Form</h1>
<form id="my-form" action="/your-action-here">
    <div class="fields"></div>

    <p>
        <button type="button" class="add-fields">
            Add fields
        </button>

        <button type="submit">
            Send form
        </button>
    </p>
</form>

<!--
    text/x-templates is a fake type  just to tell
   the browser to ignore this script block
-->
<script type="text/x-templates" id="fields-templates">
    <p class="input-fields">
        <input name="title[]" placeholder="title">
        <input name="description[]" placeholder="description">
        <button type="button" class="remove-fields">
            Remove these fields
        </button>
    </p>
</script>

<script>
$(function () {
    var FIELDS_TEMPLATE = $('#fields-templates').text();
    var $form = $('#my-form');
    var $fields = $form.find('.fields');

    $form.on('click', '.add-fields', function () {
        $fields.prepend($(FIELDS_TEMPLATE));
    });

    $form.on('click', '.remove-fields', function (event) {
        $(event.target).closest('.input-fields').remove();
    });
});
</script>
</body>
</html>

The trick here is to use a delegate on the event listener.

2 likes

Please or to participate in this conversation.