I am trying to make dynamic adding for input elements using JQuery, so far I’ve done this in the code below, my problem is that when trying the checkbox
and date
it does not work, but for radio
there is no problem.
I’m a beginner in JS and JQuery so every search result did not help me with this matter, any help will be appreciated
$(document).ready(function() { var max_fields = 5; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var type__ = $("#q_types :selected").val(); var x = 1; $(add_button).click(function(e) { e.preventDefault(); if (x < max_fields) { x++; $(wrapper).append('<div><input type="' + type__ + '" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box } else { alert('You Reached the limits') } }); $(wrapper).on("click", ".delete", function(e) { e.preventDefault(); $(this).parent('div').remove(); x--; }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <label for="q_types">Choose the question type:</label> <div class="container1"> <select name="q_types" id="q_types" class="q_types"> <option value="" selected disabled hidden>Choose here</option> <option value="radio">radio</option> <option value="checkbox">checkbox</option> <option value="date">date</option> <option value="email">email</option> </select><br> <button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button> <div><input type="text" name="mytext[]"></div> </div>
Advertisement
Answer
The input time has to be updated everytime it changed so you had to add an onchange eventlistener on this selection.
$('#q_types').on('change', function() { type__ = this.value; });
Here the whole code for testing:
$(document).ready(function() { var max_fields = 5; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var type__ = $("#q_types :selected").val(); var x = 1; $('#q_types').on('change', function() { type__ = this.value; }); $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; $(wrapper).append('<div><input type="'+type__+'" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box } else { alert('You Reached the limits') } }); $(wrapper).on("click",".delete", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <label for="q_types">Choose the question type:</label> <div class="container1"> <select name="q_types" id="q_types" class="q_types"> <option value="" selected disabled hidden>Choose here</option> <option value="radio">radio</option> <option value="checkbox">checkbox</option> <option value="date">date</option> <option value="email">email</option> </select><br> <button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button> <div><input type="text" name="mytext[]"></div> </div>