0

I am working on a question and answer comparison example where i am trying to compare question string with json data. Questions and answers will be pulled as json data. Could you please help me guiding fix for comparison problem.

My code is here

<label for="What_is_planning">What is planning</label>
<br>
<label for="What_is_implementing">What is implementing</label>
<br>
<div class="result"></div>


$(document).ready(function () {
    $('label').mouseover(function () {
        var helpString = this.firstChild.nodeValue.replace(':', '').trim();

        var answerString = "<br>No Answer";
        $(".result").html(" <hr><b>Guest: </b>" + helpString);
        $(".result").append(" <div><b>AskGFS: </b>" + answerString);
        console.log(helpString);
    });

    var QandAData = '{"gfsdata":[{"question":"what is planning","answer":"This is a important part of life"},' +
        '{"question":"what is implementing","answer":"this is followed by planning"}]}';

    //Comparing answers
    for (var i = 0; i < QandAData.length; i++) {
        if (QandAData[i].gfsdata.question == 'what is planning') {
            answerString = QandAData[i].gfsdata.answer;
        }
    }
});
3
  • can you tell me what is the data in answer string your getting !!!! Commented Dec 6, 2013 at 7:06
  • possible duplicate of How to parse JSON in JavaScript Commented Dec 6, 2013 at 7:06
  • FYI, there is no reason to use JSON here. You could just use an object literal and save the parsing step. Commented Dec 6, 2013 at 7:07

1 Answer 1

1

Try:

$(document).ready(function () {
    $('label').mouseover(function () {
        var helpString = this.firstChild.nodeValue.replace(':', '').trim();
        var answerString = "<br>No Answer";
        var QandAData = {
            "gfsdata": [{
                "question": "What is planning",
                "answer": "This is a important part of life"
            }, {
                "question": "What is implementing",
                "answer": "This is followed by planning"
            }]
        };
        for (var i = 0; i < QandAData.gfsdata.length; i++) {
            if (QandAData.gfsdata[i].question == helpString) {
                answerString = QandAData.gfsdata[i].answer;
            }
        }
        $(".result").html(" <hr><b>Guest: </b>" + helpString+" <div><b>AskGFS: </b>" + answerString);
    });
});

Updated fiddle here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.