user1434156
user1434156

Reputation:

Using .split in jquery and extracting the first item from array

I have a basic select field that display options with values that have a numeric value combined with the a letter value such as <option value=”36:a”>Hi</option>. I am trying to extract just the numeric from the value. I worked mainly through php and used explode and then call the first item in the array [0] but not sure how to perform this in jquery/javascript. I am using split and then assigning pointing to the first item but that is not working. How can properly I extract just the numeric value from the option value?

var content = "<option value=\"36:Hi\">Hi</option>";
$(...).find(..).on('change', function(){ 
if($this.val().split(":")[0] == 36){    

}
});

Upvotes: 1

Views: 8725

Answers (2)

Sterling Archer
Sterling Archer

Reputation: 22395

Use parseInt(), it takes a parameter with a number first (else it will yield NaN), and will parse until no number is found. So parseInt("36:hi") will log 36

So:

if(parseInt($(this).val()) == 36)

Upvotes: 1

codingrose
codingrose

Reputation: 15699

Change

if($this.val().split(":")[0] == 36){  

to

if($(this).val().split(":")[0] == 36){  

Upvotes: 4

Related Questions