How add a class to select element

2019-06-07 04:49发布

问题:

I'm a big fan of Contact Form 7 and I always come to a point where I need to make a few extended customization to my forms. This time, I'm quite frustrated trying to add different classes to a select element <option> tag with no avail.

What I'm trying to do is implement a cool style and effect to dropdown lists from Here into my own CF7 form - as the screenshot shows it works nicely, however, icons are not showing because so that they can be displayed the <option>tag within a select element needs to have its own class.

For e.g:

First, I need to create a select element with id="cd-dropdown" and class="cd-select", until here, this can be easily achieved with the CF7 shortcode generator as bellow.

[select* select-profissao id:cd-dropdown class:cd-select "Professional" "Nurse" "Lawyer"]

Contact Form 7 aforementioned shortcode generates the html select element to something like this:

<select id="cd-dropdown" class="cd-select">
 <option value="" selected>Professional</option>
 <option value="" >Nurse</option>
 <option value="" >Lawyer</option>
</select>

But I'd like to be able to add a class to the <option> tag. Is it even possible to achieve that by using the CF7 shortcode generator? Are there any workarounds in order to achieve that maybe by using javascript/jQuery or even PHP?

<select id="cd-dropdown" class="cd-select">
 <option value="" selected>Professional</option>
 <option value="" class="icon-nurse">Nurse</option>
 <option value="" class="icon-lawyer">Lawyer</option>
</select>

I'd really appreciate any guidance regarding this issue. Thanks in advance.

回答1:

Just add this jquery: http://jsfiddle.net/rvpatel/7wa3V/

    $( "#cd-dropdown option" ).addClass(function(index) {
     return "icon-" + $(this).text().toLowerCase().split(' ').join('-');
});



回答2:

I think it would be easier to add classes to option client side using jQuery (assuming you are already using jQuery for the SimpleDropDownEffects plugin)

Example Select rendered by contact form:

<select id="cd-dropdown" class="cd-select">
    <option value="-1" selected>Choose a weather condition</option>
    <option value="1">Sun</option>
    <option value="2">Clouds</option>
    <option value="3">Snow</option>
    <option value="4">Rain</option>
    <option value="5">Windy</option>
</select>

Add following javascript on the page:

jQuery(document).ready(function() {
    myClassNames = ["", "icon-sun", "icon-cloudy", "icon-weather", "icon-rainy", "icon-windy"];
    jQuery.each(jQuery("#cd-dropdown option"), function(index, value) {
        jQuery(value).addClass(myClassNames[index]);
    });
    //do SimpleDropDownEffects plugin here after classes are added.
});

Pros: No hacking into plugin files, no update plugin woes.
Cons: class names are had-coded in js



回答3:

Modify in your plugin dir modules/select.php wpcf7_select_shortcode_handler function:

function wpcf7_select_shortcode_handler( $tag ) {
    $tag = new WPCF7_Shortcode( $tag );

    if ( empty( $tag->name ) )
        return '';

    $validation_error = wpcf7_get_validation_error( $tag->name );

    $class = wpcf7_form_controls_class( $tag->type );

    if ( $validation_error )
        $class .= ' wpcf7-not-valid';

    $atts = array();

    $atts['class'] = $tag->get_class_option( $class );
    $atts['id'] = $tag->get_option( 'id', 'id', true );
    $atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );

    if ( $tag->is_required() )
        $atts['aria-required'] = 'true';

    $atts['aria-invalid'] = $validation_error ? 'true' : 'false';

    $defaults = array();

    if ( $matches = $tag->get_first_match_option( '/^default:([0-9_]+)$/' ) )
        $defaults = explode( '_', $matches[1] );

    $multiple = $tag->has_option( 'multiple' );
    $include_blank = $tag->has_option( 'include_blank' );
    $first_as_label = $tag->has_option( 'first_as_label' );

    $name = $tag->name;
    $values = $tag->values;
    $labels = $tag->labels;

    $empty_select = empty( $values );

    if ( $empty_select || $include_blank ) {
        array_unshift( $labels, '---' );
        array_unshift( $values, '' );
    } elseif ( $first_as_label ) {
        $values[0] = '';
    }

    $html = '';

    $posted = wpcf7_is_posted();

    foreach ( $values as $key => $value ) {
        $selected = false;

        // changed here
        if (! ( $attributes = json_decode($value, true) ) ) {
            $attributes = array(
                'value' => $value
            );
        } else {
            $value = (isset($attributes['value'])) ? $attributes['value'] : null;
        }

        if ( $posted && ! empty( $_POST[$name] ) ) {
            if ( $multiple && in_array( esc_sql( $value ), (array) $_POST[$name] ) )
                $selected = true;
            if ( ! $multiple && $_POST[$name] == esc_sql( $value ) )
                $selected = true;
        } else {
            if ( ! $empty_select && in_array( $key + 1, (array) $defaults ) )
                $selected = true;
        }

            // changed here
            $item_atts = array('selected' => $selected ? 'selected' : '' );
            $item_atts = array_merge($attributes, $item_atts);

        $item_atts = wpcf7_format_atts( $item_atts );

        $label = isset( $labels[$key] ) ? $labels[$key] : $value;

        $html .= sprintf( '<option %1$s>%2$s</option>',
            $item_atts, esc_html( $label ) );
    }

    if ( $multiple )
        $atts['multiple'] = 'multiple';

    $atts['name'] = $tag->name . ( $multiple ? '[]' : '' );

    $atts = wpcf7_format_atts( $atts );

    $html = sprintf(
        '<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select>%4$s</span>',
        $tag->name, $atts, $html, $validation_error );

    return $html;
}

Now you can call the plugin as before, or send the value of json(all keys rendered as attribute), i.e.:

[select* select-profissao id:cd-dropdown class:cd-select '{"value":"Professional","class":"mytestclass"}' '{"value":"Nurse","more-attr":"Nurse Attribute"}']

Unfortunately I can not test this (No installed wordpress).