Dynamically added checkbox / radio buttons / rating elements are not firing the attached events in semantic ui. Below is the js fiddle for sample and its not all triggering the events when check box is checked i have tried both 'setting' option and onChange separately as well. nothing is working as expected.
Javascript :
$("#cbdiv").checkbox('setting', 'onChange', function() {
alert("Changed");
});
$("#addcheckboxes").unbind();
var chkcounter = 0;
$("#addcheckboxes").bind('click', function() {
$('#chkgrp').append("<div id='chkbx_'" + chkcounter + "class='ui checkbox'><input type='checkbox' ></div>");
$('#chkbx_' + chkcounter).checkbox({
onChange: function() {
alert('i am added. my id is : ' + $(this).attr('id'));
}
});
});
Html
<div class="field">
<div id="cbdiv" class="ui toggle checkbox">
<input type="checkbox" id="confirm" name="confirmed">
<label>Confirmed</label>
</div>
<div>
<button id="addcheckboxes">Add checkboxes</button>
<div id="chkgrp">
</div>
</div>
</div>
Jsfiddle sample
It is because of the append statement adding wrong id element. After the append statement execute, if you look at your html it will look like below.
<div id="chkgrp">
<div id="chkbx_" 0class="ui checkbox">
<input type="checkbox">
</div>
</div>
After the above code execute, you are searching for the id chkbx_0 through jquery and try to add the onChange event for that. So it is failed. Update your append element syntax like below and it will work.
$('#chkgrp').append("<div id='chkbx_" + chkcounter + "' class='ui checkbox'><input type='checkbox' ></div>");
In the above code, I have closed id string after adding chkcounter id='chkbx_" + chkcounter + "'. In your earlier code you have closed the id string before adding the chkcounter itself id='chkbx_'" + chkcounter + ".
UPDATE
Looks like your semantic css have the following styles.
.ui.checkbox input {
position: absolute;
top: 0px;
left: 0px;
opacity: 0;
outline: 0px;
}
Because of the above styles you are not able to see the checkboxs. If you want to see the styled checkbox then you have add the label to your check box and update your code like below.
$('#chkgrp').append("<div id='chkbx_" + chkcounter + "' class='ui checkbox'><input type='checkbox'><label>test</label></div>");
Also I have noticed that you are trying to get the ID of the element using $(this).attr('id'). This statement will give the output undefined, because the checkbox does not have any attribute called id. I hope you are trying to get the id chkbx_0. In that case you have to add your code like below.
$(this).parent().attr('id');
I have updated your fiddle with all the above changes and you can see the demo here.
In checkbox code ID name is not set properly that's is the reason. You can see below working code
$("#addcheckboxes").bind('click', function() {
chkcounter++; // set counter increment
$('#chkgrp').append("<div id='chkbx_"+chkcounter+"' class='ui checkbox'><input type='checkbox' name='checkboxval[]' id='checkbox_id_"+chkcounter+"' ></div>");
$('#chkbx_'+chkcounter).checkbox({onChange:function(){alert('i am added. my id is : '+$(this).attr('id'));}});
});
Hope this will help you.
Related
I'm building a seed e-commerce site for my farmer friend to help build my portfolio and save hime some $$. I'm a beginner so it's been quite the learning experience.
Right now I'm having trouble with the number input fields that are used to an item's quantity before adding to the cart. I'm using the "id" tag, which I know is wrong, but I can't figure out what to use so that the value for one item doesn't affect the value of another item.
So my questions:
What do I use in my html to uniquely identify the value for each item/product?
How do I tweak my javascript to distinguish between each item's unique quantity?
Updated HTMl
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="panel panel-success">
<div class="panel-heading"><a href="Varieties
Grains/amaranth_hopireddye.html">Hopi Red Dye</a></div>
<div class="panel-body"><a href="Varieties
Grains/amaranth_hopireddye.html"><img
src="Images/amaranth_hopireddye.jpg" class="img-responsive"
style="width:100%" alt="Image"></a></div>
<div class="panel-footer">500 seeds per packet<br>$4.00 per
Packet</div>
<div class="panel-footer"><div align="center"><input type="number"
id="orderQty001" value="1" style="width: 50px; margin-right: 10px;"><a
href="#" class="productItem btn btn-primary center-block" data-
name="Hopi Red Dye " data-s="500 seeds" data-price="400" data-
id="001">Add to Cart</a></div></div>
</div>
</div>
<div class="col-sm-4">
<div class="panel panel-success">
<div class="panel-heading"><a href="Varieties
Grains/amaranth_dedosdedios.html">Dedos de Dios</a></div>
<div class="panel-body"><a href="Varieties
Grains/amaranth_dedosdedios.html"><img
src="Images/amaranth_dedosdedios.jpg" class="img-responsive"
style="width:100%" alt="Image"></a></div>
<div class="panel-footer">500 seeds per packet<br>$4.00 per
Packet</div>
<div class="panel-footer"><div align="center"><input type="number"
id="orderQty002" value="1" style="width: 50px; margin-right: 10px;"><a
href="#" class="productItem btn btn-primary center-block" data-
name="Dedos de Dios " data-s="500 seeds" data-price="400" data-
id="002">Add to Cart</a></div>
</div>
</div>
</div>
Updated Javascript:
var shopcart = [];
$(document).ready(function () {
outputCart();
$(".productItem").click(function (e) {
e.preventDefault();
var iteminfo = $(this.dataset)[0];
var inputId = "orderQty" + this.attr('data-id');
iteminfo.qty = document.getElementById(inputId).value;
var itemincart = false;
$.each(shopcart, function (index, value) {
//console.log(index + ' ' + value.id);
if (value.id == iteminfo.id) {
value.qty = parseInt(value.qty) + parseInt(iteminfo.qty);
itemincart = true;
}
})
if (!itemincart) {
shopcart.push(iteminfo);
}
sessionStorage["sca"] = JSON.stringify(shopcart);
outputCart();
})
I've also tried to assign a class and unique id to each element, but then I can't figure out how to get the unique user input in my javascript.
Make the ids unique.
One way to do this is to append the data-ids to each input id. For example id="orderQty001". Then in the JavaScript you can find the corresponding input based on the clicked element's data-id:
var inputId = "orderQty" + this.attr('data-id'); // 'this' is the clicked <a> element
iteminfo.qty = document.getElementById(inputId).value;
And the rest of the JavaScript could stay the same I think.
Edit (1/31): Since there are still problems I started a jsFiddle to run the code. Firstly, I found that this in the click handler is not a jQuery object, but a DOM element. As such, attr is not a function, and instead we must use getAttribute as follows:
var inputId = "orderQty" + this.getAttribute('data-id');
Next, I noticed a bug where the qty of the cart item was not getting set correctly. I found that the problem code was iteminfo.qty = document.getElementById(inputId).value;. This statement is a problem because it is manipulating the DOM earlier than we'd like. That is, it is setting the qty on the element immediately, instead of after we calculate the new qty. So instead we should declare a temporary variable to hold the input's value:
var qtyToAdd = document.getElementById(inputId).value;
Additionally, we must now set the iteminfo.qty before we add it to the cart for the first time:
if (!itemincart) {
iteminfo.qty = parseInt(qtyToAdd);
shopcart.push(iteminfo);
}
Here is the fiddle with these changes in place: https://jsfiddle.net/7vwyh03h/. The HTML was unchanged aside from formatting.
Edit (2/5): I've integrated my changes into your fiddle. All my previous updates edits are included. Updated fiddle:
https://jsfiddle.net/aougb72r/. When you click 'Add to Cart' the cart gets updated as you can see in the console and by checking the cart.
I changed one more thing, which was making iteminfo a clone of the dataset with:
var iteminfo = Object.assign({}, $(this.dataset)[0]);
This will make sure we don't edit the DOM accidentally when we really only want to manipulate the shopping cart in that function.
Check it out and see if you're still seeing any problems.
I would like to "attach" a div to a dropdown list. Is that possible?
I require something like this:
To be clear, I don't need to add div into the proper dropdownlist controller. I just need to attach.
What I've tried so far and not working:
HTML:
<select id="platypusDropDown">
<option value="duckbill">duckbill</option>
<option value="duckbillPlatypus">duckbillPlatypus</option>
<option value="Platypus">Platypus</option>
<option value="Platypi">Platypi</option>
</select>
<div id="addCategory">
<input id="categoryInput" type="text" /> <br/>
<input id="categoryInputAddBtn" type="button" value="Add new" />
</div>
JS:
$('#platypusDropDown').click(function () {
var myDiv = document.getElementById('addCategory');
this.append(myDiv);
});
Any solution? Thanks in advance.
I don't think so, what you are trying to achieve is possible using select dropdown.What here, i will do is modify my HTML Code and use css style.
<style type="text/css">
ul{ list-style: none;
margin: 0;
padding: 0; }
</style>
Here is my HTML Code: Instead of dropdown, i am using here ul li listing element.
<div class="select-wrapper">
Select Dropdown
<ul id="platypusDropDown" style="display:none;">
<li rel="duckbill">duckbill</li>
<li rel="duckbillPlatypus">duckbillPlatypus</li>
<li rel="Platypus">Platypus</li>
<li rel="Platypi">Platypi</li>
</ul>
</div>
<div class="wrapper" style="display:none;">
<div id="addCategory">
<input id="categoryInput" type="text" /> <br/>
<input id="categoryInputAddBtn" type="button" value="Add new" />
</div>
</div>
Here is my JS code:
<script type="text/javascript">
$(document).ready(function(){
var flg = 0;
$('.select-wrapper').click(function(){
flg++;
if(flg == 1){
$this_html = jQuery('.wrapper').html();
$("#platypusDropDown").append("<li>"+$this_html+"</li>");
}
$("#platypusDropDown").slideToggle();
});
});
</script>
You can't add DIV to selectBlock. But you can add option into select:
$('#platypusDropDown').click(function () {
var myDiv = document.getElementById('addCategory');
$(this).after(myDiv);
});
LEAVE jQuery Part . This is not possible by setting HTML static markup WITH select Containing DIV . SO IT IS NOT POSSIBLE . u may use markup but , still It wil hide in browser even though u can see in Firebug , div is attached to dropdown.
But if u r asking for : add Text as option in dropdown , then ,
Working FIDDLE
$('#categoryInputAddBtn').click(function () {
var myDiv = $('#categoryInput').val();
//this.append(myDiv);
var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text(myDiv);
$('#platypusDropDown').append(option);
});
As far as I know this is not possible with standard HTML select/option tags. But there are several different libraries emulating dropdown functionality and giving additional functionalities. One of those is UI Kit which provides this among a lot of other features. You can add so called 'Grid' components to the dropdown which can in fact contain anything you want. See detail over here under the headline 'Grid'.
You can add input value to dropdown list.
var $platypusDropDown = $('#platypusDropDown');
$('#categoryInputAddBtn').on('click', function() {
// Value of div input
var $category = $('#categoryInput').val();
// Add to dropdown list
$platypusDropDown.append('<option value="' + $category + '">' + $category + '</option>');
});
Why you whant add div to Options? You could try like this:
$('#platypusDropDown').click(function () {
var dropHeight = $(this.options[0]).height() * this.options.length;
if($(this).data('open')) {
$(this).data('open', false);
$('#addCategory').css('padding-top', '0px')
return;
}
$('#addCategory').css('padding-top', dropHeight + 'px')
$(this).data('open', true);
});
JSFIDDLE DEMO
I’m looking for some direction for my problem.
I’ve HTML divs and I want to replicate it when user clicks on span with id plus-1.
This is my html
<div id = “tab”>
<div class="row">
<div>
<select id="ProjectsFolder0FolderId" name="data[ProjectsFolder][0][folder_id]">
<option value="1">Project Presentation</option>
<option selected="selected" value="4">Project Root</option>
</select>
</div>
<div>
<div>
<input type="text" required="required" id="ProjectsFolder0Linux" value="xyz" name="data[ProjectsFolder][0][linux]">
</div>
</div>
<div id="plus-1" >
<span>
Click here
</span>
</div>
</div>
</div>
Jquery
$(document).on('click', '#plus-1' , function() {
var html = "<div class=\"row\" >"
???
+ "</div>";
$('#tab').append(html);
});
It is appending above html defined in jquery , but I don’t know how to append entire HTML efficiently as required above on each click.
Demo FIDDLE
Jquery
$(document).on('click', '#plus-1' , function() {
var html = $(this).parent().clone();
html.find('#plus-1').attr('id','plus-'+($('#tab').find('.row').length+1));
$('#tab').append(html);
});
Made a jsfiddle for you - http://jsfiddle.net/23GCn/. You also have an error in your html, you need to use correct parenthesis on <div id="tab">
jQuery(function($){
var count = 1;
$(document).on("click", "[id^='plus']", function(){
newBlock = $(this).parents(".row").clone();
count += 1;
// change id of Plus button
newBlock.find("[id^='plus']").attr("id", "plus-"+count);
// Change id and name of select box
newBlock.find("select")
.attr("id", "ProjectsFolder"+count+"FolderId")
.attr("name", "data[ProjectsFolder]["+count+"][folder_id]");
// Same for input
newBlock.find("input[type='text']")
.attr("id", "ProjectsFolder"+count+"Linux")
.attr("name", "data[ProjectsFolder]["+count+"][linux]");
// append new element to your tab
$("#tab").append(newBlock);
});
});
Note that [id^='plus'] type selectors are very inefficient, means, slow. Consider using classes instead of ids, this way you avoid all of the code required to change ids, since you can't have elements with same id on your page obviously.
I am using bootstrap theme called: Core Admin
http://wrapbootstrap.com/preview/WB0135486
This is the code I write:
<div class="span6">
<input type="checkbox" class="icheck" id="Checkbox1" name="userAccessNeeded">
<label for="icheck1">Needed</label>
</div>
And bootstrap generates me this code:
<div class="span6">
<div class="icheckbox_flat-aero" style="position: relative;">
<input type="checkbox" class="icheck" id="Checkbox7" name="userAccessNeeded" style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background-color: rgb(255, 255, 255); border: 0px; opacity: 0; background-position: initial initial; background-repeat: initial initial;"></ins>
</div>
<label for="icheck1" class="">Needed</label>
This is the result:
So basically it makes a pretty checkbox for me. Each time I click on the checkbox, it will add a checked class to the div:
<div class="icheckbox_flat-aero checked" style="position: relative;">
So at first I wanted to listen the input field being changed like this
$('input[type="checkbox"][name="userAccessNeeded"]').change(function () {
if (this.checked) {
}
});
But it doesn't actually change the input field, but rather changes the class of <div> element.
How could I listen to checkbox being checked?
$('input#Checkbox1').change(function () {
if ($('input#Checkbox1').is(':checked')) {
$('input#Checkbox1').addClass('checked');
} else {
$('input#Checkbox1').removeClass('checked');
}
});
i solve it that way.
The template looks to be using https://github.com/fronteed/iCheck/, which has callbacks:
$('input[type="checkbox"][name="userAccessNeeded"]').on('ifChecked', function(event){
alert(event.type + ' callback');
});
Or there is also:
$('input[type="checkbox"][name="userAccessNeeded"]').iCheck('check', function(){
alert('Well done, Sir');
});
Which should work with a whole range of methods:
// change input's state to 'checked'
$('input').iCheck('check');
// remove 'checked' state
$('input').iCheck('uncheck');
// toggle 'checked' state
$('input').iCheck('toggle');
// change input's state to 'disabled'
$('input').iCheck('disable');
// remove 'disabled' state
$('input').iCheck('enable');
// change input's state to 'indeterminate'
$('input').iCheck('indeterminate');
// remove 'indeterminate' state
$('input').iCheck('determinate');
// apply input changes, which were done outside the plugin
$('input').iCheck('update');
// remove all traces of iCheck
$('input').iCheck('destroy');
Link to the Documentation: http://fronteed.com/iCheck/
You need to bind to the ifchecked event via
Use on() method to bind them to inputs:
$('input').on('ifChecked', function(event){
alert(event.type + ' callback');
});
this will change the checked state
$('input').iCheck('check'); — change input's state to checked
This worked for me
jQuery('input.icheck').on('ifChanged', function (event) {
if ($(this).prop('checked')) {
alert('checked');
} else {
alert('unchecked');
}
});
Finally solved it like this, since I am clicking on a div element, then I must listen click event of that, and then check if the div has class and what is the id of checkbox.
$('.iCheck-helper').click(function () {
var parent = $(this).parent().get(0);
var checkboxId = parent .getElementsByTagName('input')[0].id;
alert(checkboxId);
});
Just my five cents, if anyone would have the same problem..
I needed the exact checkbox states. Toggle not worked here. This one has done the required state delivery for me:
$('.iCheck-helper').click(function () {
var checkbox = $(this).parent();
if (checkbox.hasClass('checked')) {
checkbox.first().addClass('checked');
} else {
checkbox.first().removeClass('checked');
}
doWhateverAccordingToChoices();
});
#Srihari got it right except the selector. Indeed the input isn't modified onclick, but the div do :
$('.icheckbox_flat-aero').click(function(){
$(this).find('input:checkbox').toggleClass('checked'); // or .find('.icheck').
});
Hey i hope this logic should work for you
JS CODE:
$('.icheckbox_flat-aero').on('click',function(){
var checkedId=$(this,'input').attr('id');
alert(checkedId);
});
This way a general event is added for all the checkbox`s
Happy Coding :)
Looking at your question and working with bootstrap since the past 1 year, I can definitely say that the checked class being added is not done by bootstrap. Neither is the checked class being added is a property which is built into BS 2.3.*.
Yet for your specific question try the following code.
$('.icheck').click(function(){
$(this).toggleClass('checked');
});
You can get a working example here.
Update 1:
The Checkbox cannot be styled by color using CSS. Hence, the developer is using insert tag to delete the Checkbox and put in his styling code. In effect, the CSS and JS in the specified theme do the styling by putting in the new stylized code.
Instead you can listed to the click event on the div icheckbox_flat-aero.
$('.icheckbox_flat-aero').children().on('click',function(){
alert('checked');
});
Check for the example http://jsfiddle.net/hunkyhari/CVJhe/1/
you could use this:
$('input#Checkbox1').on('ifChanged',function() {
console.log('checked right now');
});
I have a piece of code that on hover of another element insert's this code below.
<div class="star" id="1">
<div class="star" id="2">
<div class="star" id="3">
<div class="star" id="4">
<div class="star" id="5">
</div>
</div>
</div>
</div>
</div>
All I want to do is retrieve the ID of each DIV through javascript:
$(document).ready(function() {
$('.star').on(function(e){
e.stopPropagation();
var rating = $(this).attr('id');
alert(rating);
});
});
I've tried many ways of achieving this, this is the latest I've tried but I'm still having no luck! I'll be grateful of any help
Trigger an event when said divs are added.
var counter = 0;
$(someelement).on("mouseenter",function(){
counter++;
$('<div class="star" id="' + counter + '" />').appendTo(".star:last").trigger("staradded");
})
$(document).on("staradded",".star",function(e) {
alert(this.id);
});
Or better yet, skip the event.
var counter = 0;
$(someelement).on("mouseenter",function(){
counter++;
$('<div class="star" id="' + counter + '" />').appendTo(".star:last");
alert(counter);
})
I would use "livequery" plugin - https://github.com/brandonaaron/livequery
If I understood correctly, you need something like old function "live", since you would like to watch all new ".star" elements.
In this case you will just use following code:
$('.star').livequery('click',function(e){});
Simple example you can find there - http://jsfiddle.net/WEr5J/11/
You have wrong syntax of on as you are not telling what event you want to bind. After binding your required event e.g. click you can use map function to get all the comma separated ids of elements having class star.
Live Demo
$(document).on('click', '.star', function(e) {
e.stopPropagation();
ids = $('.star').map(function() {
return this.id;
}).get().join();
alert(ids);
});
You need to use each to iterate through all elements.
$('.star').each(function(){
var rating = $(this).attr('id');
alert(rating);
});