0

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?

1
  • What is happening when you click the button? Commented Dec 24, 2010 at 19:26

2 Answers 2

1

You need to wrap your code in

$('document').ready(function(){
    // Put your ``var id = `` code in here.
});

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The quick answer to your question is, you have to call it like $("#divTxt") not $(".divTxt") which means class=divTxt and you want id=divTxt

Try not to mix jQuery with raw dhtml. You can access form elements in jQuery using $("#id").val() and set it using $("#id").val(newValue)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.