I'm building a sortable word quiz where the user has to put the words of a sentence in the correct order. The idea is that the user drags the words from below the sentence and then the word blocks light up green or red depending on if their solution matches the answer.
I'm using jQuery and the jQuery UI sortable method. The jQuery sortable and HTML & CSS all works fine, but in my JavaScript if statement comparing the answer string with the users solution string is always false no matter what. The really odd thing is console.log shows the strings as being identical in every way as far as I can tell. i.e typeof show they are both of type "string" and length of both strings shows 31. I even added some code to chop white space off the ends of the strings to sanitize them. The answer is being stored in a variable called answer and the users solution is stored in a variable called solution
The demo code is live on codepen here:
https://codepen.io/codepajamas/pen/zYGMveN?editors=1111
You can open the console to see the result.
Following is the HTML, CSS, and JavaScript Code:
<div class="sentence" data-answer="Henry wants to go to the store!">
<span class="sentence-start">Henry</span>
<ul class="words place-words"></ul>
<span class="sentence-end">to the store!</span>
</div>
<ul class="words supply-words"><li class="word">wants </li><li class="word">go </li><li class="word">to </li></ul>
$(function () {
var answer = $('.sentence').data('answer');
$('.words').sortable({
connectWith: '.place-words, .supply-words',
beforeStop: function () {
if ($('.supply-words').text() === '') {
var sentence_start = $('.sentence-start').text(),
placed_words = $('.place-words').text(),
sentence_end = $('.sentence-end').text(),
combined = sentence_start+placed_words+sentence_end,
// get rid of line returns and white space at beginning and end of sentence
solution = combined.replace(/(\r\n|\n|\r)/gm,'').trimLeft().trimRight();
if (solution === answer) {
console.log('correct');
$('.words').not('.supply-words').removeClass('wrong').addClass('correct');
} else {
console.log('wrong');
$('.words').not('.supply-words').removeClass('correct').addClass('wrong');
}
}// outer if
}// beforeStop function
});
$('.words, .answer').disableSelection();
}; //end document ready
.sentence {
margin: 0 0 10px 0;
}
.words, .place-words {
display: inline-block;
margin: 0 5px 0 5px;
padding: 0;
}
.place-words, .supply-words {
width: auto;
min-width: 135px;
height: 30px;
border: 1px dashed #ccc;
vertical-align: bottom;
}
.word {
display: inline-block;
margin: 0;
border: 1px solid #000000;
padding: 5px 10px;
cursor: pointer;
}
.correct {
background: lime;
}
.wrong {
background: pink;
}
Let me know if anyone has any questions. Any help is appreciated. I think I need a fresh set of eyes on this. Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire