amjs amjs - 22 days ago 9
Javascript Question

how to check the dynamic values using if condition in jquery?

I have tried to validate the user input from the contenteditable in jquery. I don't know exactly where I made the mistake. Please advise.



$(function() {
$("#p28-textid39").hide();
$(".result").click(function() {
$("#p28-textid39").show();
var data_answer = $(this).attr("data-answer");
var content = $(this).text();
if (content == data_answer) {
alert("correct");
} else {
alert("incorrect");
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure id="bodyimage">
<img alt="" src="images/page0028.jpg" />
</figure>
<div id="parent-p28">
<p><span class="styleid2" id="p28-textid12">line is to write an ____________________.</span>
</p>
<p><span class="styleid9" id="p28-textid39">answer</span>
</p>
<div style="position:absolute;left:348px;top:278px;" class="act1">
<table>
<tr>
<td class="txt" data-answer="answer" contenteditable="true"></td>
<td><span class="show">&#160;</span>
</td>
</tr>
<tr style="opacity:0;">
<td>____________________</td>
<td><span class="show">&#160;</span>
</td>
</tr>
</table>
</div>
<div class="result" data-act="1" style="position:absolute;left:65px;top:173px;width:170px;height:125px;cursor:pointer;border:1px solid;">
</div>
</div>




Answer

As per my understanding user will be writing answer in <td class="txt" data-answer="answer" contenteditable="true"></td> which contains the reference answer to compare with; you may try below code:

$(function() {
  $("#p28-textid39").hide();
  $(".result").click(function() {
    $("#p28-textid39").show();

    var sibAnwserDiv = $(this).prevAll(".act1").first(); //grab the wrapper Div in which <table> is present
    var targetTD = $(sibAnwserDiv).find("td.txt");

    var data_answer = targetTD.data("answer"); //get the reference answer
    var content = $.trim(data_answer.text()); //get the answer entered by user

    if (content == data_answer) {
      alert("correct");
    } else {
      alert("incorrect");
    }
  });
});