james james - 6 months ago 11
Javascript Question

JS trigger value check on change AND on load for an element added to page after document load

What's happening is this:


  1. User hits button to add input field

  2. 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

Answer

I think this should be as simple as triggering a click event on the dynamically added input right after you append it.

So what you have now is this in your click event handler

$(".content").append( '<input class="input" type="number" min="0" />' )

Add this line after it

$(".content > .input:last").trigger("change")

So the idea is to find the last element with class input By using the :last selector (as the element added using append will be in last) and triggering a click event on it.

Comments