views:

66

answers:

2

I'm using cake & have a web form for entering URLs to go into my db. There will be one input space (url1) and below that a link that says "add another URL" which, when clicked, generates a new form (url2) and reuses the "add another URL". So it would be like:

echo $form->input('name');
echo $form->input('id');
echo $form->input('url1');
echo $form->input('weight1');
echo '<a href="XXX">add another URL</a>';

and then, if XXX is clicked it would be like this:

echo $form->input('name');
echo $form->input('id');
echo $form->input('url1');
echo $form->input('weight1');
echo $form->input('url2');
echo $form->input('weight2');
echo '<a href="XXX">add another URL</a>';

Is there a jquery script I can use to do this or does cake have something built in?

+2  A: 

Haven't try the code but i would do something like this:

<form>
    <div id="mainData">
        echo $form->input('name');
        echo $form->input('id');
    </div>
    <div id="urlsHolder">
        <div class="url">
            echo $form->input('urls[]');
            echo $form->input('weights[]');
        </div>
    </div>
    <a href="#" id="addUrl">add another URL</a>
</form>

<script type="text/javascript">
    $(document).ready(function() {
        $('#addUrl').click(function( event ){
            event.preventDefault();         
            $('div.url').filter(':first').clone().appendTo('#urlsHolder');          
        });
    });
</script>

When the form is submited do a foreach for $_POST['urls'] and $_POST['weights'].

There is room for improvement, It's just an inspirational example. Hope it helps.

Kindred
Thanks a lot for your answer, I will try this.
pg
I tried this but when I do, I get no response at all when clicking on the "add another url" link. Also I'm concerned that js won't be able to make the number afte URL and Weight increment, since it's calling php, which I always thought finished rendering before js even starts.
pg
I don't understand why you say that, you can use the attr method to modify an attribute on the fly. But actually you don't need to append a number to URL and Weight just make a loop to read the $_POST['urls'] and $_POST['weights'] arrays and you are done.
Kindred
A: 

Actually I think it's not necessary to do your work like this.According to your description,I think you can change the <a href="XXX">add another URL</a> to any other element such as a button,which will make a hidden div visible when clicked.Then it will be what you want.

SpawnCxy
I disagree with this solution. It's a static approach.
Kindred