Home > Net >  how to preselect a multiple option on php loop
how to preselect a multiple option on php loop

Time:05-04

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  ';
  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

CodePudding user response:

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.

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

CodePudding user response:

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 put the last output, (the close of the tag), inside the for loop.

                    if($subcategory->parent == $category->term_id) {
                        $output.=' <option  ';
                        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>';
                    }

CodePudding user response:

This is the same as the answer provided by Ruchita Sheth. I just added your if statement.

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