jqueryfunction

Jquery Get ID using on method


I have a large form with radio buttons. I want to be able to click on a button and change its setting in the database using ajax. I initially coded it to use onclick and it all worked except that the buttons appearance wasn't changed. I found here that I should use the on method. I added that and the click is being recognized but I have to get the ID and the type of button clicked in order to change the database and I can't figure out how to get those. So, for example, in my code below if the first button is clicked on, I need to get the id of 1 and the type of "wh-active". My jsfiddle is here but it is not working for some reason, though the code does work on my computer. Would someone explain how to do this, please?

    <link rel="stylesheet" href="//use.fontawesome.com/releases/v6.7.2/css/all.css">

    <div>
    <div class="wh-loc">1</div>
    <div class="wh-active"><i id="1" class="fa-solid fa-circle fa-on"></i></div>  
    <div class="wh-name"><i id="2" class="fa-solid fa-circle fa-on"></i></div>  
    <div class="wh-address"><i id="3" class="fa-solid fa-circle fa-on"></i></div>  
    </div>

    <script>
    $(document).on('click', function() {
      var oldstatus = ($(this).hasClass("fa-on") ? 'fa-on' : 'fa-off');
      var id = $(this).attr('id');
      console.log('status '+oldstatus+' id '+id);
    });
    </script>

Solution

  • Keeping close to your example, I changed the $(document) selector to be $('.fa-circle'), which is one of the CSS values to the <i> elements.

    Then used .parent() to get the class from the <div> parent element that wraps the <i>.

    Try the example below:

        $('.fa-circle').on('click', function() {
          var oldstatus = ($(this).hasClass("fa-on") ? 'fa-on' : 'fa-off');
          var id = $(this).attr('id');
          var parentCSS = $(this).parent().attr('class');
          console.log('status '+oldstatus+' id '+id + ' parentCSS: ' + parentCSS);
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//use.fontawesome.com/releases/v6.7.2/css/all.css">
    
        <div>
        <div class="wh-loc">1</div>
        <div class="wh-active"><i id="1" class="fa-solid fa-circle fa-on"></i></div>  
        <div class="wh-name"><i id="2" class="fa-solid fa-circle fa-on"></i></div>  
        <div class="wh-address"><i id="3" class="fa-solid fa-circle fa-on"></i></div>  
        </div>