Lee
Lee

Reputation: 25

get all options from select box NOT MULTIPLE and pass them to php for inserting in mysql

<select class="myselect" id="myselect" name="mul_cat" onChange="catChange();" multiple="multiple">
   <option value="" selected>-Select-</option>
<option value="Truck">Truck</option>
<option value="Car">Car</option>
<option value="Van">Van</option>
<option value="Bus">Bus</option>
  </select>

<?php
    while(($mul_cats = each($mul_cat))) {
    $mul_cats = trim($mul_cats['value']);
    //insert into vehicles........ 
    }
?>

I am trying to post all the select option from the above and pass them to the database using the while loop above. Please N.B., I do not want the above select box to be a multiple select box. I just simple want to pass all the options in there to the database. Additionally, I want all of the options that are available not selected . Please help me or tell me if it is possible to do so.

Upvotes: 1

Views: 714

Answers (2)

Ed Meacham
Ed Meacham

Reputation: 583

Assuming you have complete control over the markup, you could do something similar to the following...

$categories = ['Truck', 'Car', 'Van', 'Bus'];

<select multiple="multiple" name="mul_cat[]">
<? foreach($categories as $value) { ?>
    <option value=<?= $value; ?>></option>
<? } ?>
</select>

This way, you will already have the categories and can map them however you want without the need for javascript.

Otherwise, you would need to stuff everything into a hidden input or added a POST variable for mul_cats.

Upvotes: 0

PHP Web
PHP Web

Reputation: 257

Try the following logic .

Use a JQuery to get all the options of the select dropdown (not multiple) and store them in a hidden field with comma delimiter . Now take this value , explode the values using the comma delimiter and store them in database . Let's have a look :-

<script>
$(document).ready(function(){
    $('#myselect').each(function(){
        optionValues.push($(this).val());
    });
    $('#result').val(optionValues);
});
</script>

<html>
<input type="hidden" id="result" />
</html>

<?php
    //Get the values of the drop-down in an array and run a loop to insert all the values of the array in a database
?>

Upvotes: 1

Related Questions