简体   繁体   中英

Javascript/PHP: How to add multiple values from a select, separated by a comma, to an text field

Id like to add more than one value in text box when the user selects a value from a select field. If the text field is not empty, the values will be separated by a comma. Im using php and javascript to populate both fields. For now, when I try to select another item, the value in the text field is replaced by the nez one.

Here is my code:

echo' <div>';
                echo' <label for="pnationalite"><strong>Visited countries</strong></label> '; 

                echo' <select onclick="this.form.paysvisites.value=this.options[this.selectedIndex].text;" name="nationalite_ID" > '; 

                $sql = $bdd->query("SELECT * FROM cov_pays"); 

                //Feed the select from the db

                while ($row = $sql->fetch()) 
                {                       
                    echo '<option value="' . $row['LibPays'] . '">' . $row['LibPays'] . '</option>';                            
                }

                echo' </select> ';

                echo' <div>
                        <br /><input type="text" name="paysvisites" placeholder="Please select one country" >
                    </div>

                    ';              

            echo' </div><br/>';

You can use a javascript function to check whether there is already any selected countries in the textbox or not. You can call the function on onchange event of the select box. I have put comments along with the code. Hope this helps.

        <select onchange="addCountry(this)" name="nationalite_ID" >     
        <script>
            function addCountry(s) {
                console.log(s.options[s.selectedIndex].text);                    
                var thisCountry = s.options[s.selectedIndex].text; // latest selection                    
                var selected = s.form.paysvisites.value;  // already selected in the textbox
                console.log(selected);                    
                var toAdd = "";                    
                if(selected.length) {
                     toAdd = ", "; // if there are already selected countries add a comma
                }                    
                if(selected.indexOf(thisCountry) === -1) {    // if this selected country is not already in the textbox, add it                    
                    s.form.paysvisites.value+= toAdd + thisCountry;    
                }                    
            }

        </script>

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