What's happening is this:
- User hits button to add input field
- When that input field changes to have a value > 0, a function is fired that adds another input field
The code works fine as below and in Fiddle: https://jsfiddle.net/9nf6r3xf/1/
$("#add").click(function(e) {
e.preventDefault();
$(".content").append(
'<input class="input" type="number" min="0" />'
)
})
$(document).on("change", ".input", function() {
if ($(this).val() > 0) {
$(".add-content").append(
'<input class="input" type="text" value="test" />'
)
}
})
The additional complexity however, is I realized in SOME situations, the user will add an input field ALREADY containing a value. In that case, I STILL want the change
function to run, and the second input field to be added. In other words, I want the change
function to run if the click
function appends like this:
$(".content").append(
'<input class="input" type="number" min="0" value="3"/>'
)
I've read these answers (jQuery on change and on load solution, How to get option value on change AND on page load?), which suggest to trigger a change event immediately on my change function, like this:
$(".input").change(function(){
if ($(this).val() > 0) {
$(".add-content").append(
'<input class="input" type="text" value="test" />'
)
}
}).change()
However, that solution will not work for me, because since .input
is itself added by a JS button click event, I need to add my listener to the document, hence $(document).on("change", ".input")
instead of $(".input").change()
FINAL WORKING ANSWER FIDDLE: https://jsfiddle.net/9nf6r3xf/7/
took the selected answer and made a modification to build some flexibility in because I will ultimately be using this on more than one field