Building a multidimensional object of form values using loops - javascript

I have this form that calculates the value of the radio button checkbox and quantity. I want to loop the name and value of every checked or selected item into a multidimensional object array. I am using the storeArray function to do this but all i could do was this tab = {Apple: 1, Orange: 2, quantity: 7}
But I want to be able to do something like so..
tab = {name: Apple, value: 1,}{name:Orange, value: 2}{name: quantity, value: 7}. I tried my best, I guess I'm not doing it right.
function storeArray() {
var tab = {};
$('*[data-in="num"]:checked,#quantity').each(function() {
tab[$(this).attr('name')] = parseInt($(this).val());
});
console.log(tab);
return tab;
}
function validate(s) {
//This is how we check that at least a checkbox is checked
/*if($("input:checkbox:not(:checked)").length == $('input[type=checkbox]').length){
$('#totalcost,#checkedcount').val(0);
} else {*/
$('#checkedcount').val(s);
$('#totalcost').val((parseInt($('#quantity').val()) * s));
$('#totalcount').val($('#quantity').val());
//}
}
$('*[data-in="num"],#quantity').on('change', function() {
var sum = 0;
$('[data-in="num"]:checked').each(function() {
sum += parseInt($(this).val());
});
validate(sum);
myArray = storeArray();
//myArray Object containing all input values
//console.log(myArray);
//This is how get the quantity for example
//console.log(myArray['quantity']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div id="CheckBoxList">
<label><input type="checkbox" id='game0' value="1" name="Apple" data-d="b" data-in="num">Apple</label>
<label><input type="checkbox" id='game1' value="2" name="Orange" data-d="b" data-in="num">Orange</label>
<label><input type="checkbox" id='game2' value="3" name="Pineaple" data-d="b" data-in="num">Pineaple</label>
<label><input type="checkbox" id='game3' value="4" name="Lemon" data-d="b" data-in="num">Lemon</label>
<label><input type="checkbox" id='game4' value="5" name="Mango" data-d="b" data-in="num">Mango</label>
</div>
<div id="RadioButtonList">
<label><input type="radio" id='pad' value="6" data-d="b" name="HI" data-in="num">Small Cup</label>
<label><input type="radio" id='pad1' value="7" data-d="b" name="HI" data-in="num">Medium Cup</label>
<label><input type="radio" id='pad2' value="8" data-d="b" name="HI" data-in="num">Big Cup</label>
</div>
<div id="SelectOptions">
<select name="quantity" id="quantity" data-d="b">
<option value="0">Select quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<code id="demo"></code>
total cost<input type="text" id="totalcost" value="">
<br>total Checked<input type="text" id="checkedcount" value="">
<br>total boxes<input type="text" id="totalcount" value="">
<!-- partial -->
</form>

Try with this code:
function storeArray() {
var tab = [];
$('*[data-in="num"]:checked,#quantity').each(function(index) {
tab[index] = {
name: $(this).attr('name'),
value: parseInt($(this).val())
});
return tab;
}

Related

Convert CheckBoxList to Multiselect Dropdown

I am currently trying to figure out how to edit the below script to convert a list from a check list to a multi select drop down list if it is possible. Any help that can be offered is appreciated.
function checkCheckBoxList(oSrc, args) {
var isValid = false;
$("#<%= cklLocations.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
isValid = true;
});
args.IsValid = isValid;
}
You can map the checked checkboxes
const $dropdown = $("#dropdown");
const $checks = $("#cklLocations input[type='checkbox']").on("click", function() {
$dropdown[0].length = 1; // remove all but first
const opts = $("#cklLocations input[type='checkbox']:checked").map(function() {
return `<option value="${this.value}">${this.name}</option>`
}).get().join("")
$dropdown.append(opts)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cklLocations">
<label>A<input type="checkbox" name="A" value="a" /></label>
<label>B<input type="checkbox" name="B" value="b" /></label>
<label>C<input type="checkbox" name="C" value="c" /></label>
<label>D<input type="checkbox" name="D" value="d" /></label>
</div>
<select id="dropdown" multiple>
<option disabled>Please select</option>
</select>

How to change text based upon select id and radio name

I am bit lost over here.
I am trying to change the content of the id #total to "not eligible", if the user selects option in "countries" where the "data-class" is "false" and selects the radio "value" to "business". So if select is False and radio is business then change the #total to not eligible.
$(document).ready(function() {
$('.countries').change(function() {
var self = $(this).find('option:selected')
$('input:radio[name="service"]').change(
function() {
if ($(this).val() == 'Business' && self.attr("data-class") == 'False') {
return $('#total').text('Not Eligible')
}
}
).change()
}).change()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control countries">
<option value="AUSTRALIA" data-class="False" data-tx_1="63">AUSTRALIA</option>
<option value="USA" data-class="True" data-tx_1="65">USA</option>
<option value="GERMANY" data-class="True" data-tx_1="69">GERMANY</option>
</select>
<br><br>
<label for="id_service_0"><input type="radio" name="service" value="Economy" required id="id_service_0" />Economy</label>
<label for="id_service_1"><input type="radio" name="service" value="Business" required id="id_service_1" />Business</label>
<label for="id_service_2"><input type="radio" name="service" value="First" required id="id_service_2" />First</label>
<p>Total Price is <span id="total"></span></p>
I believe your code is indeed working. The reason you thinks it is not might be that you're not resetting the label text. See my snippet below. I've just added an "else" condition to your inner if statement.
$(document).ready(function() {
$('.countries').change(function() {
var self = $(this).find('option:selected')
$('input:radio[name="service"]').change(
function() {
if ($(this).val() == 'Business' && self.attr("data-class") == 'False') {
$('#total').text('Not Eligible')
}
else{
$('#total').text('Eligible')
}
}
).change()
}).change()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control countries">
<option value="AUSTRALIA" data-class="False" data-tx_1="63">AUSTRALIA</option>
<option value="USA" data-class="True" data-tx_1="65">USA</option>
<option value="GERMANY" data-class="True" data-tx_1="69">GERMANY</option>
</select>
<input type="radio" name="service" value="Economy" required id="id_service_0" />
<input type="radio" name="service" value="Business" required id="id_service_1" />
<input type="radio" name="service" value="First" required id="id_service_2" />
<p>Total Price is <span id="total"></span></p>
Have 2 separate change event
Check for value and compare
$(document).ready(function() {
$('.countries').change(function() {
var self = $(this).find('option:selected');
var inputvalue = $('input:radio[name="service"]:checked').val();
if (inputvalue == 'Business' && self.attr("data-class") == 'False') {
$('#total').text('Not Eligible')
} else {
$('#total').text('Eligible')
}
}).change()
$('input:radio[name="service"]').change(function() {
var self = $('.countries').find('option:selected');
var inputvalue = $('input:radio[name="service"]:checked').val();
if (inputvalue == 'Business' && self.attr("data-class") == 'False') {
$('#total').text('Not Eligible')
} else {
$('#total').text('Eligible')
}
}).change()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control countries">
<option value="AUSTRALIA" data-class="False" data-tx_1="63">AUSTRALIA</option>
<option value="USA" data-class="True" data-tx_1="65">USA</option>
<option value="GERMANY" data-class="True" data-tx_1="69">GERMANY</option>
</select>
<input type="radio" name="service" value="Economy" required id="id_service_0" />Economy
<input type="radio" name="service" value="Business" required id="id_service_1" />Business
<input type="radio" name="service" value="First" required id="id_service_2" />First
<p>Total Price is <span id="total"></span></p>

Set checkbox with Vue data

I have Vue data;
Like as app.$data.Result this result coming from server and it is just value(0-31) ;
I want to arrange my checkboxes with depend on this value;
This is checkboxes;
<div class="form-group">
<input class="checkbox" data-role="checkbox" data-caption="Issue1" id="ch1" value="1" />
<input class="checkbox" data-role="checkbox" data-caption="Issue2" id="ch2" value="2">
<input class="checkbox" data-role="checkbox" data-caption="Issue3" id="ch3" value="4" >
<input class="checkbox" data-role="checkbox" data-caption="Issue4" id="ch4" value="8">
<input class="checkbox" data-role="checkbox" data-caption="Issue5" id="ch5" value="16" >
</div>
I can set them by coming data with their using Id's
if (app.$data.Result == 1) {
$("#ch1").prop("checked", true);
}
But this way is too long because app.$data.Result can be like "3" and i must checked Issue1 and Issue2 also when User click any checkbox ,i need add/sub app.$data.Result so how can i solve this problem with Vue.
give you an example:
code updated,and the checkbox will be checked in 3 seconds
var app = new Vue({
el: '#app',
data () {
return {
list: new Array(5).fill('').map((o,i)=>i),
checked:[]
}
},
created () {
setTimeout(_=>{
//receive your data here
this.checked = [1,3]
},3000)
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<label v-for="i in list"><input type="checkbox" :value="i" v-model="checked">{{i}}</label>
{{checked}}
</div>
I implement like this and work but i am not sure that is clear solution;
<div class="form-group">
<input class="checkbox" data-role="checkbox" data-caption="Issue1" value="1" :checked="(data.Result& 1) === 1" />
<input class="checkbox" data-role="checkbox" data-caption="Issue2" value="2" :checked="(data.Result& 2) === 2">
<input class="checkbox" data-role="checkbox" data-caption="Issue3" value="4" :checked="(data.Result& 4) === 4" >
<input class="checkbox" data-role="checkbox" data-caption="Issue4" value="8" :checked="(data.Result& 8) === 8">
<input class="checkbox" data-role="checkbox" data-caption="Issue5" value="16" :checked="(data.Result& 16) === 16">
</div>
And when user change checkbox,result will be change and i handle it like this;
var sum = 0;
$("input:checked").each(function() {
sum += parseInt($(this).val(), 10);
});
data.Result = sum;

How Do I count the selected checkbox in AngularJS?

/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}

How set checked checkbox if it's value is in array

I have inputs:
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
And my javascript:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray($(this).val(), initValues)));
});
And now all my checkboxes are checked. How must I change my code to set checked for ckeckboxes which values are in initValues array?
$.inArray returns the index, not boolean. Also, parseInt your value because its considered as string when you pick it up.
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", $.inArray(parseInt($(this).val()), initValues) == -1 ? false : true );
});
let initValues = [1, 2, 3];
$('#my').find(':checkbox[name="names[]"]').each(function() {
if (initValues.some(v => v == $(this).val())) {
$(this).prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
You need to turn the value back into a number so it compares with the array value.
$.inArray(+$(this).val(), initValues))
Revised Example:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray(+$(this).val(), initValues)) != -1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
function printChecked(isChecked, value) {
const newProjectStages = projectstage.filter((p) => p !== value);
if (isChecked) {
newProjectStages.push(value);
}
Setprojectstage(newProjectStages);
var items = document.getElementsByName("tr");
var selectedItems = [];
for (var i = 0; i < items.length; i++) {
if (items[i].type == "checkbox" && items[i].checked == true)
selectedItems.push(items[i].value);
}
console.log("selected val", selectedItems);
Setselectedprostages(selectedItems);
}

Categories

Resources