The XML template given to me by the background:
<Pay>0,1,2</Pay>
<input type="checkbox" name="PayTypeList" class="PT1">1
<input type="checkbox" name="PayTypeList" class="PT2">2
<input type="checkbox" name="PayTypeList" class="PT3">3
<script>
($(".PT1").is(':checked')==true)?PT1="0":PT1="";
($(".PT2").is(':checked')==true)?PT2="1":PT2="";
($(".PT3").is(':checked')==true)?PT3="2":PT3="";
</script>
$("#textarea").html("<Pay>"+PT1+","+PT2+","+PT3+"</Pay>")
I use this method to determine and then splice, but if the last option is not selected, then the previous option is followed by a comma, what should I do
Declare an array. If a checkbox is selected, push the value into it, and finally use join to convert it into a comma-separated array.
The regular expression used upstairs can only remove the last comma. If there are unselected ones in front, there will still be extra commas.
1. I understand your requirement: you only need to display them in order, regardless of the order of selection. For example, whether you select 2 or 0 first, the display will be 0, 2;
My solution is to use an array to traverse. There are many traversal methods:
Option 1: Use
reduce
(I just learned reduce today, let’s play with it)Option 2: Use
filter + join
Option 3: Use
for loop
2. If you consider the click order, you can use the change event: when the CheckBox changes, judge checked to add or delete data
html:
javascript
(Learned from
huguangju
’s method of creating an empty array)As an array, remove the null items in the array and then format it into a string