[英]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.当用户从 select 字段中选择一个值时,我想在文本框中添加多个值。 If the text field is not empty, the values will be separated by a comma.如果文本字段不为空,则值将用逗号分隔。 Im using php and javascript to populate both fields.我使用 php 和 javascript 来填充这两个字段。 For now, when I try to select another item, the value in the text field is replaced by the nez one.现在,当我尝试 select 另一个项目时,文本字段中的值被 nez 替换。
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.您可以使用 javascript function 检查文本框中是否已经有任何选定的国家/地区。 You can call the function on onchange event of the select box.您可以在 select 框的 onchange 事件上调用 function。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.