NOTE: I know this is similar to other questions, but for semantic and other reasons (e.g. ease of input on iOS) I specifically want the HTML input to be type="number". This is where the problem comes in....
I'm trying to set up an HTML form so that number fields show thousands commas -- e.g. "10,000,000" instead of "10000000". I want to set it so that the field displays the commas, but when it gets focus for actual editing the commas go away.
I can manually add commas to the value without any issue (I'm testing mainly in Firefox ~59); but any time I try to have JavaScript add the commas, the field is blanked out instead. Does anyone know how to make this work?
(Note, I'm using Numerals.js for formatting here... http://numeraljs.com/ )
Here is what I have:
$(document).ready(function(){
var numberFields = $("input[type=number]");
numberFields.each( function(){
$(this).val( numeral( $(this).val() ).format('0') );
});
numberFields.focus( function(){
$(this).val( numeral( $(this).val() ).format('0') );
});
numberFields.blur( function(){
$(this).val( numeral( $(this).val() ).format('0,0') );
});
});
Example HTML input:
<input name="myField" value="0" type="number">
(Incidentally -- and conveniently, I've confirmed that submitting a number with commas to the HTML form processing script just drops the commas and puts the unformatted number into the DB. Sweet!)
I'm not familiar with numeral.js, but if I were doing it, I would just save the numeric value as a data attribute, and then format with .toLocaleString, keeping in mind that you have switch between text and number types so that you can display your commas:
Seeing the issues with iOS, I believe the following will work. You can clone the element, THEN set the original to be a text input. Then, get the position of the original, and set the new element to be absolutely positioned over the original. Now, set the number input to opacity: 0, this way you won't see it, but when they click, it will click your clone. When the clone is clicked, set it to opacity: 1, and when it is blurred, set the original input to the cloned input's value, but using toLocaleString. I checked that it works in firefox, in theory it should work on iOS as well.
$(document).ready(function(){
var $clones = [];
var numberFields = $("input[type='number']");
numberFields.each(function(i){
var $clone = $(this).clone();
$(this).attr('type', 'text');
var destination = $(this).offset();
var width = $(this).width();
$clones.push($clone.css({
position: 'absolute',
top: destination.top,
left: destination.left,
opacity: '0',
width: width
}));
$(this).after($clone);
var that = this;
$clone.on('focus', function() {
$(this).css('opacity', '1');
});
$clone.on('blur', function() {
$(this).css('opacity', '0');
$(that).val('' + $(this).val() ? parseInt($(this).val()).toLocaleString() : '');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" pattern="[0-9,]*" />
NOTE: I'm leaving this original answer in case something here is useful down the road; but please see my other answer, which is a complete solution to the original question.
I've found no way to quite do what I want. Futzing with input "type" is too inconsistent in different browsers; and doesn't work anyway on iOS (which was 90% of the point). However, I did get "pretty close" working smoothly with the following. (NOTE this uses the numeral.js library for formatting):
JavaScript:
<script>
$(document).ready(function(){
var intFields = $("input[data-format=integer]");
intFields.each( function(){
$(this).attr( "pattern", "[0-9,]*" );
$(this).val( numeral( $(this).val() ).format('0,0') );
});
intFields.focus( function(){
$(this).val( numeral( $(this).val() ).format('0') );
});
intFields.blur( function(){
$(this).val( numeral( $(this).val() ).format('0,0') );
});
$("form#myForm").on( "submit", function(){
intFields.each( function() {
$(this).val( numeral( $(this).val() ).format('0') );
} );
return true;
} );
});
</script>
HTML:
<input type="text" data-format="integer" name="some_number" value="12345678>">
Overall, WAAAY too much work for such a common use-case. I hope browsers makers come up with a solution to this soon! There needs to be a simple, standard way to display numbers in fields.
My final function, based on Dave's answer. Dave's was not fully functional (though an effective proof of concept). This handles the name attribute (which is necessary for Form submit), and positions the input overlay relative to the original input, rather than the page (which prevents things going catywampus if the window is resized).
IMPORTANT: When using this, you must use <label>...</label><input>, NOT <label>...<input></label> for your number fields Fixed!:
$(document).ready(function() {
format_integers();
});
/**
* Any form inputs with type=number and data-format=integer will display contents with commas when input not in focus.
* #param container string to be used as jQuery search. Defaults to 'body'; but can be any specific element
*/
function format_integers(container) {
container = (typeof container !== 'undefined') ? container : 'body';
var $wrapper = $('<span>').css({
position: 'relative',
display: 'inline-block',
padding: 0
});
$(container + " input[type='number'][data-format=integer]").each(function() {
var $clone = $(this).clone();
var $parentLabel = $(this).parent('label');
if( $parentLabel.length !== 0 ) {
$parentLabel.css( 'display', 'inline-flex' );
$clone.css( 'order', 1 );
$(this).css( 'order', 2 );
}
$(this).wrapAll($wrapper).css({
position: 'absolute',
top: 0,
left: 0,
opacity: 0
})
.attr('pattern', '[0-9]*');
$clone.removeAttr('name class id pattern')
.attr('type', 'text')
.attr('tabindex', -1)
.css('width', $(this).width)
.val($(this).val() ? parseInt($(this).val()).toLocaleString() : '');
$(this).before($clone);
$(this).on('focus', function() {
$(this).css('opacity', '1');
});
$(this).on('blur', function() {
$(this).css('opacity', '0');
$clone.val($(this).val() ? parseInt($(this).val()).toLocaleString() : '');
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Integer Input: <input type="number" data-format="integer" name="test" id="num_input" value="123456789" /></label><br>
<label for="num_input2">Integer Input: </label>
<input type="number" data-format="integer" name="test2" id="num_input2" value="10000000" /><br>
<label>Textarea <textarea>Something to focus other than the number fields</textarea></label>
</form>
Related
My first time writing my own javascript/jQuery for-loop and I'm running into trouble.
Basically, I have a series of divs which are empty, but when a button is clicked, the divs turn into input fields for the user. The input fields are there at the outset, but I'm using CSS to hide them and using JS/jQuery to evaluate the css property and make them visible/hide upon a button click.
I can do this fine by putting an id tag on each of the 7 input fields and writing out the jQuery by hand, like this:
$('#tryBTN').click(function(){
if ( $('#password').css('visibility') == 'hidden' )
$('#password').css('visibility','visible');
else
$('#password').css('visibility','hidden');
}
Copy/pasting that code 7 times and just swapping out the div IDs works great, however, being more efficient, I know there's a way to put this in a for-loop.
Writing this code as a test, it worked on the first one just fine:
$('#tryBTN').click(function() {
for(i = 1; i <= 7; i++) {
if($('#input1').css('visibility') == 'hidden')
$('#input1').css('visibility', 'visible');
}
});
But again, this only works for the one id. So I changed all the HTML id tags from unique ones to like id="intput1" - all the way out to seven so that I could iterate over the tags with an eval. I came up with this:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
if ($(eval('input' + i)).css('visibility') == 'hidden')
$('input' + i).css('visibility', 'visible');
}
});
When I put in the eval stuff - it doesn't work. Not sure what I'm doing wrong. A sample of the HTML looks like this:
<form>
<div class="form-group">
<label for="page">Description: Specifies page to return if paging is selected. Defaults to no paging.</label>
<input type="text" class="form-control" id="input7" aria-describedby="page">
</div>
</form>
You were forgetting the #:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
var el = $('#input' + i); // <-- The needed `#`
if (el.css('visibility') == 'hidden') {
el.css('visibility', 'visible');
}
}
});
#Intervalia's answer explains the simple error in your code (the missing #), and the comments explain why you should never use eval() unless you absolutely know it's the right tool for the job - which is very rare.
I would like to add a suggestion that will simplify your code and make it more reliable.
Instead of manually setting sequential IDs on each of your input elements, I suggest giving them all a common class. Then you can let jQuery loop through them and you won't have to worry about updating the 7 if you ever add or remove an item.
This class can be in addition to any other classes you already have on the elements. I'll call it showme:
<input type="text" class="form-control showme" aria-describedby="page">
Now you can use $('.showme') to get a jQuery object containing all the elments that have this class.
If you have to run some logic on each matching element, you would use .each(), like this:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
if( $(element).css('visibility') == 'hidden' ) {
$(element).css( 'visibility', 'visible' );
}
});
});
But you don't need to check whether an element has visibility:hidden before changing it to visibility:visible. You can just go ahead and set the new value. So you can simplify the code to:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
$(element).css( 'visibility', 'visible' );
});
});
And now that the only thing we're doing inside the loop is setting the new visibility, we don't even need .each(), since jQuery will do the loop for us when we call .css(). (Thanks #TemaniAfif for the reminder.)
So the code becomes very simple:
$('#tryBTN').click( function() {
$('.showme').css( 'visibility', 'visible' );
});
I need to fake a toggle switch with an input range.
The idea is to create a short range, with just 2 values, min and max. the css button will match one end of the range. So far you click on it, the div containing the range will move a bit bringing the other end of the ranger under your mouse.
I have this function, which applies on all input ranges on the page. But i need to apply it only on some classes, not all. But i can't find the right syntax and it doesn't work.
The Javascript:
$('input[type="range"]').on('change', function() {
$('div#launcher01').css('margin-top', parseInt($(this).val() ) > 0 ? parseInt($(this).val() ) + 'px' : '0px');
});
CSS:
.fakbl input {
height: 50px;
width: 50px;
HTML:
<div id="launcher01">
<div class="fakbl">
<input type="range" id="launch01" name="launch01" min="0" max="50" step="50"" />
</div>
</div>
Fiddle
Since you are already using jQuery, you can phrase your widget-maker as a jQuery plugin as follows :
$.fn.rangeButton = function(containerSelector) {
return this.each(function() {
var $self = $(this);
$self.on('change', function() {
$self.closest(containerSelector).css('margin-left', ($self.val()/3) > 0 ? ($self.val()/3) + 'px' : '0px');
}).trigger('change'); // trigger 'change' immediately to initialize everything.
});
};
Now, invoke the widget on each of your ranges, and pass a selector for the appropriate container :
$('#launcher01 input[type="range"]').rangeButton('#launcher01');
$('#launcher02 input[type="range"]').rangeButton('#launcher02');
Demo
Alternatively, by giving all containers the same class, you can invoke all your widgets with a single command :
$('.myClass input[type="range"]').rangeButton('.myClass');
Demo
May I ask a refinement please?
I completed the fake button. As you can see in this FIDDLE
(the white box will disappear, I added some opacity to it just to show that the button is working)
The red box (now green due to my buggy code part) is in the background and I would need it to change color depending on the status. I tried this but it doesn't work.
Here the code:
$.fn.rangeButton = function(containerSelector) {
return this.each(function() {
var $self = $(this);
$self.on('change', function() {
$self.closest(containerSelector).css('margin-left', ($self.val()/3) > 0 ? ($self.val()/3) + 'px' : '0px');
// this part is not working, if you remove this part, the button works flawlessy
if ($self = 100) {
document.getElementById("fakbuttonsfondo01").style.backgroundColor="rgb(0, 191, 1)";
} else {
document.getElementById("fakbuttonsfondo01").style.backgroundColor="rgb(0, 0, 255)";
}
// end of buggy code
}).trigger('change'); // trigger 'change' immediately to initialize everything.
});
};
$('#launcher01 input[type="range"]').rangeButton('#launcher01');
$('#launcher02 input[type="range"]').rangeButton('#launcher02');
Thanks:)
this is my first post on StackOverflow. I hope it doesn't go horribly wrong.
<input type="Text" id="filterTextBox" placeholder="Filter by name"/>
<script type="text/javascript" src="/resources/events.js"></script>
<script>
$("#filterTextBox").on("keyup", function () {
var search = this.value;
$(".kurssikurssi").show().filter(function () {
return $(".course", this).text().indexOf(search) < 0;
}).hide();
});
</script>
I have a javascript snippet like this on my school project, which can be found here: http://www.cc.puv.fi/~e1301192/projekti/tulos.html
So the search bar at the bottom is supposed to filter divs and display only those, that contain certain keyword. (t.ex, if you type Digital Electronics, it will display only Divs that contain text "Digital Electronics II" and "Digital Electronics". Right now, if I type random gibberish, it hides everything like it's supposed to, but when I type in the beginning of a course name, it will not hide the courses that dont contain the certain text-string.
Here is an example that I used (which works fine): http://jsfiddle.net/Da4mX/
Hard to explain, but I hope you realize if you try the search-function on my page. Also, I'm pretty new to javascript, and I get the part where you set the searchbox's string as var search, the rest I'm not so sure about.
Please help me break down the script, and possibly point where I'm going wrong, and how to overcome the problem.
in your case I think you show and hide the parent of courses so you can try
$("#filterTextBox").on("keyup", function () {
var search = $(this).val().trim().toLowerCase();
$(".course").show().filter(function () {
return $(this).text().toLowerCase().indexOf(search) < 0;
}).hide();
});
Try this this is working now, paste this code in console and check, by searching.
$("#filterTextBox").on("keyup", function () {
var search = this.value; if( search == '') { return }
$( ".course" ).each(function() {
a = this; if (a.innerText.search(search) > 0 ) {this.hidden = false} else {this.hidden = true}
}); })
Check and the search is now working.
Your problem is there :
return $(".course", this)
From jquery doc: http://api.jquery.com/jQuery/#jQuery-selection
Internally, selector context is implemented with the .find() method,
so $( "span", this ) is equivalent to $( this ).find( "span" )
filter function already check each elements
then, when you try to put $(".course") in context, it will fetch all again...
Valid code :
$("#filterTextBox").on('keyup', function()
{
var search = $(this).val().toLowerCase();
$(".course").show().filter(function()
{
return $(this).text().toLowerCase().indexOf(search) < 0;
}).hide();
});
In fact, you can alternatively use :contains() CSS selector,
but, it is not optimized for a large list and not crossbrowser
http://caniuse.com/#search=contains
You were accessing the wrong elements. This should be working:
$(".kurssikurssi").find('.course').show().filter(function () {
var $this = $(this)
if($this.text().indexOf(search) < 0){
$this.hide()
}
})
I have two input fields, where people can write numbers. And what I need is when a person finished writing in this input field some constant words or symbols are left there near his number.
I think that you didn't get anything from what I wrote above so I will try to explain with this example:
In the upper there are two inputs you see what person printed himself. And two inputs in the bottom are what he gets when he puts his cursor out of the input where he was printing.
(I don't need all four inputs, just two...upper two just show the first step and bottom two show the final step)
I think it can be done by javascript... but I couldn't do it by myself and I couldn't find anything in web...
You'll need to get a reference to the textbox (try onblur event) and then append your static text to the value property.
I've used the following before, the reason I chose using an image over anything else was because text added to an input dynamically can cause confusion, as well as getting in the way when users wish to edit. Using an image meant it could be constantly there and wouldn't get in the way of the user typing:
It's only written in jQuery because it was lying around, this could easily be rewritten in pure js - and it could easily be optimised.
http://jsfiddle.net/pafMg/
css:
input {
border: 1px solid black;
background: #fff;
padding: 2px;
}
markup:
<input class="right-aligned" type="text" />
<input class="left-aligned" type="text" />
code:
In the following code the padding-left and padding-right has to take into account the width of the image you use.
$(function(){
/* For left aligned additions */
$('input.left-aligned')
.css({
'padding-left': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : '2px center',
'background-repeat': 'no-repeat'
});
});
The left aligned version is really simple, the right aligned gets a little bit more complex however:
$(function(){
/* For right aligned additions */
$('input.right-aligned')
.bind('keypress keyup', function(e){
var input = $(this), measure, text = input.val(), x, w, y;
/// You can calculate text width, but it's not easily cross-browser
/// easier method, inject the text to a span and measure that instead
if ( !input.data('measure') ){
/// only build our measuring span the first time
measure = $('<span />')
.hide() // hide it
.appendTo('body')
/// try and match our span to our input font
/// this could be improved
.css({
'font-weight':input.css('font-weight'),
'font-family':input.css('font-family'),
'font-size':input.css('font-size')
});
/// store the measure element for later
input.data('measure', measure );
}
/// handle if the user types white space
text = text
.replace(/\s/g,' ')
.replace(/</g,'>');
measure = input.data('measure');
measure.html(text);
w = measure.width();
y = input.width();
/// calculate the image position (minus padding)
x = w + parseInt(input.css('padding-left')) + 2;
/// take into account the scroll ability of an input
x -= ( w > y ? w - y : 0 );
/// reposition our image background on the input
input
.css({
'padding-right': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : x + 'px center',
'background-repeat': 'no-repeat'
});
}).trigger('keyup');
});
Take a look at the blur event using jQuery: http://docs.jquery.com/Events/blur#fn
Here's a quick sample: http://jsfiddle.net/jDGg9/
<form>
Field 1: <input id="ip1" type="text" value="" />
Field 2: <input id="ip2" type="text" value="" />
</form>
$('#ip1').blur(function() {
$('#ip1').val($('#ip1').val() + ' month');
});
$('#ip2').blur(function() {
$('#ip2').val($('#ip2').val() + ' month');
});
Since you didn't specify using jQuery, here's a simple example with basic Javascript using the blur event (as everyone has already specified) although it might make sense to use the onchange event:
http://jsfiddle.net/A9yVv/1/
<input type="text" id="text1" value="" />
<br />
<input type="text" id="text2" value="" readonly="readonly" />
var text1 = document.getElementById("text1");
text1.onblur = function () {
var text2 = document.getElementById("text2");
text2.value = this.value + " month(s)";
};
If jQuery is available this will be much easier, but the code can be rewritten to work without it if it's not.
When an input loses focus, the blur event is fired, and when it regains focus the focus event is fired. If you store the original value (say, using jQuery's data method), you can accomplish what you're asking fairly easily:
<input type="text" name="months" class="month" />
<input type="text" name="price" class="price" />
<script>
jQuery(function($) {
$('.months')
.blur(function(event) {
// This code runs when the input with class "months" loses focus
var originalValue = $(this).val();
$(this)
.data('original-value', originalValue)
.val(originalValue + ' months');
})
.focus(function(event) {
// This code runs when the input with class "months" gains focus
var originalValue = $(this).data('original-value');
if (typeof originalValue !== 'undefined') {
$(this).val(originalValue);
}
});
$('.price')
.blur(function(event) {
// This code runs when the input with class "price" loses focus
var originalValue = $(this).val();
$(this)
.data('original-value', originalValue)
.val('$ ' + originalValue);
})
.focus(function(event) {
// This code runs when the input with class "price" gains focus
var originalValue = $(this).data('original-value');
if (typeof originalValue !== 'undefined') {
$(this).val(originalValue);
}
});
$('form.myform')
.submit(function(event) {
// This code runs when the form is submitted
// Restore the original values, so they are submitted to the server
$('.months').val($('.months').data('original-value'));
$('.price').val($('.price').data('original-value'));
});
});
</script>
I've done it all without javascript... The problem was that it changed the value of the input field but I didn't need that.
So I've just made images of '$' and 'month' and added them as a background in CSS to the inputs... In the first input field i wrote a property maxlenth='3' so numbers won't be written over the constant text and in the second field I've done padding-left='15px' in CSS.
Thanks everyone.
(jQuery noob here)
Im trying to write a script which when I write <input type='checkbox'/> will automatically convert it to jQuery UI button and look like a checkBox.
Sample code so far ...
var newCheckboxID = 0;
$( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that?
$( "input:checkbox" ).after("<label style='width:16px; height:16px; vertical-align:middle;'></label>");
$( "input:checkbox" ).next().attr("for", $(this).attr('id') ); // doesn't work for sure
$( "input:checkbox" ).button();
$( "input:checkbox" ).button( "option", "text", false );
$( "input:checkbox" ).attr("onclick", "$(this).button( 'option', 'icons', {primary:((this.checked)?'ui-icon-check':null),secondary:null} )");
Sorry, if it's too obvious but I've lost more than hour in that ...
EDIT
Finally did it with the old fashioned way (for the doesn't working parts).
Any comments for making it more compact and "more jQuery" would be appriciated ...
Code sample
// ---- set ids
var checkboxID = 0;
//$( "input:checkbox" ).attr('id', "cbx-" + nextCheckboxID++); // how to do that?
var cboxes = document.getElementsByTagName('input'); // <-- do this instead
for(var i=0; i<cboxes.length; i++){
if( cboxes[i].getAttribute('type')!='checkbox' ) continue;
cboxes[i].setAttribute('id', 'cbx-'+checkboxID++);}
// ---- add labels
$( "input:checkbox" ).after("<label style='width:16px; height:16px; vertical-align:middle;'></label>");
//$( "input:checkbox" ).next().attr("for", $(this).attr('id') ); // doesn't work this
for(var i=0; i<cboxes.length; i++){ // <-- do this instead
if( cboxes[i].getAttribute('type')!='checkbox' ) continue;
cboxes[i].nextSibling.setAttribute('for', cboxes[i].getAttribute('id') );}
// ---- create
$( "input:checkbox" ).button();
$( "input:checkbox" ).button( "option", "text", false );
$( "input:checkbox" ).attr("onclick", "$(this).button( 'option', 'icons', {primary:((this.checked)?'ui-icon-check':null),secondary:null} )");
Working examples:
jsFiddle (without comments)
jsFiddle (without comments with UI theme switcher!)
jsFiddle (with comments)
jsFiddle (Just for fun, uses timer and some other jQuery features, just for future reference)
jsFiddle (Just for fun, uses timer and changes UI theme every second!)
In the following, I should note 2 primary changes. I added CSS to do what you were trying to do to labels in "code" (where it really doesn't belong).
Also, I changed the HTML for "ease of jQuery" use. However, I still noted in the comments how you can easily change it back.
the HTML
<center>
<button>Create New CheckBox</button>
</center>
<hr />
<div id="CheckBoxes">
<input class="inp-checkbox" />
<input class="inp-checkbox" />
<input class="inp-checkbox" />
<input class="inp-checkbox" />
</div>
the CSS
.inp-checkbox+label {
width:16px;
height:16px;
vertical-align:middle;
}
the JavaScript/jQuery
// keep in mind, and i will explain, some of these "moving-parts" or not needed, but are added to show you the "ease" of jquery and help you see the solution
// This global function is designed simply to allow the creation of new checkboxes as you specified, however, if you won't be making check boxes at end user time, then i suggest simply moving it to within the .each statement found later on.
// Also, this could easily be written as a jQuery plugin so that you could make a "chainable" one-line call to change checkboxes to this but let's get to the nitty gritty first
function createCheckBox(ele, i) {
// First I simply create the new ID here, of course you can do this inline, but this gives us a bottleneck for possible errors
var newID = "cbx-"+i;
// below we use the param "ele" wich will be a jQuery Element object like $("#eleID")
// This gives us the "chainability" we want so we don't need to waste time writing more lines to recall our element
// You will also notice, the first thing i do is asign the "attribute" ID
ele.attr({ "id": newID })
// Here we see "chainability at work, by not closing the last line, we can move right on to the next bit of code to apply to our element
// In this case, I'm changing a "property", keep in mind this is kinda new to jQuery,
// In older versions, you would have used .attr but now jQuery distinguishes between "attributes" and "properties" on elements (note we are using "edge", aka. the latest jQuery version
.prop({ "type": "checkbox" })
// .after allows us to add an element after, but maintain our chainability so that we can continue to work on the input
// here of course, I create a NEW label and then immidiatly add its "for" attribute to relate to our input ID
.after($("<label />").attr({ for: newID }))
// I should note, by changing your CSS and/or changing input to <button>, you can ELIMINATE the previous step all together
// Now that the new label is added, lets set our input to be a button,
.button({ text: false }) // of course, icon only
// finally, let's add that click function and move on!
// again, notice jQuery's chainability allows us no need to recall our element
.click(function(e) {
// FYI, there are about a dozen ways to achieve this, but for now, I'll stick with your example as it's not far from correct
var toConsole = $(this).button("option", {
icons: {
primary: $(this)[0].checked ? "ui-icon-check" : ""
}
});
console.log(toConsole, toConsole[0].checked);
});
// Finally, for sake of consoling this new button creation and showing you how it works, I'll return our ORIGINAL (yet now changed) element
return ele;
}
$(function() {
// This .each call upon the inputs containing the class I asiged them in the html,
// Allows an easy way to edit each input and maintain a counter variable
// Thus the "i" parameter
// You could also use your ORIGINAL HTML, just change $(".inp-checkbox") to $("input:[type='checkbox']") or even $("input:checkbox")
$(".inp-checkbox").each(function(i) {
// as previously noted, we asign this function to a variable in order to get the return and console log it for your future vision!
var newCheckBox = createCheckBox($(this), i);
console.log(newCheckBox);
});
// This next button added is simply to show how you can add new buttons at end-time
// ENJOY!!!
$("button").button().on("click", function(e) {
var checkBoxCount = $("#CheckBoxes .inp-checkbox").length;
var newCheckBox = $("<input />").addClass("inp-checkbox").appendTo($("#CheckBoxes"));
createCheckBox(newCheckBox , checkBoxCount);
console.log(newCheckBox);
});
});
Update: The original intent here was to purely answer the question, which was to create a jQuery UI styled checkbox and show how jQuery can be used in multiple ways. However, a later comment queried how to include a traditional style label with it. While there are a billion options for this, I'll simply take from the above and extend.
The first option I took is pretty simple. Using jsFiddle (without comments with UI theme switcher!), I made the following changes:
the JavaScript/jQuery
// First I add a new variable.
// It will simply be for a new "wrapper" element, in which to ensure our button is encased.
// Giving this element a new class gives easy access for later CSS or Event Triggering of sub elements (like the checkbox)
var newID = "cbx-"+i,
wrapper = $('<div />', { 'class': 'ui-checkbox-wrapper' }).appendTo('#CheckBoxes');
// Then I added a line to our ele series of methods.
// This line simply append our element (checkbox) to our new wrapper
// Take Note at how I added this method at start rather than at end.
// Had I not done this, then the label would not have been wrapped!
ele.appendTo(wrapper) // <-- new line!
.attr({ "id": newID })
Then I simply added the following CSS:
#CheckBoxes .ui-button .ui-button-text {
background: #A9A9A9;
display: inline;
font-size: 16px;
left: 19px;
padding: 0;
position: relative;
text-indent: 0;
top: -4px;
}
Results!