onselect javascript
- Published
- Reading time
- 2 min read
- Length
- 303 words
On this page
Understanding onselect javascript#
As a web developer, you may come across situations where you want to perform some action when an option is selected from a dropdown list. In such cases, you can use the onselect JavaScript event.
What is onselect JavaScript event?#
The onselect event is triggered when a user selects some text or an option from a dropdown list. It can be used to perform some action, such as displaying the selected text or value in an alert box.
Examples of using onselect JavaScript event#
Here are some examples of how you can use the onselect JavaScript event:
- Display selected text: You can display the selected text in an alert box using the following code:
<script>
function displaySelectedText() {
var selectedText = window.getSelection().toString();
alert(selectedText);
}
</script>
<p onclick="displaySelectedText()">Select some text</p>
- Display selected option: You can display the selected option from a dropdown list in an alert box using the following code:
<select onchange="displaySelectedOption()">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<script>
function displaySelectedOption() {
var selectedOption = document.querySelector('select').value;
alert(selectedOption);
}
</script>
- Perform action on selected option: You can perform some action based on the selected option from a dropdown list using the following code:
<select onchange="performActionOnSelectedOption()">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<script>
function performActionOnSelectedOption() {
var selectedOption = document.querySelector('select').value;
if(selectedOption == 'option1') {
// perform action for option 1
} else if(selectedOption == 'option2') {
// perform action for option 2
} else if(selectedOption == 'option3') {
// perform action for option 3
}
}
</script>
These are just a few examples of how you can use the onselect JavaScript event. With a little creativity, you can use it to perform many other actions on your web pages.