Kurkula
Kurkula

Reputation: 6762

jquery comparing json string with value

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;
        }
    }
});

Upvotes: 0

Views: 1364

Answers (1)

codingrose
codingrose

Reputation: 15699

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.

Upvotes: 1

Related Questions