A user types words into an input field, after clicking the Go button, little images with file names that match the keywords pop up in a certain place in the hierarchy. I just wanted someone to double check this script to see if there’s any bugs in it, as it doesn’t appear to work. The input is a comma separated list, hence the trim.
$(".Go").live('click', function(){
var words = [];
jQuery.each(jQuery.trim(jQuery("#input").val()).split(","), function(index, value){
words.push(jQuery.trim(value));
});
for(i=0; i > words.length(); i++){
$('#Place').append('img').attr("src", words[i]+'.png');
}
});
Thanks goes out to Femi, who formulated this script for me.
Here’s a working demo with various improvements.
The reasons your code won’t work are:
i > words.length()will always be false as you’re initially setting it to0, that needs to be<.lengthis a property, not a function. Remove the brackets.Your syntax for appending a new
imgelement just appends a string of
‘img’. In order to use append() to append a new element like that, you’ll need to use the overload that takes a function.
Not strictly a bug, but there’s a lot
of unnecessary code in there.
split()returns an array already, so looping
through that array to put each array
element into another array is
redundant. There’s also no reason to
new up the
wordsarray beforeassigning it.
There’s no particular reason to use
live()if you’re not dynamicallyadding elements with a class of
go.You could simply use
click()instead.
EDIT:
In answer to the comments, here’s how to add the images to two different containers based on the word.
EDIT 2:
and to add the image to a different container based on whether the ‘word’ is upper case, lower case, numbers or symbols (ie: none of the above!)