Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Output only the first word from select list value - jQuery?
Let’s say the following is our select −
<select id="firstValueDemo" onchange="showFirstValue(this)"> <option value="John Smith">Get First Name</option> <option value="David Miller">Get First Name Only</option> </select>
To get only the first word, use split() on the basis of space and can select the 0th index value.
Example
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<select id="firstValueDemo" onchange="showFirstValue(this)">
<option value="John Smith">Get First Name</option>
<option value="David Miller">Get First Name Only</option>
</select>
</body>
<script>
function showFirstValue(choosenObject) {
var allValues = choosenObject.value.split(" ");
var firstValue = allValues[0];
console.log("The first Name=" + firstValue);
}
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −
Output
This will produce the following output on console −

Now you can select the value which will show the first word. This will produce the following output −

Output
The output in console −

Advertisements