Home jquery Selecting a select element with jQuery

Selecting a select element with jQuery

Author

Date

Category

I have a problem like this:
There is Select:

& lt; select id = "make" name = "make" & gt;
  & lt; option value = "0" & ​​gt; ---------------------- & lt; / option & gt;
  & lt; option value = "Mercedec" & gt; Mercedec & lt; / option & gt;
  & lt; option value = "Mazda" & gt; Mazda & lt; / option & gt;
  & lt; option value = "Audi" & gt; Audi & lt; / option & gt;
  & lt; / select & gt;

And I wrote js code to the console:

$ ("# make [value = 'Mazda']"). attr ("selected", "selected");

Returns the desired element option, selected = “selected”, but I’m looking at the list and the first option (value = 0) is still selected.

$ ("# make [value = 'Mazda']"). attr ("selected", "");

Answer 1, authority 100%

I would venture to suggest that this is some feature of the JS implementation in Chrome. Your code runs quite well under IE (10th version) and Firefox (23rd). But in Chrome (28th) the problems you described occur. I have not tested it in Opera.
One way or another, with the help of this miracle crutch:

var val = text = 'Mazda';
$ ("select option [value =" + val + "]"). attr ('selected', 'true'). text (text);

Answer 2, authority 70%

In current versions of jQuery, to change option to select and select checkbox , use the .prop () method

$ ('select option [value = "Mazda"]'). prop ('selected', true);

This method modifies the javascript property of the corresponding option object and does not add attributes, that is, nothing will change in the markup. Although adding the attribute so far works with option (checked in Opera), it doesn’t work with checkbox .


Answer 3, authority 50%

Try it

$ ('# make'). val ('Mazda')

Answer 4, authority 20%

To change things like selected and checked, you need to use prop, not attr.


Answer 5, authority 10%

$ ("# make"). val ("Mazda"). change ()

Answer 6

I don’t understand the question, but it is possible

$ ("# make option [value = 'Mazda']"). val ('Mazda'). attr (" selected ", true);

Answer 7

I personally prefer the following one-liner method:

$ ("select"). val (""). trigger ("chosen: updated")

Should work in all browsers.
Accordingly, instead of an empty line, you need to use the text of the first option ‘a, but as a rule, the default option should be empty, and not contain 0, etc.

Accordingly, substituting the value of any option ‘and you can select it.


Answer 8

The selected attribute must be applied to the option element:

$ ("# make & gt; option [value = 'Mazda']"). attr ("selected", "selected" );

Answer 9

$ ("# make"). val ("Mazda");

That’s all.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions