1

I am trying to select certain buttons that have a data-state="start", so that when the user clicks on the buttons, the function randomly selects from an array. I just don't know how to select my data-states... Here is some of the code:

$("").on("click", function() {
    var randomPick = Math.floor(Math.random() * comPicks.length);
    alert(randomPick);
  });

I'm trying to select the buttons with the data-state="weapon"...

<button class="btn btn-info btn-block" data-state="weapon">ROCK</button>

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
MattP
  • 489
  • 1
  • 7
  • 16

4 Answers4

0

If you're trying to select elements that have the data-state attribute set to a certain value, you can use this plugin:

$.fn.filterByData = function(prop, val) {
    return this.filter(function() {
        return $(this).data(prop) == val;
    });
};

Now, you can use $('button').filterByData('state', 'start') to get a list of all buttons that have a data-state="start" attribute.

If all you want is to get the actual value of the data-state attribute in the function, you can just use $(this).data('state')

gpanders
  • 1,301
  • 2
  • 15
  • 23
0

One way is just have the data-type in the query

$("input[data-type='start']").on("click", function() {
    var randomPick = 10;//changed to show example
    alert(randomPick);
});
$("button[data-type='start']").on("click", function() {
    var randomPick = 20;//changed to show example
    alert(randomPick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' data-type='start' value='Click me'/>
<button data-type='start'>Button</button>
<input type='button' value='Does nothing'/>
depperm
  • 10,606
  • 4
  • 43
  • 67
0
$(document).on("click", "[data-state=start]", function() {
  // do stuff
  var randomPick = Math.floor(Math.random() * comPicks.length);
})
guest271314
  • 1
  • 15
  • 104
  • 177
0

You can use selector by attribute :

$('body').on("click", "button[data-state='start']", function() {
     //Your code here
})

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101