1
populate_form($array_data)
{
   //Format: $array_data['css_selector'] = "value";

    $html = "<script>\n$(document).ready(function(){\n";

    foreach($array_data as $key => $val)
    {
        $html .= "$('$key').val('$val');\n";
    }

    $html .= "});\n</script>";

    return $html;
}

I just coded this function but havent used it yet. I wonder if this is approach for populating form with data is a good idea.

1
  • why not populate the markup and avoid the extra step of having Jquery do it? Commented Jan 17, 2012 at 4:29

2 Answers 2

3

I wouldn't do it this way.

If you want to populate a form, populate it. Don't overkill and make something else which populates it.

I mean, you already control the output of the HTML, why not just do it directly and not drag jQuery into this?

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

3 Comments

Because I have form html file that serves for both inserting and editing data. And with this jquery trick, I can populate the form without having to create another file for editing data. For example: <?php if($form_edit){ populate_form($data); } ?>
What do you mean by that? You shouldn't need to do that. If you are printing raw HTML, that's something you should fix. I always use a XML parser to create my forms (if they are large). Post your other code.
Can you show me an example of that XML parser that creates your forms?
1

I think you can assign values from PHP to JavaScript/jQuery in following way:

populate_form($array_data)
{
   //Format: $array_data['css_selector'] = "value";

    foreach($array_data as $key => $val)
    {
    ?>    
        <script language="javascript">
        $('<?php echo $key ?>').val('<?php echo $val ?>');
        </script>
    <?php
    }

    return $html;
}

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.