how retrieve the value from checkbox buttons on Bootstrap 4? - javascript

I Am using Bootstrap's button plugin for my buttons, currently I have 6 Checkbox buttons and I need a Method to retrieve the value of every checked button to make some calculations. But I cannot figure how, I tried searching here And found a pretty good way but for Radio Buttons and for a single checkbox but didn't find any for multiple.
how can I make a Jquery method for sweeping the btnGroup elements and retrieve all the checked values in an array?
Please help!!
PS. I Am not native English speaker and I Am pretty new to Jquery, so sorry if its a noob question.
Example Html:
<div class="btn-toolbar btn-group-toggle" data-toggle="buttons id="btnGroup">
<div class="col-auto">
<label class="btn btn-outline-info">
<input type="checkbox" name="btn1" id="" autocomplete="off" value="value1">value1</label>
</div>
<div class="col-auto">
<label class="btn btn-outline-info">
<input type="checkbox" name="btn2" id="" autocomplete="off" value="value2">value2</label>
</div>
<div class="col-auto">
<label class="btn btn-outline-info">
<input type="checkbox" name="btn3" id="" autocomplete="off" value="value3">value3</label>
</div>
</div>

You can use this selector:
$("#btnGroup input[type='checkbox']:checked")
To get all the checked checkboxes in the div with the id btnGroup. You can then use .each() to loop over all the checked boxes and use destructuring assignment to get the value of each checked box.
Here I have logged out each value as an example.
See example below:
let values = [];
$('.calculate').click(_ => {
values = [];
$("#btnGroup input[type='checkbox']:checked").each((_, {value}) => {
values.push(value);
});
console.log(values);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-toolbar btn-group-toggle" data-toggle="buttons" id="btnGroup">
<div class="col-auto">
<label class="btn btn-outline-info">
<input type="checkbox" name="btn1" id="" autocomplete="off" value="value1">value1</label>
</div>
<div class="col-auto">
<label class="btn btn-outline-info">
<input type="checkbox" name="btn2" id="" autocomplete="off" value="value2">value2</label>
</div>
<div class="col-auto">
<label class="btn btn-outline-info">
<input type="checkbox" name="btn3" id="" autocomplete="off" value="value3">value3</label>
</div>
</div>
<button class="calculate btn btn-primary btn-lg">Calculate</button>

Related

Cannot read property 'split' of undefined (debugging issue)

I am having difficulty figuring out the following error:
Uncaught TypeError: Cannot read property 'split' of undefined
The HTML:
<div id="content" class="col-xs-12 col-sm-12">
<p>Please select your preferred payment method.</p>
<div class="radio">
<label>
<input type="radio" name="payment_method" value="authorizenet" checked="checked">
Credit Card/Debit Card (Authorize.Net) </label>
</div>
<div class="radio">
<label>
<input type="radio" name="payment_method" value="affirm">
Credit Card/Debit Card (Affirm) </label>
</div>
<p><strong>Add comments about your order.</strong></p>
<p>
<textarea name="comment" rows="8" class="form-control"></textarea>
</p>
<div class="cart-module">
<div class="cart-content">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<h4 for="input-coupon">Coupon Code</h4>
<div class="input-group">
<input type="text" name="coupon" value="" placeholder="Coupon Code" id="input-coupon" class="form-control">
<span class="input-group-btn">
<input type="button" value="Apply" data-code="coupon" data-loading-text="Loading..." class="btn btn-primary">
</span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<h4 for="input-voucher">Gift Certificate Code</h4>
<div class="input-group">
<input type="text" name="voucher" value="" placeholder="Gift Certificate Code" id="input-voucher" class="form-control">
<span class="input-group-btn">
<input type="button" value="Apply" data-code="voucher" data-loading-text="Loading..." class="btn btn-primary">
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="buttons">
<div class="pull-right">I have read and agree to the <b>Shipping and Returns</b>. <input type="checkbox" name="agree" value="1">
<input type="button" value="Continue" id="button-payment-method" data-loading-text="Loading..." class="btn btn-primary">
</div>
</div>
The Script:
var newtext = "affirm";
selector = $("input[type=radio][value=affirm]").closest("label");
var line = selector.html().split(">")[0] + ">" + newtext;
selector.html(line);
The Goal:
I have two radio buttons on the checkout page.
Credit Card/Debit Card (Authorize.Net)
Credit Card/Debit Card (Affirm)
I am unable to edit the HTML directly. Thus rebuilding the html line with the above code to give me the output I want. I am trying to change the HTML text of the 2nd radio input to just "Affirm".
The script works in a fiddle, but not on the page.
I once encountered a similar bug when trying to maintain a page without access to the source files. I was using jQuery to attempt to delete a p element sentence but was coming up undefined because it was running on the homepage before the application even got to generate that part of the html. It was an SPA. I fixed it by adding a listener on the document to the router something along like this: $(document).on("pageshow", "#checkoutPage", function() {//your jquery function});
I tried it both on CodePen and locally with VS Code and both time I got the intended effect. Have you tried maybe making sure youre using the right version of JQuery and that is linked to the html in the proper oder, also debugging via console logs? See below:
CodePen
enter code here

How to structure, multiple single page forms and handle them in nodejs

I have an html form using express-handlebars inside a loop that gets rendered a certain amount of times based off how many users there are assigned to a group.
So if there are 5 users the below code between the "#Each" gets loaded 5 times.
How do I structure this so that I can Post it back to node and write it to mongoDB in terms of what I use for the id and name.
I couldn't find anything related, if there's anything on here, please link it :)
<form action="/users/rsvp" method="POST">
{{#each docs}}
<div class="card border-secondary mb-3">
<div class="card-header"></div>
<div class="card-body">
<h4 class="card-title">{{this.name}}</h4>
<div class="form-check">
<input class="form-check-input" type="radio" value="1" id="{{this._id}}"
name="{{this._id}}">
<label class="form-check-label" for="{{this.id}}">
Attenting
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" value="0" id="{{this._id}}"
name="{{this._id}}">
<label class="form-check-label" for="{{this._id}}">
Not Attenting
</label>
</div>
<div class="form-group">
<label for="DietaryRequirements"></label>
<input type="text" id="DietaryRequirements" name="DietaryRequirements" class="form-control"
placeholder="Dietary Requirements" />
</div>
</div>
</div>
{{/each}}
<button type="submit" class="btn btn-primary btn-block">
RSVP
</button>
</form>
With your code, all the users' form are rendered within 1 <form>, which will cause a lot of duplicate fields on DietaryRequirements and of course the server cannot figure out which field is for which user. You can simply break it up so that each user has a separate , and pass the user's ID through a hidden input. E.g.:
{{#each docs}}
<form action="/users/rsvp" method="POST">
<!-- Your Form Content, name=attending and name=dietaryRequirements -->
<input type="hidden" value="{{this._id}}">
<button type="submit" class="btn btn-primary btn-block">
RSVP
</button>
</form>
{{/each}}
OR
If you really want a single form for the whole group of user, you can utilize the extended setting on body parser, which allows submission of nested object through HTML, in that case you write something similar to:
<form action="/users/rsvp" method="POST">
{{#each docs}}
<div class="card border-secondary mb-3">
<div class="card-header"></div>
<div class="card-body">
<h4 class="card-title">{{this.name}}</h4>
<div class="form-check">
<input class="form-check-input" type="radio" value="1" id="user-{{this._id}}-attending"
name="user[{{this._id}}][attending]">
<label class="form-check-label" for="user-{{this._id}}-attending">
Attenting
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" value="0" id="user-{{this._id}}-not-attending"
name="user[{{this._id}}][attending]">
<label class="form-check-label" for="user-{{this._id}}-not-attending">
Not Attenting
</label>
</div>
<div class="form-group">
<label for="user-{{this._id}}-dietary"></label>
<input type="text" id="user-{{this._id}}-dietary" name="user[{{this._id}}][dietaryRequirements]" class="form-control"
placeholder="Dietary Requirements" />
</div>
</div>
</div>
{{/each}}
<button type="submit" class="btn btn-primary btn-block">
RSVP
</button>
</form>
Notice the name s has a notation of a[b][c], and also the id and for should have unique pairings on each page which have been fixed as well.
If you have set body parser extended to true, you should get for req.body:
{
user: {
'10': {
attending: '1',
dietaryRequirements: 'Meaty'
},
'11': {
attending: '0',
dietaryRequirements: 'N/A'
}
}
}

How to check which checkbox is checked and save the data into database using Angular

I have 4 different checkboxes and when I check one(or two, or three, or all) I want to save some data into a database with a click on the button "Save". I'm using angular.
How I can do this?
I have this HTML code:
<div class="addMode1" style="display: none;">
<div class="form">
<form ng-submit="createReason(reasonsForm1.$valid)" name="reasonsForm1">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="database_address">Name of reason:</label>
<input type="text" class="form-control" ng-model="reasonname" placeholder="Име основание за добавяне" />
</div>
<div class="container">
<p>Using in::</p>
<input type="checkbox" ng-model="all">Buy<br>
<input type="checkbox" ng-checked="all">Sell<br>
<input type="checkbox" ng-checked="all">PKO<br>
<input type="checkbox" ng-checked="all">RKO
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-primary" id="cnlbtn1" type="button">Cancel</button>
<!--ng-click="createUser()"-->
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
And Angular code(createReason function which saves data from input box into the database):
$scope.createReason=function()
{
var objectToSave = {
name: $scope.reasonname,
};
defaultAdapter.query('INSERT INTO reasons(name) VALUES(:name)',
{ replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
).then(projects => {
console.log(projects);
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh();
});
}
Please help me.
Thanks!
enter image description here
<label><input type="checkbox" name="test" ng-model="testModel['item1']" /> Testing</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3</label><br />
After this on submit check the testModel index value which one is true or false then send that value in database.
try this i hope its helpful to you

Closing Dynamically created DIV

So I have a section to add a color and I got it to dynamically create a copy of the div with a new ID for each dynamic div.
The problem is that once the div is created, I don't know how to close it (i.e. remove it from DOM via a "close" action). I know it's because it's dynamic content. You cant bind event likes the static content, it's will not bind to the elements because they don't appear at the time you bind. I just don't know how to go about getting it to close.
The div I want to close starts with "Color" + incremented number. I hope I explained this correctly and any help would be appreciated. Thanks.
<div class="col-xs-12" style="max-width: 800px">
<div class="col-md-12">
<h3>COLOR ROTATION</h3>
<!--Begin color rotation well-->
<div id="color">
<div class="well well-sm">
<div class="row">
<div class="col-md-6">
<div class="form-group"><a><span class="glyphicon glyphicon-remove-sign" aria-hidden="true" style="padding-right: 2px;"></span></a>
<label class="control-label">Color 1</label>
<input class="form-control" maxlength="100" placeholder="Enter Color" required="required" type="text" />
</div>
</div>
<div class="col-md-6">
<label class="control-label">DROPDOWNS REQUIRED?</label>
<div class="form-inline">
<div class="radio">
<label>
<input name="optradio" type="radio" />Yes</label>
</div>
<div class="radio">
<label>
<input name="optradio" type="radio" />No</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End color rotation well-->
</div>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span><a id="addcolor">Add Color</a>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
Here's the link to the working example:
jsfiddle
Sure, see this updated fiddle;
Essentially you want to bind an event to the document using .on(), like:
$(document).on('click', '.remove', function(e){
$(this).closest('.color-wap').remove();
});
I added the .color-wrap class to the #color div to avoid working with duplicated ID's via cloning, and added the .remove class to the remove button
1)Use the .on() to bind events on dynamically created elements
2)jquery selector ^ can help in selecting the div with id of color-number.
3).animate() to toggle height of the div or .remove if you want to completly remove the element.
$(function() {
var count = 0;
$('#addcolor').click(function() {
count++;
var clonediv = $('#color');
$(clonediv).clone().insertBefore('#color');
$(clonediv).attr("id", "color" + count);
});
$(document).on("click", ".glyphicon-remove-sign", function() {
$(this).closest("div[id^='color']").animate({"height":"toggle"});
//$(this).closest("div[id^='color']").remove();
})
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12" style="max-width: 800px">
<div class="col-md-12" id="test">
<h3>COLOR ROTATION</h3>
<!--Begin color rotation well-->
<div id="color">
<div class="well well-sm">
<div class="row">
<div class="col-md-6">
<div class="form-group"><a><span class="glyphicon glyphicon-remove-sign" aria-hidden="true" style="padding-right: 2px;"></span></a>
<label class="control-label">Color 1</label>
<input class="form-control" maxlength="100" placeholder="Enter Color" required="required" type="text" />
</div>
</div>
<div class="col-md-6">
<label class="control-label">DROPDOWNS REQUIRED?</label>
<div class="form-inline">
<div class="radio">
<label>
<input name="optradio" type="radio" />Yes</label>
</div>
<div class="radio">
<label>
<input name="optradio" type="radio" />No</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End color rotation well-->
</div>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span><a id="addcolor">Add Color</a>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>

Checked state for buttons Bootstrap

I want to have a checked state for group chexboxes in Bootstrap 3.0.2. docs
html:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="checkbox" name="123" data-toggle="button"> <span class="glyphicon glyphicon-star"></span> 123
</label>
<label class="btn btn-default">
<input type="checkbox" name="456"> <span class="glyphicon glyphicon-star-empty"></span> 456
</label>
</div>
But data-toggle="button" doesnt works. jsfiddle
How to fix it? Thanks.
To actually check the input, you will need to add the checked property. This will not actually make it appear checked, but is important if you are using this in a form and actually want the input to be checked by default.
<input type="checkbox" name="123" data-toggle="button" checked>
To make it look checked (or pressed), add class .active to the .btn label wrapping it.
<label class="btn btn-default active">
http://jsfiddle.net/ZktYG/2/
Not sure why data-toggle="buttons" isn't working. Could be related to this: https://github.com/twbs/bootstrap/issues/8816
For now, you can achieve the same effect through JS by doing something like:
$('.btn-group').on('input', 'change', function(){
var checkbox = $(this);
var label = checkbox.parent('label');
if (checkbox.is(':checked')) {
label.addClass('active');
}
else {
label.removeClass('active');
}
});
It's been a couple of years; however, I wanted to address the actual problem above of why the data-toggle="button" wasn't working.
The answer was to remove the data-toggle="button" on the <input>'s.
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="checkbox" name="123"> 123
</label>
<label class="btn btn-default">
<input type="checkbox" name="456"> 456
</label>
</div>
I solved this by making a custom attribute that housed whether it was active or not, then setting that value within JQuery's click event.
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active check_button" id="check1">
<input type="checkbox" autocomplete="off" checked data-checked=true> Checkbox 1 (pre-checked)
</label>
<label class="btn btn-primary check_button" id="check2">
<input type="checkbox" autocomplete="off" data-checked=false> Checkbox 2
</label>
<label class="btn btn-primary check_button" id="check3">
<input type="checkbox" autocomplete="off" data-checked=false> Checkbox 3
</label>
</div>
You can see a working example of this within the fiddle,
https://jsfiddle.net/jeffbeagley/DTcHh/34024/

Categories