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
Related
I'm trying to get a specific h3 from a cloned div when pressing a button. Since I got 10 cloned divs with the exact same values I want to be able to get the h3 from the specific button I just pressed.
$("body").on("click", ".btnFavorite", function() {
var favoriteMovieTest = $(this).parent().find("h3");
alert(favoriteMovieTest);
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
You can do it like this:
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
}
$(".btnFavorite").on("click", function() {
var favoriteMovieTest = $(this).closest("div").find("h3");
favoriteMovieTest.css('color','red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
As you can see i get that specific h3 element from the button.
Now you can do whatever you like with it, for example manipulate it's CSS code to change the color, like I did.
Try this.
Note : Keep code to attach event handler after for loop because if it is executed before for loop, elements created by for loop won't be attached with a event handler.
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search").find("h3").append(" "+i);
}
$(".btnFavorite").on("click", function() {
var favoriteMovieTest = $(this).siblings("h3")[0];
console.log(favoriteMovieTest);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3>Titel(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
You can climb up and down the DOM to get and title or index number of which cloned element was clicked.
$("body").on("click", ".search .btnFavorite", function(e) {
var elIndex = Array.from(e.target.parentNode.parentNode.children).indexOf(e.target.parentNode);
var favoriteMovieTest = e.target.parentNode.innerText;
alert('H3: ' + favoriteMovieTest + ' index: ' + elIndex);
});
for (var i = 0; i < 10; i++) {
$(".search-result:first").clone().appendTo(".search");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
<div class="search-result">
<h3 id='title'>Title(year)</h3>
<input type="submit" value="Favoritfilm" class="btn btn-warning btnFavorite">
<input id="btnArkiv" type="submit" value="Arkiv" class="btn btn-warning">
</div>
</div>
I'm trying to sum up values of buttons if the buttons are clicked on. For example, there is "Button1". If this button is clicked, it should add its value to a sum which will be displayed at the bottom of the page. If "Button1" is clicked a second time it should substract its value from the sum.
Here is my attempt to do this but it's not doing anything at all:
var value_Buttons = 0;
var total = 0;
$("button[name=Button1],[name=Button2],[name=Button3],[name=Button4],[name=Button5],[name=Button6]").click(function() {
if($(this).hasClass('active') == false) {
value_Buttons += parseInt($(this).val());
} else if($(this).hasClass('active') == true) {
value_Buttons -= parseInt($(this).val());
}
total += value_Buttons;
alert(total);
});
total = value_Buttons + value_Optional_Button;
$("input[name=value_sum]").val(total);
Additionally, here is the code for an examplary button (Like "Button1"):
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button1" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">Button 1</button>
</div>
There will be more buttons, but they will only differ in their name and value.
Also, the box which will display the sum of the button-values currently looks like this:
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
I've searched all over Stackoverflow, as well as via Google, etc. yet I can't find anything or anyone with a similar problem
Blocking JS logic error is here :
$("input[name=value_sum]").val(total);
this line should be in the above code block. Added corrections for substraction :
var total = 0;
$("button[name]").on("click", function() {
if(!$(this).hasClass('active')) {
total += Number($(this).val());
$(this).addClass('active').html("remove " + $(this).attr("title"));
} else {
total -= Number($(this).val());
$(this).removeClass('active').html("add " + $(this).attr("title"));
}
$("input[name=value_sum]").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button300" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 300 €</button>
<button type="button" class="form-control btn btn-primary" name="Button600" value="600" title="600 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 600 €</button>
</div>
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
Lines 14 and 15 need to be placed within the click event of the button to update the value_sum input on every click. Also your selection for the value attribute it a little bit off. The way to return the value attribute of a button using jQuery is:
$(this).attr('value');
So after these two points, stripping your code of the if and else check, and also selecting the buttons with a cleaner method, you should have something like this:
var total = 0;
$("button[name=Button1], button[name=Button2], button[name=Button3], button[name=Button4], button[name=Button5], button[name=Button6]").click(function() {
total += $(this).attr('value');
$("input[name=value_sum]").val(total);
});
To display the total, that is 0, in the input element on page load, you could use:
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
start off by create a listener for a class that will be applied to all of your buttons.
$(.btn).click(function() {
//get value
var value = parseint($(this).attr("value"));
//check if already clicked
if($(this).hasClass('active') {
//set value of total
total = total - value;
//remove class active
$(this).removeClass('active');
}else {
//set value of total
total = total + value;
//addclass active
$(this).addClass('active');
}
)};
Is this what you need?
Working Demo
Here have added a classname 'add' for all buttons , on click its toggle class add, sub in you case you using active,inactive class
var total = 0;
$("button[name=button1],[name=button2],[name=button3]").on('click', function () {
var self = $(this);
var gValue = Number(self.val());
if (self.hasClass("add")) {
total += gValue;
self.removeClass("add").addClass("sub");
} else {
total -= gValue;
self.removeClass("sub").addClass("add");
}
$("#costs").val(total);
});
Check this fiddle.
Add as many buttons as you like, the only thing is that you'll have to add a data-value to them to figure out how much to add or substract. I would also do the search for buttons using a class instead of "button" but that's up to you.
var buttons = {};
$("button").each(function (index, item) {
buttons[index] = 0;
$(item).click(function () {
var value = +($(item).data("value")),
val = +($("#costs").val());
val += (!buttons[index]) ? value : -value;
buttons[index] = (!buttons[index]) ? 1: 0;
$("#costs").val(val);
});
});
Hope it helps.
I have several forms for a product order page. Each Item on the page needs to have two prices, one for a one time order, and one for a recurring order.
The code I have is working fine, the problem is a need three javascript functions for each item, which as you can guess will get out of hand fast.
Here is the form for one product:
<form id="mangoForm" action="https://ximo365.foxycart.com/cart" method="post" accept-charset="utf-8">
<input type="hidden" name="name" value="Mango Bash Pack" />
<input id="mango-price-input" type="hidden" name="price" value="50" />
<input id="mango-sub-input" type="hidden" name="sub_frequency" value="1m">
<input id="mango-refBy" type="hidden" name="Referred By:" value="Not Specified">
<div class="btn-group">
<button type="button" onclick="changePriceLowMango()" class="btn btn-default">Subscribe & Save</button>
<button type="button" onclick="changePriceHighMango()" class="btn btn-default">One Time</button>
<button type="button" onclick="mangoSubmit()" class="btn btn-default" value="Submit form">Add To Cart</button>
</div>
</form>
And her is that forms javascript:
function changePriceHighMango() {
document.getElementById("mango-price").innerHTML = "80.00";
document.getElementById("mango-price-desc").innerHTML = "Switch to recurring and save up to 35%!";
document.getElementById("mango-price-input").value = "80.00";
document.getElementById("mango-sub-input").name = "Frequency";
document.getElementById("mango-sub-input").value = "Single Order";
}
function changePriceLowMango() {
document.getElementById("mango-price").innerHTML = "50.00";
document.getElementById("mango-price-desc").innerHTML = "Recurring Price. Cancel Anytime.";
document.getElementById("mango-price-input").value = "50.00";
document.getElementById("mango-sub-input").name = "sub_frequency";
document.getElementById("mango-sub-input").value = "1m";
}
function mangoSubmit() {
var mangoName = document.getElementById("distName").innerHTML;
document.getElementById("mango-refBy").value = mangoName;
document.getElementById("mangoForm").submit();
}
What I would like is three functions–one for increasing the price, one for decreasing the price, and one for submitting the form–that will work for each item. The functions would need to know which forms to change, what the low and high prices are, and what items on that form to update.
Is that at all possible to do?
Thanks for your help.
Trying to keep as much as the style and code you have right now, I would just pass all the variable stuff as arguments to a more generic changePrice function. As you say, the function would need to know which forms to change, what the low and high prices are, and what items on that form to update. So let's create a more generic changePrice function like this:
function changePrice(productName, description, price, subName, subValue) {
document.getElementById(productName + "-price").innerHTML = price;
document.getElementById(productName + "-price-desc").innerHTML = description;
document.getElementById(productName + "-price-input").value = price;
document.getElementById(productName + "-sub-input").name = subName;
document.getElementById(productName + "-sub-input").value = subValue;
}
function productSubmit(productName) {
var distName = document.getElementById("distName").innerHTML;
document.getElementById(productName + "-refBy").value = distName;
document.getElementById(productName + "Form").submit();
}
I am assuming that all the form inputs begin with the productName and have the same suffixes (-price, -price-desc, -price-input, -sub-input, and -sub-input).
Then you can just change the buttons onclick property with a call to those functions with the proper arguments.
<div class="btn-group">
<button type="button" onclick="changePrice('mango', 'Recurring Price. Cancel Anytime.', '50.00', 'sub_frequency', '1m')" class="btn btn-default">Subscribe & Save</button>
<button type="button" onclick="changePrice('mango', 'Switch to recurring and save up to 35%!', '80.00', 'Frequency', 'Single Order')" class="btn btn-default">One Time</button>
<button type="button" onclick="productSubmit('mango')" class="btn btn-default" value="Submit form">Add To Cart</button>
</div>
Example of a form for a **foo* product:
<form id="fooForm" action="https://ximo365.foxycart.com/cart" method="post" accept-charset="utf-8">
<input type="hidden" name="name" value="Foo Bash Pack" />
<input id="foo-price-input" type="hidden" name="price" value="50" />
<input id="foo-sub-input" type="hidden" name="sub_frequency" value="1m">
<input id="foo-refBy" type="hidden" name="Referred By:" value="Not Specified">
<div class="btn-group">
<button type="button" onclick="changePrice('foo', 'Foo Recurring Price. Cancel Anytime.', '10.00', 'sub_frequency', '1m')" class="btn btn-default">Subscribe & Save</button>
<button type="button" onclick="changePrice('foo', 'Foo Switch to recurring and save up to 35%!', '20.00', 'Frequency', 'Single Order')" class="btn btn-default">One Time</button>
<button type="button" onclick="productSubmit('foo')" class="btn btn-default" value="Submit form">Add To Cart</button>
</div>
</form>
You can try this:
function Mango(action) {
var mangoprice = document.getElementById("mango-price"),
mangopricedesc = document.getElementById("mango-price-desc"),
mangopriceinput = document.getElementById("mango-price-input"),
mangoprivesubinput = document.getElementById("mango-sub-input"),
mangorefBy = document.getElementById("mango-refBy"),
mangoForm = document.getElementById("mangoForm");
var mangoName = document.getElementById("distName").innerHTML;
switch(action)
{
case 'Low':
mangoprice.innerHTML = "80.00";
//... etc LOW PRICE
break;
case 'High':
//... etc HIGH PRICE
break;
case 'Submit':
mangorefBy.value = mangoName;
mangoForm.submit();
break;
}
}
Greetings from Vienna
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);
});
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>