Search code examples
jquerycheckboxradio-button

Looping through checkboxes and choosing the :checked checkbox value?


I have an array for each array attribute an input checkbox is looped, I can return the value of the checked input, but it outputs every instance of the array.

     $('#moon-generator-settings .moon-generator-attr').each(function() {
        if ( $(this).val() !== '') {
            $('#moon-generator-result').val( $('#moon-generator-result').val() + ' ' + $(this).attr('name') + '="' + $(this).val() + '"' );                
        }

this outputs code into the editor on wordpress the code should look like this

      [icons myicon="globe"]

but instead returns

      [icons myicon="globe" myicon="pencil" myicon="plus" myicon="minus" myicon="left" myicon="up" myicon="right" myicon="down" myicon="home" myicon="pause" myicon="fast-fw" myicon="fast-bw" myicon="to-end" myicon="to-start" myicon="stop"]

where myicon is, that is where $(this).attr('name') is, and $(this).val() is obviously the value myicon equals, the value inside my input. I am having trouble only returning the checked value of the input, not all of them, which causes me to suspect the checkboxes are not returning properly.

here is some more code.

     $('#moon-generator-insert').live('click', function(event) {

    var queried_shortcode = $('#moon-generator-select').find(':checked').val();
    var moon_compatibility_mode_prefix = $('#moon-compatibility-mode-prefix').val();

    $('#moon-generator-result').val('[' + moon_compatibility_mode_prefix + queried_shortcode);

    $('#moon-generator-settings .moon-generator-attr').each(function() {
        if ( $(this).val() !== '') {
            $('#moon-generator-result').val( $('#moon-generator-result').val() + ' ' + $(this).attr('name') + '="' + $(this).val() + '"' );                
        }

    });

    $('#moon-generator-result').val($('#moon-generator-result').val() + ']');

Ive read as much as I could and I dont think the .find(:checked).val() should be written that way?

Here is the parsed php in HTML format

     <div class="icons">
     <input class="moon-generator-attr" type="checkbox" value="globe" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="pencil" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="plus" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="minus" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="left" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="up" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="right" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="down" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="home" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="pause" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="fast-fw" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="fast-bw" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="to-end" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="to-start" name="myicon">
     <input class="moon-generator-attr" type="checkbox" value="stop" name="myicon">
     </div>

So here is what does work... when using a select options dropdown there isnt a problem...

      <select id="moon-generator-attr-style" class="moon-generator-attr" name="style">
        <option>1</option>
        <option>2</option>
      </select>

the Jquery

      $('#moon-generator-insert').live('click', function(event) {
    var queried_shortcode = $('#moon-generator-select').find(':selected').val();
    var moon_compatibility_mode_prefix = $('#moon-compatibility-mode-prefix').val();
    $('#moon-generator-result').val('[' + moon_compatibility_mode_prefix + queried_shortcode);
    $('#moon-generator-settings .moon-generator-attr').each(function() {
        if ( $(this).val() !== '' ) {
            $('#moon-generator-result').val( $('#moon-generator-result').val() + ' ' + $(this).attr('name') + '="' + $(this).val() + '"' );
        }
    });
    $('#moon-generator-result').val($('#moon-generator-result').val() + ']');

thanks everyone, this is MUCH APPRECIATED here is updated code...

      $('#moon-generator-insert').live('click', function(event) {
    var queried_shortcode = $('#moon-generator-select').find(':selected').val();

    var moon_compatibility_mode_prefix = $('#moon-compatibility-mode-prefix').val();
    var result = $(".moon-generator-attr:checked").map(function () {
    var $this = $(this);
    return $this.attr("name") + '="' + $this.val() + '"';
    }).get().join(" ");

    $('#moon-generator-result').val('[' + moon_compatibility_mode_prefix + queried_shortcode);
    $('#moon-generator-settings .moon-generator-attr').each(function() {
        if ( $(this).val() !== '' ) {
            $('#moon-generator-result').val( $('#moon-generator-result').val() + ' ' + $(this).attr('name') + '="' + result + '"' );
        }
    });
    $('#moon-generator-result').val($('#moon-generator-result').val() + ']');

outputs to this

      [icons myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop"" myicon="myicon="stop""]

here is the checkbox php

      // Checkbox
        if ( count( $attr_info['checks'] ) && $attr_info['checks'] ) {              
            $return .= '<div class="icons">';
            foreach ( $attr_info['checks'] as $attr_value ) {
                $attr_value_selected = ( $attr_info['default'] == $attr_value ) ? ' checked="checked"' : '';        
            $return .= '<input name="' . $attr_name . '" class="moon-generator-attr" type="checkbox" value="' . $attr_value . '" '.$attr_value_selected.'>  </input> ';

            }
            $return .= '</div>';
        }

here is the array

      'icons' => array(
            'name' => 'Icons',
            'type' => 'single',
            'atts' => array(
                'myicon' => array(
                    'checks' => array(
                        'globe',
                        'pencil',
                        'plus',
                        'minus',
                        'left',
                        'up',
                        'right',
                        'down',
                        'home',
                        'pause',
                        'fast-fw',
                        'fast-bw',
                        'to-end',
                        'to-start',
                        'stop',
                    ),
                    'desc' => __( 'Add an icon', 'moon-shortcodes' )
                )
            ),
            'usage' => '[icons myicon="globe"][/icons]',
            'desc' => __( 'Add Icon', 'moon-shortcodes' )
        ),

Solution

  • The problem is, whether or not the checkboxes are checked, they still have a value, so .val() will return the value even if unchecked. You need to filter the checkboxes by the :checked selector when looping over them.

    Here is code which will return a string containing all of the checked items:

    var result = $(".moon-generator-attr:checked").map(function () {
            var $this = $(this);
            return $this.attr("name") + '="' + $this.val() + '"';
        }).get().join(" ");
    
    alert("Result='" + result + "'");
    

    Here is a fiddle: http://jsfiddle.net/bman654/NE8M9/ Just click some checkboxes and click Go

    -- Updated code from OP --

    var queried_shortcode = $('#moon-generator-select').find(':selected').val();
    
    var moon_compatibility_mode_prefix = $('#moon-compatibility-mode-prefix').val();
    var checkedString = $(".moon-generator-attr:checked").map(function () {
        var $this = $(this);
        return $this.attr("name") + '="' + $this.val() + '"';
    }).get().join(" ");
    
    var resultString = '[' + moon_compatibility_mode_prefix +
                       queried_shortcode + ' ' + checkedString + ']';
    
    $('#moon-generator-result').val(resultString);