The web page I'm working on has a 'main' form where the visitor enters personal data and information about a first property. If he/she has further properties to record, he/she clicks an 'add property' checkbox, which dynamically generates a new (partial) form).
I'm using #PSL's answer to the question How to use jQuery to add form elements dynamically to build a form that can be reloaded and completed multiple times on the same page. I have been able to change the input IDs and names so that they are all unique, and it all works well that far, including adding all the info to a database when submitted.
I am now trying to add (the same) default values to some of the inputs on each form. This too needs to be dynamic because each input has a different ID. My working can be seen on JSFiddle https://jsfiddle.net/ramasaig/yrpoo6v7/ (shown with the static selector, see below)
The first problem seems to lie with the jQuery selector. If I make it static as:
$('#pc2').val('PA66 6BP');
then it will work (but only when the NEXT form is created, see second problem). And of course it only applies the default value to the input with id = 'cp2'. If I try to create the ID using a variable, like:
$('#pc' + prop_no).val('PA66 6BP');
it fails without producing a console error. I've looked at the elements using 'Inspector' and the IDs are there OK, but not the values.
The second problem is that even when I use the static $selector the value doesn't appear in the 'first' form until I create the second (which makes me wonder if the first problem might be to do with the timing, but I am unsure how to check for this or what to do about it.).
So my questions are:
1. How do I select the ID dynamically ?
2. How do I get the default value to show up when the form is created.
I'd be grateful for some help here, please.