Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I POST all options in a select list?

I have a select multiple list that has a few items in it. It is a list of IP addresses for an ACL. People can add/remove IPs, and then save the list. However, unless you select an item on the list, $_POST[selectName] does not contain any values. How can I accomplish this? I know I can do this with javascript but I would rather stick to PHP.

like image 734
Steve Avatar asked Mar 03 '13 20:03

Steve


People also ask

How do I iterate a dropdown in jQuery?

Simple jQuery code snippet to loop select box options (drop down boxes) in a form to get the values and text from each option. Useful for manipulating values in form select boxes. $('#select > option'). each(function() { alert($(this).


2 Answers

Edit/corrected: You need JS. There is no way to send all (selected and not selected) options via POST. You have to programatically select all options before submission.

File with form (file1.php):

<script type="text/javascript">
    function selectAll() 
    { 
        selectBox = document.getElementById("someId");

        for (var i = 0; i < selectBox.options.length; i++) 
        { 
             selectBox.options[i].selected = true; 
        } 
    }
</script>

<form method="post" action="file2.php">
    <select id="someId" name="selectName[]" multiple>
        <option value="123.123.123.123">123.123.123.123</option>
        <option value="234.234.234.234">234.234.234.234</option>
    </select>
    <input type="submit" name="submit" value=Submit onclick="selectAll();">
</form>

File that receives POST (file2.php):

<?php
    foreach ($_POST['selectName'] as $item)
    {
    print "$item<br/>";
    }
?>
like image 130
Kamil Avatar answered Sep 30 '22 08:09

Kamil


Just to tack on this you could also use the jQuery version of @Kamil's code which is a little simpler than the loop:

<script type="text/javascript">
jQuery('[name="form1"]').on("submit",selectAll);

function selectAll() 
{ 
    jQuery('[name="selectName[]"] option').prop('selected', true);
}

</script>
<form name="form1" method="post" action="file2.php">
<select id="someId" name="selectName[]" multiple>
    <option value="123.123.123.123">123.123.123.123</option>
    <option value="234.234.234.234">234.234.234.234</option>
</select>
<input type="submit" name="submit" value=Submit onclick="selectAll();">  
</form>
like image 32
RestlessWeb Avatar answered Sep 30 '22 08:09

RestlessWeb