I’m trying to dynamically add elements to a Cakephp form:
<?php echo $javascript->link('jquery',false); ?>
<script language="javascript" type="text/javascript">
function addFormField() {
var id = parseInt(document.getElementById("id").value);
$('.divTxt').append("<p id='row" + id + "'><label for='txt" + id + "'>Field " + id + " <input type='text' size='20' name='txt[]' id='txt" + id + "'> <a href='#' onClick='removeFormField(\"#row" + id + "\"); return false;'>Remove</a><p>");
document.getElementById("id").value = id+1;
}
</script>
<?php echo $this->Form->create('Booking'); ?>
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
<?php echo $this->Form->end('Save Post'); ?>
<p><a href="#" onClick="addFormField(); return false;">Add</a></p>
I think that my $(‘.divTxt’) call is incorrect due to a speciality of the form creation by CakePHP. Can anyone point out how this can be done correctly?
You need to wrap your code in
What’s happening is that the code above
var id = ...is running during page load before the form is even output. If you turn on output buffering in PHP, it’ll help, but that’s not the reliable fix for it. The ready function (above) is.And, you need to access the div with
#the_id, not.the_id. That’s for classes.