How to replace an value in an array with checkboxes jQuery - javascript

I'm trying to arrange a checkbox array with jQuery. I have managed to get the values to add to the array in order and remove the correct one, but for the life of me i cannot get it to replace the removed value with the newly selected value. Currently it just adds the new value to the end of the array.
Here's my code so far:
var array = [];
$('input[type="checkbox"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
$('#ff_elem512').val(array);
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
$('#ff_elem512').val(array);
}
}
}
console.log(array);
});
Thanks in advance

Use Jquery is function instead of attr like Below
var array = [];
$('input[type="checkbox"]').click(function () {
if ($(this).is('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
$('#ff_elem512').val(array);
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
$('#ff_elem512').val(array);
}
}
}
console.log(array);
});

var array = [];
$('input[type="checkbox"]').change(function() {
if ($(this).prop('checked')) {
// Add the new element if checked:
if (array.indexOf($(this).val()) < 0) {
array.push($(this).val());
}
} else {
// Remove the element if unchecked:
if (array.indexOf($(this).val()) >= 0) {
array.splice(array.indexOf($(this).val()), 1);
}
}
$('#ff_elem512').val(array.join(", "));
console.log(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />One
<input type="checkbox" value="2" />Two
<input type="checkbox" value="3" />Three
<input type="checkbox" value="4" />Four
<input type="checkbox" value="5" />Five
<br />
<input type="text" id="ff_elem512" />

You can always set your array when you click some checkbox, like this:
$('input[type="checkbox"]').click(function () {
array = [];
$("input[type=checkbox]:checked").each( function () {
array.push($(this).val());
});
console.log(array);
});
Here is a fiddle: https://jsfiddle.net/9ssyxvv2/
UPDATE: If you want to preserver the clicked order, use this instead:
$('input[type="checkbox"]').click(function () {
var elem=$(this);
if (this.checked) {
array.push($(this).val())
} else {
array = array.filter(function(x){
return x != $(elem).val() });
}
console.log(array);
});

Related

Why is Javascript equating 5 == 8 as true?

So I have 2 check-boxes:
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.length > 0) {
for (var i = 0; i < statusList.length; i++) {
if (parseInt(statusList[i]) == parseInt(x)) {
statusList[i] = 123;
} else {
statusList.push(x);
}
}
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
When I click a checkbox it adds it to a JavaScript list, if it's already in the list I want to overwrite it with another value (123 in this example).
But when I click the second one (doesn't matter the order, the 2nd element is always 123 for some reason.
Where as I would expect if I click the top check-box it would be a list containing '5', then clicking the second check-box I would expect 5,8 but it alerts as 5,123, don't really see why it's doing this as 5==8 is false... any ideas?
Updated algorithm to fix underlying issue:
In-case anyone ever finds this useful I changed the algorithm to a better alternative:
var statusList = [];
function updateStatusString(x) {
if (statusList.length > 0) {
if (statusList.includes(x)) {
var idx = statusList.indexOf(x);
if (idx != -1) {
statusList.splice(idx, 1);
}
}
else {
statusList.push(x);
}
} else {
statusList.push(x);
}
alert(statusList);
}
first iteration:
since status list is empty you are adding 5 in it,
second iteration:
statulsList = [5]
you are adding 8 so now the statusList value is [5,8] which means also the length is 2,
so we have a third iteration which in this case 8 === 8 .
if you want to have it different save the length of the status list before adding the other item on the list.
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.length > 0) {
var lengthStat = statusList.length;
for (var i = 0; i < lengthStat; i++) {
if (parseInt(statusList[i]) == parseInt(x)) {
statusList[i] = 123;
} else {
if(! (statusList.indexOf(x) != -1))
statusList.push(x);
}
}
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
Because you are iterating over the statusList. At first iteration you check if 5 == 8, then moves to else part and inserts 8 in statusList. Your statusList is = [5, 8]. For next iteration, this becomes true statuslist[i] will be 8 and 8===8 and your statement - statusList[i] = 123; will replace last inserted 8value with 123. Therefore, your statusList array will have ["5", 123].
var statusList = [];
function updateStatusString(x) {
const input = parseInt(x);
if (statusList != null) {
if (statusList.includes(input)) {
const idx = statusList.indexOf(input);
statusList[idx] = 123;
} else {
statusList.push(input);
}
alert(statusList);
}
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
It looks like the loop was causing your issue.
You were checking for the existence of x, which on the first loop was false
You pushed it to the array
Second loop, it existed and was replaced with 123
You can dramatically simplify your code by removing one of the if checks, and using array.prototype.includes instead of looping and checking equality.
Edit: Added a third input to demonstrate 123 being added.
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.includes(x)) {
statusList[statusList.indexOf(x)] = 123;
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("5")> "Active"</label>

Create an array of selected radio button values

I have few radio buttons:
<input type="radio" value="####.###/resources/videos/7.mp4">
<input type="radio" value="####.###/resources/videos/8.mp4">
<input type="radio" value="####.###/resources/videos/9.mp4">
How can I make an array containing the selected values like following:
var videos = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"];
Onclick push the value of radio in array
var arr=[];
$('input').click(function(){
arr.push("."+$(this).val().split('####.###')[1])
console.log(arr);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="####.###/resources/videos/7.mp4">Video1
<input type="radio" value="####.###/resources/videos/8.mp4">Video2
<input type="radio" value="####.###/resources/videos/9.mp4">Video3
I would add a change event listener, that checks if the input got checked or unchecked and would add it or remove it from the list.
var originalVideoList = ["./resources/videos/7.mp4",
"./resources/videos/1.mp4",
"./resources/videos/2.mp4",
"./resources/videos/3.mp4"
];
var videos = document.querySelector("#videos");
var result = document.querySelector("#result");
var template = "<li><label for='{0}'>Video {1}</label><input id='{0}' type='checkbox' onchange='onChange()'/></li>";
var selectedArray = [];
// Set up html
videos.innerHTML = originalVideoList.map(function(video) {
return template.replace(/\{0\}/g, video).replace(/\{1\}/g, video.split("/").pop());
}).join("");
// triggered on input change
function onChange() {
selectedArray = toArray(document.querySelectorAll("li>input:checked")).map(function(item) {
return item.id.replace("####.###", ".");
});
result.innerHTML = selectedArray.map(function(video) {
return "<li>" + video + "</li>";
}).join("");
}
// Same as [...input]
function toArray(input) {
var result = [];
for (var index = 0; index < input.length; index++) result[index] = input[index];
return result;
}
<ul id="videos"></ul>
<ul id="result"></ul>

How to check all checkboxes?

jsp code is
<input
type="button"
class="btn btn-theme02 btn-xs "
value="CheckAll"
onClick="CheckAll(document.myform.checklist)" />
<input
type="button"
class="btn btn-theme02 btn-xs"
value="UnCheckAll"
onClick="UnCheckAll(document.myform.checklist)" />
<input
type="checkbox"
style="width: 20px"
class="checkbox form-control centered"
id="checklist"
name="checklist"
value="<%=voucher.getId()%>" />
Checkboxes are in a table. Checkbox rows are dynamic.
Javascript:
function CheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}
function UnCheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
CheckAll and UnCheckAll buttons are working if there are two or more checkbox.These buttons not working for single checkbox.
Thanks.
You can do:
$(":checkbox").prop('checked', true);
Try this:
function CheckAll(){
$('input[type=checkbox]').each(function () {
$(this).prop('checked', true);
});
}
function UnCheckAll(){
$('input[type=checkbox]').each(function () {
$(this).prop('checked', false);
});
}
and remove anything you are passing as parameter. this should work try it and let me know for any further issue.
In traditional JS:
function CheckAll(state) {
var i = 0,
inputs = document.getElementsByTagName('input');
for (i = 0; inputs.length; i++) {
if (inputs[i].type === 'checkbox') {
inputs[i] = state;
}
}
}
checkAll(true); // to check
checkAll(false); // to uncheck

Radio Button list selected items value in javascript

I am using following code to get the selected elements value in radio button list.
function SelectRadioButton()
{
var radiobutton = document.getElementsByName('<%=RadioButtonList1.ClientID %>');
alert(radiobutton.length);
for(var x = 0; x < radiobutton.length; x++)
{
if(radiobutton[x].checked)
{
alert('selected is ' + radiobutton[x].id);
}
}
}
Following is the HTML markup
<table id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1" class="chk" onclick="javascript:SelectRadioButton(this, ctl00_ContentPlaceHolder1_idControl_RadioButtonList1)" border="0">
<tr>
<td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="1" checked="checked" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_0">List</label></td><td><input id="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1" type="radio" name="ctl00$ContentPlaceHolder1$idControl$RadioButtonList1" value="2" /><label for="ctl00_ContentPlaceHolder1_idControl_RadioButtonList1_1">Assignment</label>
But I am getting length 0 in alert(radiobutton.length); statement.
Why is this happening. any thing that I am missing?
You can use jquery to do this.
alert($(".chk").find("input:checked").length); // chk is your css class name applied to Checkbox List element.
You can get specific element by using this
alert($(".chk").find("input:checked")[0]);
RadioButtonList1 will be converted to radio buttons with ids having RadioButtonList1, You can iterate through DOM and look for matched ids and put them in some array or directly perform what you want to them.
radiobutton = [];
for(i=0;i<document.forms[0].length;i++)
{
e=document.forms[0].elements[i];
if (e.id.indexOf("RadioButtonList1") != -1 )
{
radiobutton.push(e);
}
}
Here's how you do it with javascript only, if you don't want to use getElementById
Code | JSFiddle
function SelectRadioButton(){
var radiolist = getElementsByClass("table", "chk")[0],
radios = radiolist.getElementsByTagName("input");
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
alert('Selected radiobutton is ' + radios[i].id);
}
}
}
function getElementsByClass(tag, name){
var elements = document.getElementsByTagName(tag);
var ret = [];
for(var i = 0; i < elements.length; i++){
if(elements[i].className.indexOf(name) !== -1){
ret.push(elements[i]);
}
}
return ret;
}

Fast way to validate if all checkboxes are un-selected?

Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML)
All my check boxes have the same name...
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us" value="Joe" ID="Checkbox1">
<input type=checkbox name="us" value="Dan" ID="Checkbox2">
<input type=checkbox name="us" value="Sal" ID="Checkbox3">
</form>
jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this:
function AreAnyCheckboxesChecked () {
var checkboxes = document.forms.Form2.elements.us;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
You have to loop through them. Even a library like jQuery will loop through them, just hide it from you.
var form = document.getElementById('Form2');
var inputs = form.getElementsByTagName('input');
var is_checked = false;
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') {
is_checked = inputs[x].checked;
if(is_checked) break;
}
}
// is_checked will be boolean 'true' if any are checked at this point.
JavaScript:
var allischecked = (function(){
var o = document.getElementById("Form2").getElementsByTagName("input");
for(var i=0,l=o.length;i<l;i++){
o[i].type === "checkbox" && o[i].name === "us" && o[i].checked || return false;
}
return true;
})();
With jQuery:
var allischecked = ($("#Form2 input:checkbox:not(checked)").length === 0);
In summary, this snipped will return true if all are NOT checked. It bails out as soon as a checked one is found.
var a = document.getElementsByName("us");
for(var i=0; i<a.length; i++)
if(a[i].checked)
return false;
return true;
(did not test, but conceptually it is valid)
What do you mean by
Without going through array
?
You could just do
function check() {
var anyChecked = false;
var form = document.getElementById('Form2');
var checkboxes = form.getElementsByTagName('input');
for(var i=0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
alert("Checkboxes checked? " + anyChecked);
}
Working Demo
If you have a large amount of checkboxes that you don't want to loop through to test it might be more efficient to use this approach.
var checked = 0;
$("input[type=checkbox]").live("click", function() {
if($(this).attr("checked")) checked++;
else checked--;
}
Then you would be able to test like this.
if(checked === 0) {
doSomething();
}
The proper solution with jQuery attribute checked:
$checkboxes = $('#Form2 input:checkbox');
$checkboxes.on('click', checkboxes);
function checkboxes() {
var allChecked = $checkboxes.not(':checked').length == 0;
console.log(allChecked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us1" value="Joe" ID="Checkbox1"><label>Joe</>
<input type=checkbox name="us2" value="Dan" ID="Checkbox2"><label>Dan</>
<input type=checkbox name="us3" value="Sal" ID="Checkbox3"><label>Sal</>
</form>
Even easier without loop
const toggleCheckboxes = checkbox => {
if(checkbox.checked){
return true
}else{
if(document.querySelectorAll(':checked').length === 0){
// All are unchecked
return false
}
}
}

Categories

Resources