5

Context

I'm trying to build an answer to this WordPress question.

I'm generating dynamic checkboxes in the media upload thickbox window. And they should serve to populate a text field where the user can copy/paste its value.

The final output of the text field is the include attribute in this shortcode [gallery include="23,39,45"].

Mainly, I need a helping hand to build this last part: Checkbox -> Populate/Unpopulate Text Field...


Layout

  1. Dynamic checkboxes

  2. Point of insertion of the text field (after the last <tr> shown in the console)

  3. Text field to be populated, should be include=" + CheckBoxID1 comma CheckBoxID2 comma etc + "

    enter image description here


Actual Code

<?php
add_action( 'admin_head-media-upload-popup', 'wpse_53803_script_enqueuer' );

function wpse_53803_script_enqueuer() {
    if( $_GET['tab'] == 'gallery' ) 
    {
        ?>
            <style>#media-upload th.order-head {width: 5%} #media-upload th.actions-head {width: 10%}</style>
            <script type="text/javascript">
            jQuery(document).ready( function($) {
    
                /* Iterate through the media items */
                $('.filename.new').each(function(i,e){
                    var id = $(this).next('.slidetoggle').find('thead').attr('id').replace(/media-head-/, '');
                    var filename = $('<label>Add to gallery list <input type="checkbox" name="gal-item-'+id+'" id="gal-item-'+id+'" value=""  /></label>').insertBefore($(this));
                    filename.css('float','right').css('margin-right','40px');

                    filename.id = id; // PROBLEM: not sure how to do this in Javascript
                    
                    // BUG: the alert is being fired twice
                    filename.click(function() {
                        alert('Handler for img id = '+filename.id+' called.');
                    });
                });                 
            });
            </script><?php
    }
}

Missing Parts

  • Create a dynamic text field to be populated.
  • Solve the problem and the bug noticed in the comments.
  • Make the filename.click(function() build the desired string inside the text field.
2
  • 1
    +1 for a nice definition of the problem. Albeit lengthy. Commented Jun 6, 2012 at 3:15
  • @JasonMcCreary - Yep, I have a verbose(?), verbatim(?), problem... (question for english.stackexchange?).. and seen/answered many problematic, difficult to understand, questions... Thanks for the heads up :) Commented Jun 6, 2012 at 3:19

1 Answer 1

1

You can do this using something similar to this

 $(document).on('change','input[type="checkbox"][name^="gal-item"]',function(){
    var checkedIds = $('input[type="checkbox"][name^="gal-item"]:checked')
                       .map(function(){
       return parseInt($(this).prop('name').replace(/gal-item-/,''));
    }).get();

    $('#shortcode').val('include="'+checkedIds.join(',')+'"');

});

You can replace document with any closer static container which you have to find by inspecting the add media markup. ​ And You have find a element where you want to add the input field, add it like

$('<span>[gallery</span><input type="text" id="shortcode" /><span>]</span>')
 .appendTo(TARGETIDORCLASS);

Working DEMO

And based on this your rewritten code would be something like

jQuery(document).ready( function($) {
     //add input field
     $('<span>[gallery</span><input type="text" id="shortcode" /><span>]</span>')
 .appendTo(TARGETIDORCLASS);
    //bind checkbox change handler


     $(document).on('change','input[type="checkbox"][name^="gal-item"]',function(){
         var checkedIds = $('input[type="checkbox"][name^="gal-item"]:checked').map(function(){
       return parseInt($(this).prop('name').replace(/gal-item-/,''));

    }).get();

    $('#shortcode').val('include="'+checkedIds.join(',')+'"');

    });


    /* Iterate through the media items */
    $('.filename.new').each(function(i,e){
        var id = $(this).next('.slidetoggle')
                        .find('thead')
                        .attr('id')
                        .replace(/media-head-/, '');
       var filename = $('<label>Add to gallery list <input type="checkbox" name="gal-item-'+id+'" id="gal-item-'+id+'" value=""  /></label>')
              .insertBefore($(this));
       filename.css('float','right').css('margin-right','40px');

                });                 
            });

This should work. I am in a hurry, couldn't test much, check and let me know if you find any error, I would love to fix those.

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

6 Comments

Hey, this working demo seems pretty goood.. will have to really test tomorrow, thanks for the input!
May I have the reasons for down vote please? I invested half an hour on this pausing my work, and down vote after that isn't great. Please at least care to comment the reason so I can correct myself.
Joy, I upvoted you from -1 and I see it is -1 again... This Stack is much more wild then WordPress', wow.. Downvotes without comments? No comments! (PS.: amazed at having received 3 upvotes in minutes..!)
@brasofilo, I dont mind down voting anyone can down vote, if they take a moment and tell me the reason So that I dont do it again in future. I am a newbie and try to do rnd and answer question with a hope of learning new things from the rnd. Down votes without comment is discouraging.
Olé! Works like a charm, Joy! Very well done, much appreciated!! I'll research your profile and ++ where due :)
|

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.