Add X meta box inputs based on form at top of meta box, how to do it right?

I am setting up a meta box that controls the number of ingredients for a recipe. As each recipe will have a different number of ingredients I decided to use a simple text input and button to set the number of ingredients and have jQuery dynamically add the inputs for that “X” number.

I know I need to use jQuery form but am unsure of how to return the html into the meta box correctly. I have a response div set up but not sure how to handle the html.

Read More

Can i pass the value from the text input into a php function that uses a for loop to print out all the inputs for the ingredients? Or do I need to print all of the html with jQuery?

Hope that makes sense.

Thanks!

my jQuery that works:

    jQuery('#add-ingredients').click(function(event){
        event.preventDefault();                                        
        var num = jQuery('input:text[name=_num_ingredients]').val();

        var sections = '';
        for(var i=1;i<=num;i++){

            section = '<div id="ingredient-' + i + '" class="ingredient-input">n';
            section += '<div class="ingredient-amount alignleft">n';
                section += '<label for="_ingredient_amount_' + i + '">Amount: </label>n';
                section += '<input type="text" name="_ingredient_amount_' + i + '" />&nbsp;n';
            section += '</div>n';
            section += '<div class="ingredient-measurement alignleft">n';
                section += '<label for="_ingredient_measurement_' + i + '">Measurement: </label>n';
                section += '<input type="text" name="_ingredient_measurement_' + i + '" />&nbsp;n';
            section += '</div>n';
            section += '<div class="ingredient-name alignleft">n';
                section += '<label for="_ingredient_name_' + i + '">Ingredient: </label>n';
                section += '<input type="text" name="_ingredient_name_' + i + '" />&nbsp;n';
            section += '</div>n';
            section += '<div class="clear"></div>n';
            section += '</div>n';

            sections += section;
        }//end for

        //add the new input sections
        jQuery('#ingredients').html(sections);
        //show the ingredients inputs
        jQuery('#ingredients').show('slow');

        return false;       
    });

But now I can’t figure out how to save the meta data correctly.

Here’s my for loop:

    //loop through all ingredients and update them accordingly
    for($i=1; $i<=$num; $i++):

        $amt = '_ingredient_amount_'.$i;
        $meas = '_ingredient_measurement_'.$i;
        $name = '_ingredient_name_'.$i;

        //set ingredients array for each iteration
        $post_meta['_ingredient_amount_'.$i] = $_POST['_ingredient_amount_'.$i];
        $post_meta["{$meas}"] = $_POST["{$meas}"];
        $post_meta[$name] = $_POST[$name];

        //update meta data
        foreach( $post_meta as $key => $value ):
            if( $value ):
                if( get_post_meta( $post_id, $key, FALSE) ): // If the custom field already has a value
                    update_post_meta( $post_id, $key, $value );        
                else: // If the custom field doesn't have a value
                    add_post_meta( $post_id, $key, $value );
                endif;
            else:
                //delete_post_meta( $post_id, $key ); // Delete if blank
            endif;  
        endforeach; 

    endfor;

I know I am missing something in the syntax to get the $_POST values. Any ideas?

EDIT——————————-

I was failing to pass the $post variable into my function – silly me. Now it all works correctly. Thanks for all your help!

Related posts

Leave a Reply

1 comment

  1. You could clone an existing field with jQuery and append it to the form. You’ll also have to handle cases where the number of ingredients is fewer than the number of fields, and you’ll have to use jQuery’s remove. Here’s a simple example of cloning a field:

    $('#quantity-form').submit(function(){
        // get # of fields that already exist
        // (change this to match whatever type of fields you have)
        var count = $('#metabox-form input[type="text"]').length;
        // you'll want to check if count is > or < requested quantity and possibly remove,
        // or clone (in a loop to add multiple fields):
        $('#metabox-form input[type="text"]:last')
            .clone(false)
            .attr({
                name:'field-' + (count + 1),
                id:'field-' + (count + 1)
            })
            .appendTo('#metabox-form');
    
        return false;                   
    });