How to send checkbox value: either true or false, through ajax - javascript

I want to send the value of my checkbox to database using ajax. Through some searching in internet, I somehow managed to get this far.This is what I have been using. What changes do I need to make on json2.stringify for it to correctly send my values.
Html:
<input type="checkbox" id="txtCategoryIsPaid" name="cateogryIsPaid" value="Paid">Yes<br>
Javascript:
AddCategory: function () {
BusinessManagement.config.method = "AddBusinessCategory";
BusinessManagement.config.url = BusinessManagement.config.baseURL + BusinessManagement.config.method;
BusinessManagement.config.data = JSON2.stringify({
CategoryIsPaid: $('#txtCategoryIsPaid :checked').val(),
});
BusinessManagement.config.ajaxCallMode = 0;
BusinessManagement.ajaxCall(BusinessManagement.config);

Use .prop('checked') attribute
<HTML>
<input type="checkbox" id="txtCategoryIsPaid" name="cateogryIsPaid" value="Paid">Yes<br>
Javascript
AddCategory: function () {
BusinessManagement.config.method = "AddBusinessCategory";
BusinessManagement.config.url = BusinessManagement.config.baseURL + BusinessManagement.config.method;
BusinessManagement.config.data = JSON2.stringify({
CategoryIsPaid: $('#txtCategoryIsPaid').prop('checked') == true ? "true": "false",
});
BusinessManagement.config.ajaxCallMode = 0;
BusinessManagement.ajaxCall(BusinessManagement.config);

Related

Make invalid form immediately after loading

I have a simple form written in AngularJS.
I would like to make the form invalid immediately after loading. Unfortunately $scope.myForm.$valid = false; doesn't want work. Do you have any other technique to do it? It is important for me as I want to let user click the button only when he/she choose at least on checkbox. Now you can submit the form always after loading the form.
<form name="myForm" ng-submit="myForm.$valid">
<input type="checkbox" ng-model="obj.first" ng-change="onChange()" /> First <br />
<input type="checkbox" ng-model="obj.second" ng-change="onChange()"/>Second <br />
<input type="checkbox" ng-model="obj.third" ng-change="onChange()"/> Third <br>
<button type="submit" ng-disabled="!myForm.$valid" ng-click="click()">test</button> <br>
</form>
$scope.myForm = {};
$scope.myForm.$valid = false;
$scope.click=function () {
console.log('-------------2', $scope.myForm);
};
$scope.onChange=function () {
console.log('before:', $scope.myForm);
var isValid = false;
angular.forEach($scope.obj, function(value, key) {
if(value == true){
isValid=true;
}
console.log(key + ': ' + value);
});
if(!isValid){
$scope.myForm.$valid = false;
$scope.myForm.$error.checkBoxes = {
isChecked: false
};
}
console.log('after:', $scope.myForm);
}
So this is my final solution, the form in the scope has a function called $setValidity() where we can change the validity state, and notify the form. Refer here, so I check if any of the checkboxes are having true value, then I set the value for one checkbox alone as true, if not then one of the checkboxes with name one is set to $valid = false, thus the entire form will be invalid, please go through my code for the implementation of the solution!
JSFiddle Demo
JS:
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.onChange = function() {
if ($scope.obj) {
if ($scope.obj.first || $scope.obj.second || $scope.obj.third) {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", true);
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
}
});
Try this in your submit button. hope it works
data-ng-disabled="myForm.$submitted || myForm.$invalid && !myForm.$pristine"

How to store add params in api url using angular js

my angular js function code
$scope.cardcall = function (cardtype) {
$scope.cityname=cityname;
$http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(function(data) {
$scope.deal = data.deals;
});
};
my view code
<div class="check_box" ng-repeat="cardtype in card.cardTypes.buckets">
<label>
<input type="checkbox" value=" {{cardtype.key}}" name="cardname" ng-click="cardcall(cardtype)" /> {{cardtype.key}}
</label>
</div>
now when some click on check box it call api like
/api/v1/asasas&filterBy=cardNames&filterByValue=asssas
What i am try to make when some one click 2nd check box then api call like
/api/v1/asasas&filterBy=cardNames&filterByValue=asssas,xsdza
You could add a .checked value to cardtype via ng-model
<input type="checkbox" ng-model="cardtype.checked" value=" {{cardtype.key}}" name="cardname" ng-change="typecall()" />
Then you could run a loop in your code to determine what's checked
$scope.cardcall = function () {
$scope.cityname=cityname;
var keys = [],
buckets = $scope.card.cardTypes.buckets;
for (var i = 0, len = buckets.length, i < len; i++) {
if (buckets[i].checked)
keys.push(buckets[i].key);
}
if (keys.length) {
keys = keys.join();
$http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue=' + keys}).success(function(data) {
$scope.deal = data.deals;
});
}
};
This will be called every time one of those checkboxes gets checked or unchecked and since it looks through all of the checkboxes there's no need to pass cardtype.key anymore. If no checkboxes are checked it won't do an AJAX call.

Get the value of checked checkbox?

So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.

How to serialize multiple checkbox values by jQuery?

I modified the simple example of jQuery.post as
$("#searchForm").submit(function(event) {
event.preventDefault();
var $form = $( this ),
term = $( "input[name^=tick]:checked" ).serialize(),
url = $form.attr( 'action' );
$.post( url, { ticks: term, id: '55' },
function( data ) {
$( "#result" ).empty().append( data );
}
);
});
This works for single checkbox with val() but not for multiple checkboxes in
<input type="checkbox" name="tick" value="'.$value.'" />
since serialize() should generateticks: termto be used astermin$.post`.
How can I make the serialize() to generate appropriate data for $.post
NOTE: I do not want to serialize the entire form but only checked values of checkbox INPUT.
Simple value collector :)
HTML
<input type="checkbox" class="selector" value="{value}"/>
JS
var checked='';
$('.selector:checked').each(function(){
checked=checked+','+$(this).val();
});
PHP
$ids=explode(',',substr($_GET['param_with_checked_values'],1));
You could use .serializeArray()
Ref: http://api.jquery.com/serializeArray/
In html code change name="tick" in name="tick[]" and you can use simply $(this).serialize(); to post all checked values.
You can still use .serializeArray and use it in .post() like this:
var postData = {};
var form = $('#formId').serializeArray();
for (var i = 0; i < form.length; i++) {
if (form[i]['name'].endsWith('[]')) {
var name = form[i]['name'];
name = name.substring(0, name.length - 2);
if (!(name in postData)) {
postData[name] = [];
}
postData[name].push(form[i]['value']);
} else {
postData[form[i]['name']] = form[i]['value'];
}
}
$.post('/endpoint', postData, function(response) {
}, 'json');
postData will contain all form elements except the disabled ones. All checkbox values will be passed as an array just like when doing a normal form submission.
let $form = $(".js-my-form");
let $disabled = $form.find(':input:disabled').removeAttr('disabled');
let formData = {};
$.each($form.serializeArray(), function (index, fieldData) {
if (fieldData.name.endsWith('[]')) {
let name = fieldData.name.substring(0, fieldData.name.length - 2);
if (!(name in formData)) {
formData[name] = [];
}
formData[name].push(fieldData.value);
} else {
formData[fieldData.name] = fieldData.value;
}
});
$disabled.attr('disabled', 'disabled');
console.log(formData);
Its a variation of Stanimir Stoyanov answer with possibility to serialize disabled fields.
term = $("#input[name^=tick]:checked").map(function () {
return this.value;
}).get();
term.join();

jQuery Validation using the class instead of the name value

I'd like to validate a form using the jquery validate plugin, but I'm unable to use the 'name' value within the html - as this is a field also used by the server app.
Specifically, I need to limit the number of checkboxes checked from a group. (Maximum of 3.) All of the examples I have seen, use the name attribute of each element. What I'd like to do is use the class instead, and then declare a rule for that.
html
This works:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation" value="1" />
This doesn't work, but is what I'm aiming for:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" />
javascript:
var validator = $(".formToValidate").validate({
rules:{
"salutation":{
required:true,
},
"checkBox":{
required:true,
minlength:3 }
}
});
Is it possible to do this - is there a way of targeting the class instead of the name within the rules options? Or do I have to add a custom method?
Cheers,
Matt
You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:
$(".checkBox").rules("add", {
required:true,
minlength:3
});
Another way you can do it, is using addClassRules.
It's specific for classes, while the option using selector and .rules is more a generic way.
Before calling
$(form).validate()
Use like this:
jQuery.validator.addClassRules('myClassName', {
required: true /*,
other rules */
});
Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules
I prefer this syntax for a case like this.
I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.
$.validator.addClassRules("price", {
required: true,
minlength: 2
});
This method does not require you to have validate method above this call.
Hope this will help someone in the future too. Source here.
Here's the solution using jQuery:
$().ready(function () {
$(".formToValidate").validate();
$(".checkBox").each(function (item) {
$(this).rules("add", {
required: true,
minlength:3
});
});
});
Here's my solution (requires no jQuery... just JavaScript):
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 4)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).
Here, I'll even give you a test page (paste it into a file and try it):
<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 3)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
</script></body></html>
Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.
On submit, find everything with class x, remove class x, add rule x.
$('#form').on('submit', function(e) {
$('.alphanumeric_dash').each(function() {
var $this = $(this);
$this.removeClass('alphanumeric_dash');
$(this).rules('add', {
alphanumeric_dash: true
});
});
});
If you want add Custom method you can do it
(in this case, at least one checkbox selected)
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" onclick="test($(this))"/>
in Javascript
var tags = 0;
$(document).ready(function() {
$.validator.addMethod('arrayminimo', function(value) {
return tags > 0
}, 'Selezionare almeno un Opzione');
$.validator.addClassRules('check_secondario', {
arrayminimo: true,
});
validaFormRichiesta();
});
function validaFormRichiesta() {
$("#form").validate({
......
});
}
function test(n) {
if (n.prop("checked")) {
tags++;
} else {
tags--;
}
}
If you need to set up multpile class rules you can do it like this:
jQuery.validator.addClassRules({
name: {
required: true,
minlength: 2
},
zip: {
required: true,
digits: true,
minlength: 5,
maxlength: 5
}
});
source: https://jqueryvalidation.org/jQuery.validator.addClassRules/
Disclaimer: Yes, I know it's 2021 and you shouldn't be using jQuery but, sometimes we have to. This information was really useful to me, so I hope to help some eventual random stranger who has to maintain some legacy system somewhere.
$(".ClassName").each(function (item) {
$(this).rules("add", {
required: true,
});
});

Categories