1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

jQuery - accessing attributes

Discussion in 'jQuery' started by Lammie71, Nov 6, 2019.

  1. #1
    Hello, if I have the following code how can I add the condition with jQuery:

    
    <a href="#" data-name="A1" data-city="0" class="abc">LONDON </a>
    <br/><br/>
    <a href="#" data-name="A1" data-city="2" class="abc">MANCHESTER</a>
    
    Code (markup):
    So on the button click I want to test the data-values:
    i.e, if data-name=="A1" && data-name=="2" Then Do Something:

    I know I could use just data-city but I also need to check the data-city value

    In this case, clicking. on London no allow box would show but on clicking Manchester the alert box would show up.

    I have tried this but it doesn't work:

    
    $(".abc").bind("click", function(){
       if("a[data-name=='A2'] && a[data-city=='2']"){
          alert("That Works");
       };
    };
    
    Code (JavaScript):
    Please can someone help or advise me.

    Thanks in advance,
     
    Lammie71, Nov 6, 2019 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #2
    Your code isn't going to work because you have a string inside the if statement. What I think you want is
    if(a['data-name']=='A2' && a['data-city']=='2'){
    Code (javascript):
    but even then I think you're going to have problems

    Google tells me this:
    upload_2019-11-7_17-25-1.png
    so i'd rather see code that looks like this:
    $(".abc").on("click", function(event){
    //console.log($(this).attr('data-name')); // a good way to debug your code
    var dName = $(this).attr('data-name');
    var dCity = $(this).attr('data-city');
       if (dName === 'A1' && dCity === '2'){
       alert('match');
       }
       else {
       alert('no match');
       }
    });
    Code (javascript):
     
    sarahk, Nov 6, 2019 IP