Set checkbox with Vue data - javascript

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;

Related

Disable a specific checkbox using Javascript

I would like to request assistance on how can I disable a specific checkbox.
Scenario:
If I clicked the 'Yes to all' checkbox - the other checkbox will be disabled (Q1 to Q4)
If I selected one or more on the Q1 to Q4 checkbox - 'Yes to all' checkbox will be disabled
Code:
$('input[type=checkbox]').change(function() {
if ($(this).is(':checked')) {
$('input[type=checkbox]').attr('disabled', true);
$(this).attr('disabled', '');
} else {
$('input[type=checkbox]').attr('disabled', '');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
You need to check weather the checkboxes selected or not as per your requirement,
Condition 1: if question selected length is more than 1, then disable the YTA
condition 2: if YTA is selected then disable all the Questions
If need anything else, please let me know.
$('.yta').change(function() {
if($('.yta:checked').length){
$('.q').attr('disabled', true);
}else {
$('.q').removeAttr("disabled");
}
});
$('.q').change(function() {
if($('.q:checked').length){
$('.yta').attr('disabled', true);
}else {
$('.yta').removeAttr("disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="q" type="checkbox" name="Q1" value="1" />Q1
<input class="q" type="checkbox" name="Q2" value="2" />Q2
<input class="q" type="checkbox" name="Q3" value="3" />Q3
<input class="q" type="checkbox" name="Q4" value="4" />Q4
<input class="yta" type="checkbox" name="QYTA" value="YTA" />Yes to all
My answer with my philosophy:
Avoid jQuery if you can
Use small functions that do one thing
Have in mind that the same should work when used multiple times in a document
Prevent magic values in your code
Encapsulate as much as possible
So this seems like overkill, but this works
{
function checkAnswers(qNames, allName) {
const qSelector = qNames.map(e => `[name="${e}"]`).join(',')
const allSelector = `[name="${allName}"]`
const selector = `${qSelector},${allSelector}`;
const getValue = () => Array.from(document.querySelectorAll(selector)).filter(e => e.checked).map(e => ({[e.name]: e.value}))
const checkQ = value => value.map(e => Object.keys(e)[0]).filter(value => qNames.includes(value)).length > 0;
const checkAll = value => value.map(e => Object.keys(e)[0]).includes(allName)
const qDisable = () => Array.from(document.querySelectorAll(qSelector)).forEach(e => e.disabled = true)
const qEnable = () => Array.from(document.querySelectorAll(qSelector)).forEach(e => e.disabled = false)
const allDisable =() => document.querySelector(allSelector).disabled = true
const allEnable = () => document.querySelector(allSelector).disabled = false
return e => {
if (!e.target.closest(selector)) {return}
const value = getValue();
if (checkQ(value)) {
allDisable();
} else if (checkAll(value)) {
qDisable()
} else {
allEnable();
qEnable();
}
}
}
let qNames = ['QA1','QA2','QA3','QA4']
let allName = 'QAYTA'
document.addEventListener('change', checkAnswers(qNames, allName))
qNames = ['QB1','QB2','QB3','QB4']
allName = 'QBYTA'
document.addEventListener('change', checkAnswers(qNames, allName))
}
:disabled + label {
color: lightgray;
}
<input type="checkbox" id="QA1" name="QA1" value="1"/><label for="QA1">Question 1</label><br>
<input type="checkbox" id="QA2" name="QA2" value="2"/><label for="QA2">Question 2</label><br>
<input type="checkbox" id="QA3" name="QA3" value="3"/><label for="QA3">Question 3</label><br>
<input type="checkbox" id="QA4" name="QA4" value="4"/><label for="QA4">Question 4</label><br>
<input type="checkbox" id="QAYTA" name="QAYTA" value="YTA"/><label for="QAYTA">Yes to all</label>
<br><br>
<input type="checkbox" id="QB1" name="QB1" value="1"/><label for="QB1">Question 1</label><br>
<input type="checkbox" id="QB2" name="QB2" value="2"/><label for="QB2">Question 2</label><br>
<input type="checkbox" id="QB3" name="QB3" value="3"/><label for="QB3">Question 3</label><br>
<input type="checkbox" id="QB4" name="QB4" value="4"/><label for="QB4">Question 4</label><br>
<input type="checkbox" id="QBYTA" name="QBYTA" value="YTA"/><label for="QBYTA">Yes to all</label>
You can do something like this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="q1_q4" type="checkbox" name="Q1" value="1"/>Q1
<input class="q1_q4" type="checkbox" name="Q2" value="2"/>Q2
<input class="q1_q4" type="checkbox" name="Q3" value="3"/>Q3
<input class="q1_q4" type="checkbox" name="Q4" value="4"/>Q4
<input class="yta" type="checkbox" name="QYTA" value="YTA"/>Yes to all
<script>
$(".q1_q4").on('change', function(){
$(".yta").attr("disabled","disabled");
});
$(".yta").on('change', function(){
$(".q1_q4").attr("disabled","disabled");
});
</script>
See the perfect answer.
$('input[type=checkbox]').change(function() {
if ($(this).is('input[name="QYTA"]')) {
if ($(this).is(':checked')) {
$('input[type=checkbox][name!="QYTA"]').attr('disabled', true);
} else {
$('input[type=checkbox][name!="QYTA"]').attr('disabled', false);
}
} else {
if ($(this).is(':checked')) {
$('input[type=checkbox][name="QYTA"]').attr('disabled', true);
} else if($('input[type=checkbox][name!="QYTA"]:checked').length == 0) {
$('input[type=checkbox][name="QYTA"]').attr('disabled', false);
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
You can use the .prop function in jQuery to add and remove the disabled attribute easily. You would need to refine the selectors if you are using other checkboxes on the same page.
$('input[type=checkbox]').change(function() {
if (this.name == "QYTA" && this.checked) {
$('input[type=checkbox][name!="QYTA"]').prop("disabled", true);
} else if (this.name != "QYTA" && this.checked) {
$('input[type=checkbox][name="QYTA"]').prop("disabled", true);
} else {
$('input[type=checkbox]').prop("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
My solution is to set up onchange event handler for each checkbox.
And then depending on the element which triggered the onchange event to perform a different operation.
if QYTA trigger the onchange then disable the Q1 to Q4 checkbox.
Else
disable the QYTA checkbox.
I make use of the logic difference between the checked and disabled attribute.
Here is my solution:
$("input[type='checkbox']").each(function() {
$(this).on('change', function() {
if (this.name=='QYTA'){
for (let i=1;i<5;i++){
$("input[type='checkbox'][name='Q"+i+"']").attr('disabled', this.checked);
}
} else{
$("input[type='checkbox'][name='QYTA']").attr('disabled', this.checked);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1"/>Q1
<input type="checkbox" name="Q2" value="2"/>Q2
<input type="checkbox" name="Q3" value="3"/>Q3
<input type="checkbox" name="Q4" value="4"/>Q4
<input type="checkbox" name="QYTA" value="YTA"/>Yes to all
hope help u
$("input[type='checkbox']").each(function(){
$(this).on('click', function(){
var el = $("input[type='checkbox']").not($("input[name='QYTA']"));
var elAl = $("input[name='QYTA']");
if($(this).not(elAl).length == 0) {
if(elAl.is(':checked')){
el.attr('disabled',true);
} else {
$("input[type='checkbox']").removeAttr("disabled");
}
} else if(el.is(':checked')){
elAl.attr('disabled',true);
} else {
$("input[type='checkbox']").removeAttr("disabled");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1"/>Q1
<input type="checkbox" name="Q2" value="2"/>Q2
<input type="checkbox" name="Q3" value="3"/>Q3
<input type="checkbox" name="Q4" value="4"/>Q4
<input type="checkbox" name="QYTA" value="YTA"/>Yes to all

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);
}

Javascript: How to check only one item in checkbox

Please help, I failed to code the checkbox that can only checked 1 item. Any help would be appreciated. Thanks
Html
<input type="checkbox" name="<%=Name %>" onClick="return checkbox(this)" >
Javascript
function checkbox(a) {
var Count = 0;
if (a.checked)
{
Count = Count + 1;
}
if (Count == 2)
{
alert('choose One Please');
return false;
}
}
You are declaring count inside a method hence it will always be initialised to 0 when you click on check box. Hence declare count globally and maintain the count.
var NewCount = 0;// global declaration
function KeepCount(a){
if (a.checked){
NewCount = NewCount + 1;
}else{
NewCount = NewCount - 1;
}
if(NewCount>1){
alert('Pick Just One Please');
return false;
}
}
UPDATE:
Another approach if you don't want to add variable globally:
HTML
Group 1
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<br/>
Group 2
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
JavaScript
function addClassCheck(element){
if(element.checked){
element.classList.add("marked");
}else{
element.classList.remove("marked");
}
if(document.getElementsByClassName("marked").length>1){
alert("Please select only one check box");
element.checked=false;
element.classList.remove("marked");
}
}
Fiddle demo
Group your checkboxs as
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<br/>
Group 2
<input type="checkbox" class="radio" value="1" name="test[2][]" />
<input type="checkbox" class="radio" value="1" name="test[2][]" />
<input type="checkbox" class="radio" value="1" name="test[2][]" />
Query
$("input:checkbox").click(function() {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
DEMO

Save result checkboxes checked in form into sqlite database with javascript

I have a form in my app with several checkboxen. I want the result(value) of the checked checkedboxes saved into separate rows in the database, see below. The problem is that when saving, only the first one (Ma) is saved and the other ones not eventhough the are checked in the form. When MA is not checkend nothing happens at all... I use JqueryMobile/JavaScript/PhoneGap Build
Form:
<form name="test">
<label class="label_check" id="l1" for="ch1">Ma
<input class="custom" type="checkbox" name="checkgroup" id="ch1" value="Ma" />
</label>
<label class="label_check" id="l2" for="ch2">Di
<input class="custom" type="checkbox" name="checkgroup" id="ch2" value="Di" checked />
</label>
<label class="label_check" id="l3" for="ch3">Woe
<input class="custom" type="checkbox" name="checkgroup" id="ch3" value="Woe" />
</label>
<label class="label_check" id="l4" for="ch4">Do
<input class="custom" type="checkbox" name="checkgroup" id="ch4" value="Do" />
</label>
<label class="label_check" id="l5" for="ch5">Vr
<input class="custom" type="checkbox" name="checkgroup" id="ch5" value="Vr" checked />
</label>
<label class="label_check" id="l6" for="ch6">Za
<input class="custom" type="checkbox" name="checkgroup" id="ch6" value="Za" />
</label>
<label class="label_check" id="l7" for="ch7">Zo
<input class="custom" type="checkbox" name="checkgroup" id="ch7" value="Zo" />
</label>
</form>
</p>
<p>
<input type="button" name="saveData" id="btn1" value="Save" onclick="saveRecordSafety();"/>
Javascript:
function saveRecordSafety() {
//Write the record to the database
theDBbeter.transaction(insertRecordSafety, onTxErrorB, onTxSuccessB);
}
function insertRecordSafety(txb) {
var elementen = document.getElementsByName ("checkgroup");
var tmpChoise;
for (var r= 0; r < elementen.lenght; r++);
if (elementen[r].checked) {
tmpChoise = elementen[r].value;
alert(tmpChoise);
var sqlStrB = 'INSERT INTO testSafetyBeter (beter) VALUES (?)';
txb.executeSql(sqlStrB, [tmpChoise], onSqlSuccess, onSqlError);
}
}
I think the problem is because of your for loop being terminated by a semicolon:
for (var r= 0; r < elementen.lenght; r++);
Try this:
function insertRecordSafety(txb) {
var elementen = document.getElementsByName ("checkgroup");
var tmpChoise;
for (var r= 0; r < elementen.length; r++)
{
if (elementen[r].checked)
{
tmpChoise = elementen[r].value;
alert(tmpChoise);
var sqlStrB = 'INSERT INTO testSafetyBeter (beter) VALUES (?)';
txb.executeSql(sqlStrB, [tmpChoise], onSqlSuccess, onSqlError);
}
}
}
I've also spaced things out to make it easier to read.

Categories

Resources