1

This is my select tag in HTML I am retriving the value as shown below

Could anybody please tell me how can retrieve the value before Colon (:) for instance if it is 200:Java programming language I need only 200 as value

<select name = "book" id="selSeaShells">
  <option></option>
  <option value = "100:C programming language">C programming language</option>
  <option value = "200:Java programming language">Java programming language</option>
</select>

function myFunction() {
    var quantityvalue = document.getElementById("quan").value;
    var selObj = document.getElementById('selSeaShells');
    var optionselectedvalue;
    var optionselectedtext;

    for (i = 0; i < selObj.options.length; i++) {
        if (selObj.options[i].selected) {
            optionselectedvalue = selObj.options[i].value;
        }
    }
}
karthikr
  • 97,368
  • 26
  • 197
  • 188
user1023918
  • 29
  • 1
  • 3
  • 1
    Your example does not have a DOM element with id 'quan'. – Rob Raisch Jul 09 '13 at 21:18
  • Perhaps you may like to use [data-attributes](http://stackoverflow.com/questions/4564659/adding-additional-data-to-select-options-using-jquery). – cr0 Jul 09 '13 at 21:20

3 Answers3

2

In your example, you can do

optionselectedvalue.split(':')[0]

A demo here

karthikr
  • 97,368
  • 26
  • 197
  • 188
1

You can grab the value from it using either jquery or regular javascript commands.

Then with the value use the split function use this code on the String value .split(":") it returns an array you will want the first index so the total code to put on the string is .split(":")[0].

If you want it as a number use the parseInt or parseFloat function on the result.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Legion
  • 796
  • 7
  • 12
1

Credit to Karthikr. That is a good answer I want to add that you can get rid of that for loop and increase the performance of your code by using selectedIndex.

var optionselectedvalue = selObj.options[selObj.selectedIndex].value;

Here is a jsbin demonstrating it (Karthikr's answer is also in the bin)

BenJamin
  • 783
  • 4
  • 17