0

From the topic - "jQuery - setting the selected value of a select control via its text description" - I'm using this to select my value

$("#PersonList option").filter(function() {
  return $(this).val() == <?php $PHPUser ?>;
}).attr('selected', true);

But what if I also want to STYLE it with yellow AND change the text.

I could repeat as needed.. but that seems over-coding...

ADD YELLOW:

$("#PersonList option").filter(function() {
  return $(this).val() == <?php $PHPUser ?>;
}).addClass(UserAccent);

ADD TEXT:

$("#PersonList option").filter(function() {
  return $(this).val() == <?php $PHPUser ?>;
}).innerText('Myself: ' + $PHPUser);

How would I do this in one evaluation?

Community
  • 1
  • 1
Allen May
  • 323
  • 3
  • 10
  • You'll note the answers are all mentioning chaining, which [this question](http://stackoverflow.com/questions/7475336/how-does-jquery-chaining-work) asks about. Chaining is a fairly powerful concept, so you should read up on it. – ajp15243 Apr 01 '13 at 18:50
  • Sometimes its finding the right term to use vs. what you ask. I will focus on "chaining" as you suggest. – Allen May Apr 03 '13 at 11:07

2 Answers2

2

When facing this problem, the usual approach is to store the filtered set in a variable :

var elements = $("#PersonList option").filter(function() {
  return $(this).val() == <?php $PHPUser ?>;
});
elements.prop('selected', true);
elements.addClass(UserAccent);
elements.text('Myself: ' + $PHPUser);

This is fine, and that doesn't require any specific JQuery knowledge.

But jQuery enables chaining, that is most functions return the receiver so that you call another function on it, which lets you do this :

$("#PersonList option").filter(function() {
  return $(this).val() == <?php $PHPUser ?>;
}).prop('selected', true)
  .addClass(UserAccent)
  .text('Myself: ' + $PHPUser);

And as was noticed by adeneo, you should use prop to set a boolean element property like selected.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

You'd just chain that on there :

$("#PersonList option").filter(function() {
   return this.value == "<?php echo $PHPUser; ?>";
}).prop('selected', true)
  .addClass('someClass')
  .text('Myself: <?php echo $PHPUser; ?>');
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I had to change "this.value" to "$(this).val()" but after that it behaves as I wanted. Thank you for your help!! – Allen May Apr 02 '13 at 20:22