Error selecting select text

0

Good evening, everyone. I have a select that lists the cities of the respective state. I'm using this code to select a city from the list:

$('#txtCidades option').removeAttr('selected').filter("[text=São Lourenço da Mata]").attr('selected', "selected").change();

When the text is made up of more than one word, I get the following error message:

Uncaught Syntax error, unrecognized expression: [text = São Lourenço da Mata]

But when the city consists of only one word, it normally selects without error.

Does anyone give a light?

    
asked by anonymous 19.03.2015 / 23:25

3 answers

0

So:

$('#txtCidades option').removeAttr('selected').filter("[text='São Lourenço da Mata']").attr('selected', "selected").change();
    
19.03.2015 / 23:27
0

When you use [text=São Lourenço da Mata] this implies that you have in HTML a / option element with this attribute. This is how jQuery reads your query. Something like

<option text="São Lourenço da Mata">foo</option>

I imagine this is not the case, but you want to filter the textContent of this option. In this case I suggest you use a function in the jQuery method.

$('ul li').removeAttr('selected').filter(function () {
    return $(this).text() == 'São Lourenço da Mata'; 
 }).attr('selected', "selected");
    
19.03.2015 / 23:47
0

Hello, @Sergio, HTML

<select id="txtUF">
    <option value="">Selecione o estado</option>
    <option value="1">AC</option>
    <option value="2">AL</option>
...
    <option value="24">SC</option>
    <option value="26">SP</option>
    <option value="25">SE</option>
    <option value="27">TO</option>
</select>
<br/>
<select id="txtCidades">
    <option>Selecione um estado para listar as cidades</option>
</select>

I have a WebMethod (C #) which loads listing of cities according to the selected UF. So far so good. But I also implemented the search of the data of the cadastre, being therefore, I also needed to select the option of select "txtCities" with the city of the cadastre returned.

The problem was this: WebMethod would locate the correct cadastral data, but I had neglected the jQuery syntax to assign the option to select the text returned by the query.

The correct jQuery:

'$('#txtCidades option').removeAttr('selected').filter("[text='" + Cidade + "']").attr('selected', "selected").change();'
    
22.03.2015 / 14:37