Reputation: 113
I have an array with some text:
var values = ['text1', text2',...]
This array fills a select with the text and when the user selects an option, creates an ul list with the value and another array with all the options the user has selected. What I want is to let the user delete that element from the list and from the array, the problem is when I try to get the index of the li selected
//Here it appends the element selected to the list
$('#container ul#header').append('<li class="list-group-item">' + text + '<span class="glyphicon glyphicon-remove pull-right" aria-hidden="true"></span> </li>');
function deleteElement(){
$(".list-group-item span").click(function(){
var index = values.indexOf( $(this).parent().text() )
});
}
But it always return -1, but when I hardcode the element text I want to delete it does find it
values.indexOf( $(this).parent().text() ) //Doesnt work
values.indexOf( 'text1' ) //This works
EDIT:
$(this).parent().text() returns the text from the li
On the console thats what it shows, but when I console the length of the string, it returns the size plus one:
//String
values.indexOf( $(this).parent().text().length ); //7
values.indexOf( 'string'.length ); //6
So I guess it has to do with this, I'm trying to figure why it returns plus one, I gues it has to do with the , I'm not sure.
Upvotes: 1
Views: 50
Reputation: 337590
You need to trim()
the text()
due to the whitespace after the </span>
:
var index = values.indexOf($(this).parent().text().trim());
Upvotes: 4