skip to Main Content

im trying to print an option tag with multiple options preselected, but i have a problem with the html output because the tag is closing before than i want to:

$output.=' <option class="opt" ';
  for($f = 0 ; $f < count($p_cargoInteres) ; $f++){
    if($subcategory->term_id == $p_cargoInteres[$f]){
        $output.= 'selected = "true"';
           }
        $output.= ' value="'. esc_attr( $subcategory->term_id ) .'">'. esc_html( $subcategory->name ) .'</option>';

but when im trying to print the option tag close before the ‘selected’
here is how this looks like

There`s a better way to do this?

i’m receiving the var $p_cargoInteres like an Array.

This is an updating form, than the people must refill if is necessary, but i must show the last data into the bd

3

Answers


  1. Chosen as BEST ANSWER

    Sorry if i dont explain the issue well, but i was comparing 2 arrays

    1st array with id's of post (to select) 2nd array with saved id's selected before from the bd.

    and i was wanting to re-select the past ids just to show the past preferences of the user.

    My mistake was putting the last output, (the close of the tag), inside the for loop.

    if($subcategory->parent == $category->term_id) {
        $output.=' <option class="opt" ';
        for($f = 0 ; $f < count($p_cargoInteres); $f++) {
            if($subcategory->term_id == $p_cargoInteres[$f]) {
                $output.= 'selected = "true"';
            } else {
                $output.= '';
            }
        } /* THIS IS THE FINISH OF THE FOR */
        $output.= ' value="'. esc_attr( $subcategory->term_id ) .'">'. esc_html( $subcategory->name ) .'</option>';
    }
    

  2. You have set an option tag outside a for a loop. That will create a one option tag only. It should be inside for loop to create multiple options.

    if($subcategory->parent == $category->term_id) {
        for($f = 0 ; $f < count($p_cargoInteres) ; $f++){
            $output .= ' <option class="opt" ';
            if($subcategory->term_id == $p_cargoInteres[$f]) {
                $output.= 'selected = "true"';
            }
            $output.= ' value="'. esc_attr( $subcategory->term_id ) .'">'. esc_html( $subcategory->name ) .'</option>';
        }
    }
    
    Login or Signup to reply.
  3. You then need to close the for loop after the if statement before the final $output .= ‘value="’

    if($subcategory->parent == $category->term_id) {
        $output .= '<option class="opt" ';
        for ($f = 0; $f < count($p_cargoInteres); $f++) {
            if($subcategory->term_id == $p_cargoInteres[$f]){
                $output.= 'selected="true" ';
            }
        }
        $output.= 'value="'. esc_attr( $subcategory->term_id ) .'">'. esc_html( $subcategory->name ) .'</option>';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search