kk1957
kk1957

Reputation: 8824

Display checkbox using Font-Awesome

Using Font-awesome, I am trying to write a simple javascript that displays a checkbox and does some action when its clicked. This is what I have so far:

      var check = document.createElement('i');
      check.className = 'icon-check-empty';
      check.type = 'checkbox';
      check.id = 'hideConfigCheck';

// Action on click ( alert and toggle checkbox tick)

      $('#hideConfigCheck').click(function () {
        alert('you clicked here');
        if($(this).hasClass('icon-check')){
            $(this).removeClass('icon-check').addClass('icon-check-empty');}
        else {
            $(this).removeClass('icon-check-empty').addClass('icon-check');}
    });

However, when I click the checkbox, nothing seems to happen. Suggestions?

Upvotes: 0

Views: 404

Answers (2)

kk1957
kk1957

Reputation: 8824

Your solution probably works only when the element has been appended to the DOM.

For me, this worked

check.addEventListener('click', function () {........});

Upvotes: 0

Strat
Strat

Reputation: 171

Likely the element you're declaring at the top isn't in the DOM yet, so when you bind the .click() function, there is nothing to bind to - You'll have to do the binding when you add the element to the DOM

document.createElement doesn't actually put the element on the page, it just creates it so we can use it, and render it later. We need something to render it.

The simplest thing to do is just append to the body (or wherever you're using it) - if you're using JQuery do the following:

$("body").append(check);

Put that in between your two blocks of code and it should all work (it did for me). Or switch out "body" for your own selector.

Here's a fiddle showing what I mean: http://jsfiddle.net/kcuMU/1/

Happy Coding::

Upvotes: 2

Related Questions