Home html SELECT & GT; & GT; & GT; Option & gt; & gt;...

SELECT & GT; & GT; & GT; Option & gt; & gt; & gt; SELECTED VALUE

Author

Date

Category

How in JavaScript designate the selected value variable (take the value selected)? In short, here is the source code, something like that. Here’s how to write this code correctly so that the variable sets its value from the list (from the selected option).

var variable = document.getelementByname ('name select'). selected value


Answer 1, Authority 100%

If you write on pure JS, you can use such a code:

HTML:

& lt; select id = "selectid" onchange = "change ()" & gt;
  & lt; optional = "0" & ​​gt; Select Option & LT; / Option & GT;
  & lt; optional = "1" & gt; Text1 & lt; / Option & GT;
  & lt; optional = "2" & gt; Text2 & Lt; / Option & GT;
  & lt; optional = "3" & gt; Text3 & Lt; / Option & gt;
& lt; / select & gt;

JS:

var select, value, text;
FUNCTION CHANGE () {
  select = document.getelementByid ("SELECTID"); // Select SELECT by ID
  Value = select.Options [select.selectedIndex] .Value; // Value value for selected option
  text = select.Options [select.selectedIndex] .text; // Text value for the selected option
  Alert ("Value:" + Value + "\ Nectxt:" + Text); // Conclusion Alert to verify values
}

View Example


But you can write it on JQuery , I like this option more:

HTML:

& lt; select id = "selectid" & gt;
  & lt; optional = "0" & ​​gt; Select Option & LT; / Option & GT;
  & lt; optional = "1" & gt; Text1 & lt; / Option & GT;
  & lt; optional = "2" & gt; Text2 & Lt; / Option & GT;
  & lt; optional = "3" & gt; Text3 & Lt; / Option & gt;
& lt; / select & gt;
& lt; p & gt; Value: & lt; span id = "value" & gt; 0 & lt; / span & gt; & lt; / p & gt;
& lt; p & gt; Text: & lt; span id = "text" & gt; Select Option & lt; / span & gt; & lt; / p & gt;

JS:

$ (document) .ready (function () {
  $ ("# selectid"). Change (Function () {
    $ ("# Value"). Text ($ (this) .val ());
    $ ("# Text"). Text ($ ("# SELECTID Option: Selected"). text ());
  });
});

View example on jQuery

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