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
  • 30,473
  • 11
  • 66
  • 95
MattP
  • 429
  • 1
  • 6
  • 15

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,242
  • 2
  • 16
  • 21
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
  • 9,662
  • 4
  • 42
  • 64
0
$(document).on("click", "[data-state=start]", function() {
  // do stuff
  var randomPick = Math.floor(Math.random() * comPicks.length);
})
guest271314
  • 1
  • 12
  • 91
  • 170
0

You can use selector by attribute :

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

Hope this helps.

Zakaria Acharki
  • 65,304
  • 15
  • 70
  • 95