0

my jquery code doesn't work on my dynamic field in this form that adds after the page loaded:

i add this api for jquery:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

my html form:

<form method="post" class="row g-3 my-4 px-3 needs-validation" novalidate>
    {% csrf_token %}

    <!-- Job -->
    <div class="col-lg-8 job_field">
        <label for="job" class="form-label fw-bold">Job</label>
        <div class="input-group">
            <input type="text" class="rounded-3 form-control" id="job"
                   placeholder="example: Dentist" value="Dentist" name="job"
                   required>
            <span class="add_job cursor input-group-text rounded-3 bg-Goldenrod mx-3 bg-gradient">+ Add Another Job</span>
        </div>
    </div>
    <!-- Job -->


    <!-- Save Change Button-->
    <div class="col-12 mt-5">
        <button class=" col-12 py-2 col-md-3 btn btn-Goldenrod bg-gradient fw-bold" type="submit">
            Save Change
        </button>
    </div>
    <!-- Save Change Button-->


</form>

my jquery code:

<script>


    $('.add_job').click(function () {


        $('.job_field').append('<div class=" another_job input-group mt-3"> <input type="text" class="rounded-3 form-control" id="job" placeholder="example: Dentist" name="job" required><span id = "remove" class="cursor input-group-text rounded-3 bg-danger mx-3 bg-gradient">- Remove</span></div>');

    });

    $('#remove').click(function () {

        $(this).parent.addClass('d-none')

    });
</script>

my "+add Another Job" button works correctly .. but my "-Remove" button that adds after the load page doesn't work.

  • 1
    There are two things: 1) As you are using Id, It will only on one element only, You need to use Call or any other way for it. Also If you are deleting after add new html in document then you need to again initialize Click event for delete – KHIMAJI VALUKIYA Dec 18 '21 at 12:13
  • Change `$('#remove').click(function () {` to `$(document).on("click", ".remove', function () {` and give it a class `remove` instead of `id` as noted in other comments. – freedomn-m Dec 18 '21 at 12:31

1 Answers1

2

You can not use Id multiple time in the page, jQuery will understand only first Id. You need to add class for remove/hide row. Also You need to Initialize Click event of remove after all new adds:

See Example code:

    <script>
        $('.add_job').click(function () {
            $('.job_field').append('<div class=" another_job input-group mt-3"> <input type="text" class="rounded-3 form-control" id="job" placeholder="example: Dentist" name="job" required><span id="remove" class="cursor input-group-text rounded-3 bg-danger mx-3 bg-gradient remove_record">- Remove</span></div>');
            $('.remove_record').click(function () {
                $(this).parent("div").addClass('d-none')
            });

        });
    </script>
KHIMAJI VALUKIYA
  • 626
  • 1
  • 5
  • 16