Skip to content Skip to sidebar Skip to footer

Obtain Related Div Text With Jquery

After bit of struggling and few valuable suggestions, I've come into a solution that works well as follows: As you can see, I am showing few questions with options to be selected.

Solution 1:

$(".h2Val").text() gets all text from all matching elements in the selector.

You need to target the instance within the same .heading container as the button. Traverse to the main parent container using closest() and use find() to only look within that instance

$(document).ready(function() {
  divs = $(".divs").children();
  divs.each(function(e) {
    if (e != 0)
      $(this).hide();
  });

  $("#next").click(function() {
    if (divs.next().length != 0)
      divs.next().show().prev().hide();
    else {
      divs.hide();
      divs.show();
    }
    returnfalse;
  });

  $("#prev").click(function() {
    if (divs.prev().length != 0)
      divs.prev().show().next().hide();
    else {
      divs.hide();
      divs.show();
    }
    returnfalse;
  });

  $(".btn").click(function() {
    var $container = $(this).closest('.heading')
    var id = $container.find(".h2Val").text().trim();
    var $checked = $container.find('.cbCheck:checked');
    var values = $checked.map(function(){
        returnthis.value
    }).get();
    console.clear()
    console.log('ID: ' + id +' has ' + $checked.length + ' checked');
    console.log('Values: ', values.join())
  });
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script><divclass="divs"><divclass="heading"><divclass="h2Val">
      1
    </div><div>What's the capital of England?</div><divclass="heading2"><div><inputtype="checkbox"id="val1"class="cbCheck"name="val1"value="London" />London</div></div><divclass="heading2"><div><inputtype="checkbox"id="val2"class="cbCheck"name="val2"value="New York" />New York</div></div><div><inputtype="button"class="btn"value="Get Value" /></div></div><divclass="heading"><divclass="h2Val">
      2
    </div><div>Who invented computer?</div><divclass="heading2"><div><inputtype="checkbox"id="val3"class="cbCheck"name="val3"value="Thomas Edison" />Thomas Edison</div></div><divclass="heading2"><div><inputtype="checkbox"id="val4"class="cbCheck"name="val4"value="Charles Babbage" />Charles Babbage</div></div><divclass="heading2"><div><inputtype="checkbox"id="val5"class="cbCheck"name="val5"value="Sir Isaac Newton" />Sir Isaac Newton</div></div><div><inputtype="button"class="btn"value="Get Value" /></div></div></div><aid="prev">Previous</a><aid="next">Next</a>

Post a Comment for "Obtain Related Div Text With Jquery"