JQuery value obtained from dropdown list

traditionally write

var value = $("#drop-down-id").val();

to get the value. In my case, some of the options contain a few words with spaces such as "Allow all," "Internet users," etc. What I get in VALUE is only "Allow", then jquery truncates words after a space. Is there any other way to solve this problem?

+3
source share
3 answers

If you have a value enclosed in <option></option>and you are not using the val attribute directly, you can do:

var value = $('#drop-down-id option:selected').text();
+9
source

try:

var value = $("#drop-down-id option:selected").attr("value");
+6
source

. . , , , .

HTML, , , .

:

<option value=John Doe>John Doe</option>

It will only return the first word as the actually selected value, because space is actually an attribute delimiter in HTML; now you get the value "John" as the value, and "Doe" is considered as another (non-existent) HTML attribute.

It is right.

<option value="John Doe">John Doe</option>

This way you get the "John Doe" value as the value.

+1
source

Source: https://habr.com/ru/post/1721698/


All Articles