简体   繁体   English

在HTML页面中插入多项选择

[英]Insert a multiple choice in a html page

What I have to do is to make the user select some languages among those present on a page and get an array or a string that contains all the selected languages. 我要做的是使用户从页面上显示的语言中选择一些语言,并获取包含所有选定语言的数组或字符串 Do you know how can I do? 你知道我该怎么办吗? The string or array it will serve subsequently in a JavaScript method. 随后将在JavaScript方法中提供的字符串或数组。

you could use some checkboxes and save the values in an array like this: 您可以使用一些复选框并将值保存在这样的数组中:

 var lang = []; $('.cbLang').on('change', function() { this.checked ? lang.push(this.value) : removeLang(this.value); console.log(lang); }); //REMOVE UNCHECKED LANGUAGE function removeLang(removeLang){ lang = jQuery.grep(lang, function(value) { return value != removeLang; }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="cbLang" type="checkbox" value="English">English <input class="cbLang" type="checkbox" value="German">German <input class="cbLang" type="checkbox" value="French">French 

EDIT: If you also need a way to remove it from the array, check the JQuery grep(): http://api.jquery.com/jquery.grep/ 编辑:如果您还需要一种从数组中删除它的方法,请检查JQuery grep(): http : //api.jquery.com/jquery.grep/

EDIT2: I've added a function to remove a unchecked language from the array. EDIT2:我添加了一个功能,用于从数组中删除未经检查的语言。 This method calls, when a checkbox was unchecked and gives the value of the language as parameter. 取消选中复选框时,此方法调用,并提供语言的值作为参数。 It should work like this. 它应该像这样工作。

Cheers 干杯

javascript javascript

var lang = [];


$('.cbLang').on('change', function() {
  ''
  this.checked ? lang.push(this.value) : removeLang(this.value);
  console.log(lang);
});

html html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="cbLang" type="checkbox" value="English">English
<input class="cbLang" type="checkbox" value="German">German
<input class="cbLang" type="checkbox" value="French">French

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

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