I would like to detect when a button is clicked in a div which has multiple buttons which act like checkboxes for mobile optimized application.
This is what I have as HTML:
When it was only normal checkboxes instead of button like checkboxes I was able to achieve what I want with this script:
$(document).on('change', 'input:checkbox.modifier', function () {
var totalChecked = $("#modifiersDiv :checkbox:checked").size();
var maximum = parseInt($('#Maximum').val());
if (totalChecked === maximum) {
$("#modifiersDiv :checkbox:not(:checked)").attr("disabled", true);
} else {
$("#modifiersDiv :checkbox:not(:checked)").attr("disabled", false);
}
});
Now I'm trying something like this just to see if the function will be triggered at all but without success:
$(document).on('click', 'input:button.modifier', function () {
});
Bottom line is that I want to detect with jQuery when 5 buttons are selected then I will need to disable the other buttons in the div until the user will not deselect some button.
Update
Code I'm using for the button:
var startDiv = "<div class='btn-group btn-block' data-toggle='buttons'>";
var checkBox = '';
$.each(data.modifierOptions, function(key, item) {
checkBox += "<label class='btn btn-checkbox btn-block' style='margin-bottom:2px;'><input type='checkbox' data-quantity='1' class='modifier' data-itemid='" + itemid + "' data-name='" + item.Name + "' data-price='" + item.Price + "' name='" + item.Name + "' value='" + item.ID + "'/>" + item.Name + " </label><br />";
});
var endDiv = "</div>";
var totalDiv = startDiv + checkBox + endDiv;
$(totalDiv).appendTo('#modifiersDiv');
I read over your question, and you weren't far off in your attempt. I put together a pen to demonstrate how you can do this: http://codepen.io/aecend/pen/mjklu
The checkbox inputs aren't being replaced with button elements, the labels are only styled so that they appear to be buttons. In the jQuery, you would still need to use the checkbox selector and instead of disabling the checkboxes themselves (there's no point, they're hidden), simply add the "disabled" class to the other labels once five options are selected.
Here's the HTML I used, I only added the btn-default class to make the buttons more visible:
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<title>Hamburger Builder v2.0</title>
</head>
<body class="sitecolor">
<div id="modifiersDiv" class="modal-div" style="width: 250px; margin: 0 auto;">
You can select a maximum of 5 option(s)
<br>
<div class="btn-group btn-block" data-toggle="buttons">
<label class="btn btn-default btn-checkbox btn-block" style="margin-bottom: 2px;">
<input class="modifier" type="checkbox" value="67739" name="Bacon" data-price="1" data-name="Bacon" data-itemid="a4007375-e037-46ce-be39-57ca2d1872e0" data-quantity="1">
Bacon
</label>
<br>
<label class="btn btn-default btn-checkbox btn-block" style="margin-bottom: 2px;">
<input class="modifier" type="checkbox" value="67740" name="Lettuce" data-price="1" data-name="Lettuce" data-itemid="a4007375-e037-46ce-be39-57ca2d1872e1" data-quantity="1">
Lettuce
</label>
<br>
<label class="btn btn-default btn-checkbox btn-block" style="margin-bottom: 2px;">
<input class="modifier" type="checkbox" value="67741" name="Tomato" data-price="1" data-name="Tomato" data-itemid="a4007375-e037-46ce-be39-57ca2d1872e2" data-quantity="1">
Tomato
</label>
<br>
<label class="btn btn-default btn-checkbox btn-block" style="margin-bottom: 2px;">
<input class="modifier" type="checkbox" value="67742" name="Cheese" data-price="1" data-name="Cheese" data-itemid="a4007375-e037-46ce-be39-57ca2d1872e3" data-quantity="1">
Cheese
</label>
<br>
<label class="btn btn-default btn-checkbox btn-block" style="margin-bottom: 2px;">
<input class="modifier" type="checkbox" value="67743" name="Onions" data-price="1" data-name="Onions" data-itemid="a4007375-e037-46ce-be39-57ca2d1872e4" data-quantity="1">
Onions
</label>
<br>
<label class="btn btn-default btn-checkbox btn-block" style="margin-bottom: 2px;">
<input class="modifier" type="checkbox" value="67744" name="Pickles" data-price="1" data-name="Pickles" data-itemid="a4007375-e037-46ce-be39-57ca2d1872e5" data-quantity="1">
Pickles
</label>
<br>
</div>
</div>
</body>
and here is the snippet of JavaScript you'll need, it's almost exactly what you had, except Bootstrap-ready now:
$(document).on('change', 'input:checkbox.modifier', function () {
var totalChecked = $("#modifiersDiv :checkbox:checked").size();
var maximum = 5; //parseInt($('#Maximum').val())
if (totalChecked === maximum) {
$(this).parent().siblings(":not(.active)").addClass("disabled");
} else {
$("#modifiersDiv label.disabled").removeClass("disabled");
}
});
Add a class to the selected buttons, and on each click count the number of buttons that are checked at that moment:
$(".button:not(.selected)").click(function(){
$(this).addClass("selected");
if($(".button.select").length>4){
$(".button").addClass("disabled");
}
}
You might want to add something that will also de-select a button once it's clicked twice...
Try this :))))
var count=0;
$("#modifiersDiv").find(".modifier").click(function(){
if($(this).is(":checked")){
count++;
}else{
count--;
}
if(count>=$('#Maximum').val())
$("#modifiersDiv").find(".modifier").not(':checked').attr("disabled", true);
else
$("#modifiersDiv").find(".modifier").not(':checked').attr("disabled", false);
});
Related
I have managed to come up with the following JavaScript and HTML but now I am stuck. I want to be able to add an id="" attribute to the fields and have them numbered as I add more fields with the '+ Add' button.
I've been playing around with this but have not had any success yet. Could someone give me some suggestions or offer some solutions to this issue?
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><table width="100%"><tr><td><input type="text"
name="field_name[]" value="" class="form-control" style="width:98%;"
placeholder="Role"/></td><td><input type="text" name="field_name[]" value=""
class="form-control" style="width:100%;" placeholder="Name"/></td></tr></table>
<a href="javascript:void(0);" class="remove_button"><button type="button"
class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> -
Remove </button></a></div>';
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%"/>
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%"/>
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field">
<button style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role </button>
</a>
</div>
</div>
You can try this snippet:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
$(document).ready(function () {
var x = 1; //Initial field counter is 1
var idCounter = 0;
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
function fieldHTML(id) {
return '<div><table width="100%"><tr><td>id:' + id + '<input type="text"' +
'id="role-' + id + '" name = "field_name[]" value = "" class="form-control" style = "width:98%;"' +
'placeholder = "Role" /></td > <td><input type="text" id="name-' + id + '" name="field_name[]" value=""' +
'class="form-control" style="width:100%;" placeholder="Name" /></td></tr ></table >' +
'<a href="javascript:void(0);" class="remove_button"><button type="button"' +
'class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> - Remove </button></a></div >';
}
//Once add button is clicked
$(addButton).click(function () {
//Check maximum number of input fields
if (x < maxField) {
$(wrapper).append(fieldHTML(idCounter++)); //Add field html
x++; //Increment field counter
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<label style="margin-top:70px;">Credits</label>
<div class="field_wrapper">
<div class="form-group">
<table width='100%'>
<tr>
<td>
<input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%" />
</td>
<td>
<input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%" />
</td>
</table>
<a href="javascript:void(0);" class="add_button" title="Add field"><button
style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role
</button></a>
</div>
</div>
Note, I have created a new variable idCounter to keep the id unique even when you remove a row. Otherwise, it might create elements with duplicate ids.
This is just one quick way, but there are many other ways this can be achieved. The code can be made mode tidy and readable.
I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>
I have a piece of somewhat-messy jquery in my app to assign values to the tax, shipping, and total fields of a hidden form before checkout. I have it working mostly, but for some reason if you click "Yes, I live in Colorado" (which will assign a $9ish state tax), the total doesn't get added up properly (the tax isn't added in), even though the tax does get shown.
I added a css-lite snippet that does replicate the problem. Just click "Yes I live in CO", then "See Shipping Options" and "Calculate Total".
$(document).ready(function(){
var $subtotal = $("#hfSubtotal").val();
$(".footer").removeClass("top-shadow-inset");
$(".choiceYesCO").click(function(){
$(".choice-box").removeClass("active");
$(".icon-choice").removeClass("ion-ios-checkmark-outline ion-ios-circle-outline")
$(".choice-no-co").addClass("ion-ios-circle-outline")
$(".choice-yes-co").addClass("ion-ios-checkmark-outline")
$(this).addClass("active");
var $tax = parseFloat($subtotal * .0463).toFixed(2);
$("#hfTax").val($tax);
$(".fieldTax").html("Tax: $" + $tax);
});
$(".choiceNoCO").click(function(){
$(".choice-box").removeClass("active");
$(".icon-choice").removeClass("ion-ios-checkmark-outline ion-ios-circle-outline")
$(".choice-no-co").addClass("ion-ios-checkmark-outline")
$(".choice-yes-co").addClass("ion-ios-circle-outline")
$(this).addClass("active");
var $tax = parseFloat(0.00).toFixed(2);
$("#hfTax").val($tax);
$(".fieldTax").html("Tax: $" + $tax);
});
$(".submitTax").click(function(){
$(".stepTax").addClass("hidden");
$(".stepShipping").removeClass("hidden");
$(".fieldTax").removeClass("hidden");
});
var $tax = $("#hfTax").val();
$(".submitShipping").click(function(){
var $shipping = parseFloat(0.00).toFixed(2);
$("#hfShipping").val($shipping);
$(".fieldShipping").html("Shipping: $" + $shipping);
var $total = parseFloat($subtotal).toFixed(2); + parseFloat($tax).toFixed(2); + parseFloat($shipping).toFixed(2);
$("#hfTotal").val($total);
$(".fieldTotal").html("<strong>Total: $" + $total + "</strong>");
$(".stepShipping").addClass("hidden");
$(".stepTotal").removeClass("hidden");
$(".fieldShipping").removeClass("hidden");
$(".fieldTotal").removeClass("hidden");
});
$(".submitTotal").click(function(){
$(".edit_order").submit();
});
});
.btn {
display: block;
background-color: red;
padding: 5px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stepTax">
<h3>Do you live in Colorado?</h3>
<div class="choiceYesCO choice-box"><h4><i class="icon choice-yes-co icon-choice ion-ios-circle-outline"></i>Yes, I live in Colorado.</h4></div>
<div class="choiceNoCO choice-box"><h4><i class="icon choice-no-co icon-choice ion-ios-circle-outline"></i>No, I don't live in Colorado.</h4></div>
<div class="btn submitTax">See Shipping Options</div>
</div>
<div class="stepShipping hidden">
<h3>Shipping Options Go Here</h3>
<p>For now all shipping is free!</p>
<div class="btn submitShipping">Calculate Total</div>
</div>
<div class="stepTotal hidden">
<h3>You're ready to checkout!</h3>
<div class="btn submitTotal">Checkout</div>
</div>
<form novalidate="novalidate" class="simple_form edit_order" id="edit_order_1" enctype="multipart/form-data" action="/orders/1" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="_method" value="patch" /><input type="hidden" name="authenticity_token" value="6P1CzQgCx7JVXAJgVi2puDOHX/fJApgUBeFI24TAh+ZWXZ5MmQfpMqGsxcnJl4Z6vwYp8A0MbOer34CJDnv4UQ==" />
<h4>Subtotal: $200.00</h4>
<input id="hfSubtotal" type="hidden" value="200.0" name="order[subtotal]" />
<h4 class="hidden fieldTax"></h4>
<input id="hfTax" type="hidden" value="9.26" name="order[tax]" />
<h4 class="hidden fieldShipping">Shipping: $</h4>
<input id="hfShipping" type="hidden" value="0.0" name="order[shipping]" />
<h4 class="hidden fieldTotal"><strong>Total: $</strong></h4>
<input id="hfTotal" type="hidden" value="200.0" name="order[total]" />
</form>
Can anyone see where I'm going wrong here?
the problem that you have here is that you are trying to make the sum with ";" after every value, on the first value, it just brake the line and will always give you 200.00
var $total = parseFloat($subtotal).toFixed(2); + parseFloat($tax).toFixed(2); + parseFloat($shipping).toFixed(2);
just remove those ";" and just let the last one, change it like this
var $total = (parseFloat($subtotal) + parseFloat($tax) + parseFloat($shipping)).toFixed(2);
this will solve the problem.
So I have a group of labels that all belong to the "btn btn-warning" bootstrap class:
<div class = "btn-group" data-toggle = "buttons">
<label class="btn btn-warning active">
<input type="radio" checked>QA 71</input>
</label>
<label class="btn btn-warning">
<input type="radio">QA 72</input>
</label>
<label class="btn btn-warning">
<input type="radio">QA 73</input>
</label>
<label class="btn btn-warning">
<input type="radio">QA 74</input>
</label>
<label class="btn btn-warning">
<input type="radio">ST 71</input>
</label>
<label class="btn btn-warning">
<input type="radio">PR/Beta</input>
</label>
</div>
I would like to assign IDs to all of them, with the one labeled QA 71 as environment1, the next one as environment2, etc. Here is my jquery function:
var count = 1;
var btnid = "";
$(document).ready(function(){
$("label .btn-warning").each(
function(){
btnid = "environment"+count;
$(this).attr("id", btnid);
count++;
});
});
However, this is not working. What am I doing wrong?
The reason it doesn't work, is because the selector is wrong, a label with a class is denoted as label.classname
jQuery's each() also already has a count in the first argument, use that
$(document).ready(function(){
$("label.btn-warning").each(function(index, elem){
elem.id = "environment" + (index + 1); // zero based
});
});
You could even use attr() with a callback
$(document).ready(function(){
$("label.btn-warning").attr('id', function(index){
return "environment" + (index + 1); // zero based
});
});
There is a space between label and btn-warning which mean it will try to look for a class inside label, which is not the case .
$("label.btn-warning")
JSFIDDLE
i am trying to catch checkboxes state(checked or not) on every click to checkboxes on specific row.I can able to get the id value of row that clicked but i cannot retrieve the checkbox state properly,it returns false most of time(even if it's checked).At the end i am planning to edit records according to checkboxes state.
-On Page Load status of checkboxes set according to model value.
Html(razor)
#(Html.Kendo().ListView<AIS.UI.WebService.Proxy.DSrvAllService.NewsItem>()
.Name("listView")
.Events(e => e.Change("changeFunc"))
.TagName("div")
.Selectable()
.ClientTemplateId("template")
.AutoBind(true)
.DataSource(dataSource => dataSource
.Model(model => model.Id("ID"))
.PageSize(5)
//...Some another options
Kendo template:
<div class="container-fluid" style="padding-right:0px;border-bottom:1px solid \\#d4d4d4">
<div class=" col-sm-4" style="padding-top: 2px; min-height: 35px;margin-right:-1px; border-right: 1px solid rgb(212, 212, 212)">
<span class="bold" style="color: black;">#:Title#</span>
</div>
<div id="typeField" class="col-sm-4" >
#if(#ViewBag.type=="all")
{
<label class="checkbox-inline">
<input type="checkbox" id="webCheckBox" value="web" checked = "checked" />
<span style="vertical-align:middle">Web</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="ambulanceCheckBox" value="client" checked="checked" />
<span>Ambulance Client</span>
</label>
}
else{
<label class="checkbox-inline">
<input type="checkbox" id="webCheckBox" value="web" />
#if (#ViewBag.type == "web")
{ <input type="checkbox" id="webCheckBox" value="web" checked="checked" /> }
<span style="vertical-align:middle">Web</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" id="ambulanceCheckBox" value="client" />
#if (#ViewBag.type == "client")
{ <input type="checkbox" id="ambulanceCheckBox" value="client" checked="checked" /> }
<span>Ambulance Client</span>
</label>
}
</div>
<div class="col-sm-2 pull-right " style="padding-right:0px;" >
#* <a class="btn pull-right" href="\\#"><span class="k-icon k-delete"></span></a>*#
<a id="deletebutton" class="btn-old btn-default pull-right k-button-icontext k-delete-button" ><span class="k-icon k-delete"></span></a>
<a class="btn-old btn-default pull-right" onClick="OpenAnnouncement('#:ID#')"><span class="k-icon k-edit"></span></a>
#* <button id="opencasedetails" class="btn pull-right btn-primary" onClick="OpenAnnouncement('#:ID#')" type="button" >Edit</button>
<button id="deletecasedetails" class="btn pull-right btn-primary" onClick="deleteAnnouncement('#:ID#')" type="button" >Delete</button>*#
</div>
</div>
</script>
Js:
<script >
function changeFunc(e)
{
var index = this.select().index(),
dataItem = this.dataSource.view()[index];
//id of the selected row's record
var id = dataItem.ID;
//The section that trying the retrieve checkboxes state on click
//Failed!!!
var isWeb = $('#ambulanceCheckBox').is(':checked');
var isClient = $('#webCheckBox').is(':checked');
//Also Failed
// var isWeb = $('#ambulanceCheckBox').prop('checked')
// var isClient = $('#webCheckBox').prop(':checked');
}
</script>
Giving an ID to a checkbox inside the template is not a good idea because there will be multiple input elements with such id.
Instead I would suggest giving it a class.
Once you give it a class you can find that checkbox within the selected row and get its state.
e.g.
function changeFunc(e) {
alert(this.select().find(".myCheckBox").is(":checked"));
...
}
first,all id and class tags should be removed from input elements.
Then add onClick event:
<input type="checkbox" onclick="checkboxChange(this)" value="web" checked="checked" />
JS:
<script >
function checkboxChange(e) {
var check = e.checked;
var value = e.value;
var listview= $(e).closest(".k-listview").data("kendoListView");
//Get Selected rows's data
var dataItem = listview.dataSource.view()[listview.select().index()];
var id=dataItem.ID;
alert("Last State: " + check + "/ Value: " + value + "/ Row id :" + id);
};
</script>