Reputation: 11
I don't why my website doesn't go through the if statement. The objective is to display an image when I click a button, but it gets stuck. If anyone could help I would be very happy :D
function showllum() {
$.get('llum.txt', function(data) {
alert(data);
if (data === "Llum") {
alert("1");
$('#showdada').empty();
$('#showdada').prepend($('<img>', {
id: 'llumpng',
src: 'llum.png'
}
))
} else if (data === "Molta Llum") {
alert("2");
$('#showdada').empty();
$('#showdada').prepend($('<img>', {
id: 'moltallumpng',
src: 'molta llum.png'
}
))
} else if (data === "Poca Llum") {
alert("3");
$('#showdada').empty();
$('#showdada').prepend($('<img>', {
id: 'pocallumpng',
src: 'poca llum.png'
}
))
} else if (data === "Fosques") {
alert("4");
$('#showdada').empty();
$('#showdada').prepend($('<img>', {
id: 'fosquespng',
src: 'fosques.png'
}
))
}})}
Upvotes: 0
Views: 49
Reputation: 14927
In addition to the carriage return in the string that was causing the original problem (which is fixed with data.trim()
), your code can be simplified since there's a pattern to your logic - each case clears the showdada
element and then prepends an image using the pattern src = `${data.trim()}.png`
in lowercase and then the id
removes all spaces and periods from the src
:
function showllum() {
$.get('llum.txt', function(data) {
$('#showdada').empty();
const src = `${data.trim()}.png`.toLowerCase();
$('#showdada').prepend($('<img>', {
id: src.replace(/[ .]/g,''),
src
})
});
}
Upvotes: 0
Reputation: 1684
You need to add a dataType - http://api.jquery.com/jQuery.ajax/
$(document).ready(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
if(data === '*'){...}
}
});
});
But even if you change to this, you won't get results from a localdrive, you'll need an actual http server to serve the static textfile. Please check the network requests and update here what response you get.
Upvotes: 1