繁体   English   中英

Javascript/PHP:如何将 select 中的多个值(以逗号分隔)添加到文本字段

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

当用户从 select 字段中选择一个值时,我想在文本框中添加多个值。 如果文本字段不为空,则值将用逗号分隔。 我使用 php 和 javascript 来填充这两个字段。 现在,当我尝试 select 另一个项目时,文本字段中的值被 nez 替换。

这是我的代码:

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/>';

您可以使用 javascript function 检查文本框中是否已经有任何选定的国家/地区。 您可以在 select 框的 onchange 事件上调用 function。 我已将注释与代码一起添加。 希望这可以帮助。

        <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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