Somename Somename - 3 months ago 44
PHP Question

Get values of bootstrap dropdown in php

I have created a form with multiple fields like input type name, checkboxes and also a dropdown. My code for dropdown:

<div class="container">
<form action="selecttest.php" method="post">
<div class="dropdown">
<div class="dropdown-toggle somename1" data-toggle="dropdown"id="menu1"></div>
<ul class="dropdown-menu myclass numberom1" aria-labelledby="menu1" name="thenumbers">
<li value="one">One</li>
<li value="two">Two</li>
<li value="three">Three</li>
<li value="four">Four</li>
<li value="five">Five</li>
</ul>

</div>
<input type="submit" name ="submit"/>





I want to get the value of the selected
<li>
in the selecttest.php. The following code is not working:

$val = $_POST["thenumbers"];
echo "the Value selected is ".$val;


How can I get the value of the dropdown in the php page? There are other elements in the form as mentioned above so i cannot use jquery onclick event. And this is a non ajax form.

Thanks.

Ben Ben
Answer

A dropdown menu is not the same as a select input.

Within a form, the syntax for a select input (like yours, within Bootstrap) would be:

<label for="select_1">Select list:</label>
<select class="form-control" id="select_1" name="thenumbers">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
    <option value="four">Four</option>
</select>

So long as the select has an attribute name with value "thenumbers", and the select is within the form that is being submitted, you will be able to get the value of the selected element in PHP with:

$val = $_POST["thenumbers"];
echo "the Value selected is ".$val;

To use the Bootstrap dropdown as a faux select, you can use JavaScript. Here is an example with jQuery:

HTML

<!-- Create dropdown and add specific class '.thenumbers' to ul element -->
<div class="dropdown">
    <div class="dropdown-toggle somename1" data-toggle="dropdown"id="menu1"></div>
    <ul class="dropdown-menu myclass numberom1 thenumbers" aria-labelledby="menu1" name="thenumbers">
        <li value="one">One</li>
        <li value="two">Two</li>
        <li value="three">Three</li>
        <li value="four">Four</li>
        <li value="five">Five</li>
    </ul>
</div>

<!-- Create a hidden input -->
<input type='hidden' name='thenumbers'>

jQuery

$(function(){
    //Listen for a click on any of the dropdown items
    $(".thenumbers li").click(function(){
        //Get the value
        var value = $(this).val();
        //Put the retrieved value into the hidden input
        $("input[name='thenumbers']").val(value);
    });
});

That way (as long as the hidden input is within the form), when the form is submitted, the "thenumbers" input value will be the last selected dropdown option.

Comments