0

Can someone explain to me why this doesn't work and what needs to be changed? I'm trying to have 3 icons that perform different actions when clicked.

 var array = [
        {val : 1, icon: 'fa-bolt'},
        {val : 2, icon: 'fa-exclamation'},
        {val : 3, icon: 'fa-undo-alt'}
    ];


$(array).each(function() {
   var $item = $('<i>');
   $item.attr('value', this.val).attr('class', 'fas fa-2x ' + this.icon + ' item-class');
   $body.append($item);
});


$('.item-class').on('click', function(){
    if ($(this).val() === '1') {
      //do stuff
    }
    if ($(this).val() === '2') {
      //do stuff
    }
    if ($(this).val() === '3') {
      //do stuff
    }
});
0

3 Answers 3

1

Your issue is in this line:

$('.item-class').on('click', function(){

The svg elements created by fontawesome are not yet there. You need to delegate the click event handler like:

$body.on('click', '.item-class', function (e) {

A second mystake is in this line:

$(this).val()

The value now is an attribute of svg element.

change it to:

$(this).attr('value')

var $body = $('body');
var array = [
    {val: 1, icon: 'fa-bolt'},
    {val: 2, icon: 'fa-exclamation'},
    {val: 3, icon: 'fa-undo-alt'}
];


$(array).each(function () {
    var $item = $('<i/>');
    $item.attr('value', this.val).attr('class', 'fas fa-2x ' + this.icon + ' item-class');
    $body.append($item);
});


$body.on('click', '.item-class', function (e) {
    var clickedValue = $(this).attr('value');
    console.log(clickedValue);
    if (clickedValue === '1') {
        //do stuff
    }
    if (clickedValue === '2') {
        //do stuff
    }
    if (clickedValue === '3') {
        //do stuff
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Worked! Thanks so much
1

You can add the onClick attribute, something like this:

$(array).each(function() {
  var $item = $('<i>');
  $item
    .attr('value', this.val)
    .attr('class', 'fas fa-2x ' + this.icon + ' item-class')
    .attr('onClick', 'show('+this.val+')');
  $('body').append($item);
});

function show(value) {
  console.log(value)
}

Comments

0

Why do you use value attribute for i element ? This is not HTML compliant.

You can use data-* attributes :

$item.data('value', this.val).attr('class', 'fas fa-2x ' + this.icon + ' item-class');

And in your loop :

// it will return int type, don't test with string
if ($(this).data('value') === 1) {

$(this).val() works only for input, here you just add value attribute on HTML element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.