2

I have these two radio buttons

<input id="119715_0" type="radio" name="119715" value="76952" data-logic="yes" required /><label for="119715_0">Yes</label>

<input id="119715_1" type="radio" name="119715" value="76953" data-logic="no" required /><label for="119715_1">No</label>

I need to find out first, if they have the data-logic attribute and then the value in order to put together an if statement for if the value is yes or if the value is no. I cant use the id's because there might be multiple buttons on the page that have data-logic so I'm trying to use $(this) so it runs on whichever is getting clicked.

I've found this link How to select elements with jQuery that have a certain value in a data attribute array but it's specific to just the type of tag. I dont know how to use it with $(this)

I have currently been messing around with

function checkLogic() { 

if ($(this).attr("data-logic")) {

alert("haslogic");

}
}

$("input").click(checkLogic);

but have been unsuccessful

Community
  • 1
  • 1
thisuser
  • 129
  • 3
  • 10

5 Answers5

3

Check with the .data function: http://jsfiddle.net/byzLG/1/

$('input[name="119715"]').click(function() {
    if ($(this).data('logic') !== undefined) {
        alert('Has data-logic');
    } else {
        alert('Does not have data-logic');
    }
});​

Use case where if ($(this).data('logic')) didn't work as you wanted in my original code was if the value was 0. I'm sure a value of false would have broken it as well.

Gromer
  • 9,861
  • 4
  • 34
  • 55
2

use the .data() method:

$("input").on("click", function(){
  if($(this).data("logic"))
    alert("haslogic");
});

EXAMPLE

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

Chase
  • 29,019
  • 1
  • 49
  • 48
1

You can use plain JavaScript:

if(element.getAttribute("data-logic") === null) {
   // Doesn't have attribute
}

JSFiddle.

Zar
  • 6,786
  • 8
  • 54
  • 76
1
$("input").click(function() {
    var dataAttr = $(this).attr("data-logic");

    if (dataAttr == "yes") { 
      var value = $(this).attr("value");
      alert('Has logic ' + value);
    }

}); 

http://jsfiddle.net/wCRLE/1/

Darren
  • 68,902
  • 24
  • 138
  • 144
0

You should check the values with types. Javascript is really wrong with types so you need to be extra cautious:

if (typeof($(this).attr('data-type')) === "undefined")
charly
  • 956
  • 13
  • 23