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


当用户从选择字段中选择一个值时,我想在文本框中添加多个值。如果文本字段不为空,则值将用逗号分隔。我使用php和javascript来填充这两个字段。现在,当我尝试选择另一个项目时,文本字段中的值将被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函数检查文本框中是否已经有任何选定的国家/地区。您可以在选择框的onchange事件上调用该函数。我已经在代码中添加了注释。希望这能有所帮助。

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

最新更新