Page 1 of 1

select object selected text

Posted: Wed May 23, 2018 10:40 am
by Timo
I have a Select Object (ID: select_field) with multiple set to Yes. Before saving the record, I check if the selected option contains a specific text.
As soon as the text contains a space, indexOf() always returns -1.

This works when I pass a string without spaces to indexOf()

Code: Select all

var s = $('#select_field').find("option:selected").text(); // s = "123 Hello World"
var i = s.indexOf('Hello');
alert(i);
This doesn't work when I pass a string with spaces to indexOfO

Code: Select all

var s = $('#select_field').find("option:selected").text();  // s = "123 Hello World"
var i = s.indexOf('Hello World');
alert(i);

Re: select object selected text

Posted: Fri May 25, 2018 12:32 pm
by toms
Hi,

The text that is returned by .find("option:selected").text() contains the character 160 (Non-breaking space). Here's a fix to replace it with an ordinary space.

Code: Select all

function fixSpaces(s) {
  return s.replace(/\s/g /* all kinds of spaces*/," " /* ordinary space */);
}

var s = fixSpaces($('#select_field').find("option:selected").text());  
var i = s.indexOf('Hello World');
alert(i);

Re: select object selected text

Posted: Mon Jun 04, 2018 8:20 am
by Timo
You're a genius, thank you!

Re: select object selected text

Posted: Tue Jun 05, 2018 4:08 am
by admin
.