I'm trying to use javascript to flag a word from a set list but it doesn't seem to be working. Basically I want the user to be able to type in a word and if it matches any on the list on the right it flags the word in red.
Any idea on what I am doing wrong?
http://jsfiddle.net/Copernicus76/rpuXW/embedded/result/
// Load the banned plates json data
var platesJson = (function () {
platesJson = null;
$.ajax({
'async': false,
'global': false,
'url': "bannedplates.json",
'dataType': "json",
'success': function (bannedplates) {
platesJson = bannedplates;
}
});
return platesJson;
})();
$(document).ready(function () {
// Draw the list //
$.each(platesJson, function (i) {
$('#plate-list').append('<div class="row-' + i + '">' + platesJson[i].plate + '</div>');
});
// Search the banned plates //
$('#plate-text').keyup(function () {
var result = '';
var plateRow = '';
var scrollPosition;
var searchText = $('#plate-text').val().toUpperCase();
$.each(platesJson, function (i) {
if (searchText == platesJson[i].plate) {
result = 'banned';
plateRow = i;
scrollPosition = i * 19;
}
});
if (/\S/.test(searchText)) {
if (result == 'banned') {
$('#plate-intro,#plate-ok').hide();
$('#plate-banned').show().fadeOut(1500);
$('#plate-text').addClass('banned');
$('#plate-list').animate({
scrollTop: scrollPosition
}, 1000);
$('#plate-list div.row-' + plateRow + '').addClass('banned');
} else {
$('#plate-intro,#plate-banned').hide();
$('#plate-ok').show().fadeOut(1500);
$('#plate-text').removeClass('banned');
}
} else {
$('#plate-text').val('');
$('#plate-ok,#plate-banned').hide();
$('#plate-intro').show();
}
});
}); // end document ready
var platesJson = (function () {
platesJson = null;
$.ajax({
'async': false,
'global': false,
'url': "bannedplates.json",
'dataType': "json",
'success': function (bannedplates) {
platesJson = bannedplates;
}
});
return platesJson;
})();
That's not how ajax works. The first a
means asynchronous
, so the success function will run whenever the response comes back. That doesn't happen immediately, it could take a few minutes or it could fail totally. The success
method is a callback . That's where you want to do the magic.
$.ajax({
'async': false,
'global': false,
'url': "bannedplates.json",
'dataType': "json",
'success': function (bannedplates) {
$.each(bannedplates, function (i) {
$('#plate-list').append('<div class="row-' + i + '">' + bannedplates[i].plate + '</div>');
});
$('#plate-text').keyup(function () {
// ...the rest of your code
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.