简体   繁体   中英

Pass two variables through checkbox in php

Through checkbox I want to pass & values. how can I do that. I can only pass one value. I am trying but its not working

while($row_tbl = mysqli_fetch_array($query))
      {
        <tr class="success" style="font-size:12px;">

         <td > <input type="checkbox" name="check[]" class="chk_val" value=" <?php echo $row_tbl['Course_ID'] ?> " id="in" onclick="test()" /></td>

            <td > <?php echo $row_tbl['Course_ID'] ?> </td>
            <td> <?php echo $row_tbl['Course_Title'] ?> </td>
            <td> <?php echo $row_tbl['Section'] ?> </td>
            <td> <?php echo $row_tbl['Time'] ?> </td>
            <td> <?php echo $row_tbl['Day'] ?> </td>
            <td> <?php echo $row_tbl['Dept'] ?> </td>
            <td> <?php echo $row_tbl['Capacity'] ?>&nbsp/&nbsp 0 </td>


                    <?php

                  }

To pass multiple values, you need to create multiple checkbox with the same name (as an array)

 <input type="checkbox" name="check[]" class="chk_val" value="value1"/>
 <input type="checkbox" name="check[]" class="chk_val" value="value2"/>
 <input type="checkbox" name="check[]" class="chk_val" value="value3"/>
 <input type="checkbox" name="check[]" class="chk_val" value="value4"/>

In your controller,

$values = $request->check; //the array of checked inputs.

Then you can loop through it

foreach($values as $value) {
    ...
}

Update

Accodring to the chat discussion you want to send 2 different fields per checkbox. In your checkboxes, put both fields like this

@foreach($courses as $course)
    <input type="checkbox" 
        name="check[]" 
        class="chk_val" 
        value="{{ $course->id }}-{{ $course->section }}"/>
@endforeach

Pay attention to the value here. I added a delimiter - that will be useful in the controller. In controller now

public function selectedCourses(Request $request)
{
    ... //whatever you do for validation

    //loop through selected courses
    foreach( $request->check as $values ) { 
        $values = explode("-", $values); //split where we added the dash
        $id = $values[0]; //the course ID
        $section = $values[1]; // the course section

        ... do what you want here with that information
    }
}

And voila!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM