Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

jQuery: Disable select options where value begins with xyz

Using jQuery, how can I disable all select options that begin with "xyz"?

In this example, only the last 3 options should be disabled:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<style type="text/css">

option:disabled {
background: red;
opacity: 0.3;
}

</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

 $('#xyz option').prop('disabled',true)

});
</script>

</head>
<body>
 <div>
  <select id="xyz">
   <option value="xyz">xyz</option>
   <option value="abc">abc</option>
   <option value="123" selected="selected">123</option>
   <option value="xyz1">xyz1</option>
   <option value="xyz2">xyz2</option>
   <option value="xyz3">xyz3</option>
  </select>

 </div>
</body>
</html>

Open in new window

Avatar of Scott Fell
Scott Fell
Flag of United States of America image

$('#xyz option').each(function(){
  var val=$(this).val();
  var n=val.substring(0,3);

  if(n=='xyz'){
   $(this).prop('disabled',true); 
  }

});

Open in new window

http://jsbin.com/ELArIwI/1/edit?html,js,output
ASKER CERTIFIED SOLUTION
Avatar of Pierre Cornelius
Pierre Cornelius
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm sure we can come up with even more multiple permutations of the same answer.  PierreC, what is the  point of changing to that permutation?  Is it better? or just different?
you tell me, padas.

What is easier?
adding "[value^="xyz"]" to already exisiting code

or reinventing the wheel?

Is it better to
ask JQuery for a list of items and then finding those we are interested in, or
ask JQuery for the list we are interested in
Good point