简体   繁体   中英

Getting the checkbox values from Last selected using JavaScript / JQuery

I am having a set of checkboxes which allows multiple checking. And I want to get the values by the last selected one. for example consider 4 checkboxes with values 1, 2, 3, 4. If I select 4, 2, 1 i need the values [4,2,1] as I selected instead of getting [1,2,4]

this is my html code snippet

<li><input type="checkbox" class="checkGroup" value="1"></li>
<li><input type="checkbox" class="checkGroup" value="2"></li>
<li><input type="checkbox" class="checkGroup" value="3"></li>
<li><input type="checkbox" class="checkGroup" value="4"></li>

the code below is my JQuery script to get the values in a array

var arr = $.map($('.checkGroup:checked'), function(e, i) {                
                value = e.value;
                return value;
            }); 

Please help me to resolve this.

Try this:

 var selectedArr = []; var dataElem = $('#data'); $('.checkGroup').on('change', function() { if (this.checked) { selectedArr.push(this.value); } else { selectedArr.splice(selectedArr.indexOf(this.value), 1); } dataElem.html(JSON.stringify(selectedArr)); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="data"></div> <li> <input type="checkbox" class="checkGroup" value="1"> </li> <li> <input type="checkbox" class="checkGroup" value="2"> </li> <li> <input type="checkbox" class="checkGroup" value="3"> </li> <li> <input type="checkbox" class="checkGroup" value="4"> </li> 

One way to do it is to store the array values as and when you are updating the state like

 var arr = []; $('.checkGroup').change(function() { if (this.checked) { arr.unshift(this.value) } else { arr.splice(arr.indexOf(this.value), 1); } }); $('button').click(function() { snippet.log(arr.join(', ')) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <ul> <li><input type="checkbox" class="checkGroup" value="1"></li> <li><input type="checkbox" class="checkGroup" value="2"></li> <li><input type="checkbox" class="checkGroup" value="3"></li> <li><input type="checkbox" class="checkGroup" value="4"></li> </ul> <button>Print</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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