So I am creating a form that has a feature(s) input. It starts off with only 1 but the number may increase. By clicking on a button I will append a new text box for new feature to be written into it via Jquery.
JsFiddle: https://jsfiddle.net/kmckeow/ewnetzqx/
Issue 1:error from java script saying that I cannot use input.attr().
Issue 2:When I do get this JavaScript to work, how am I supposed to reference a variable number of elements i.e. (feature1, feature2, feature3, ...) in PHP. When I submit a form with post I usually access the information in each element via it's name. How can I do that when I am not sure how many features there will be.
HTML:
<div id="new_product">
<form action="" method="post" enctype="multipart/form-data">
<p>
<label for="feature1"> Feature(s): </label>
<input type="text" name="feature1" />
<button type="button" class="btn btn-primary" id="add_feature">Add Feature</button>
<p>
<input type="submit" value="Submit" name="submit">
</form>
</div>
JQuery:
var feature_count=1;
var feature_count_old=0;
$( "#add_feature" ).click(function() {
feature_count_old=feature_count;
feature_count+=1;
var input = document.createElement("input");
input.attr('name', 'feature' + feature_count);
input.attr('type', 'text');
$("input[name='feature'+feature_count_old]").after(input);
});
Issue 1 You did not load jQuery, so $ is not defined. Simply add the jQuery library to your snippet and you're good to go!
Issue 2 attr() is a jQuery method and not vanilla JS, so you need to do something like this:
var $input = $('input');
$input.attr('name', 'feature' + feature_count);