如何在条件存在时选择特定选项

如何在条件存在时选择特定选项

问题描述:

I want to select the specific option in drop down list when a condition is existed.I set the Session in php and if the combo box has the value of 1 , it will be shown the option with value 1. I mean if session is 1, select the option with value of 1, if session is 2, select the option with vlaue of 2, and so on... . I want to set automatically select(I see the changes) with session in php. sth like blewo:

<select id="sel" >
  <option value='1'>one</option>
  <option value='2'>two</option>
  <option value='3'>three</option>
</select>
 <?php $_SESSION['num']='1'; ?>
<script>
  //must be shown the option with value of `1`.
<script>

Try this .

<select id="sel" >
  <option value='1'>one</option>
  <option value='2'>two</option>
  <option value='3'>three</option>
</select>
 <?php $_SESSION['num']='1'; ?>
<script>

    //set local variable value so that I don't have to do it for each of the following ways to do this.
    var num =  "<?php echo $_SESSION['num']; ?>";

    //normal javascript 
    document.getElementById("sel").value = num;

    //using jQuery  
    $("#sel").val(num);

<script>

Or this try vikingmaster's way

Just set the value with the selected attribute

<select id="sel" >
  <option value='1' selected>one</option>
  <option value='2'>two</option>
  <option value='3'>three</option>
</select>
 <?php $_SESSION['num']='1'; ?>
<script>
  //alternately, set it explicitly
  var element = document.getElementById('sel');
element.value = 1;
<script>

<select id="sel" >
  <option value='1' <?php if($_SESSION['num']=='1') echo "selected"; ?> >one</option>
  <option value='2' <?php if($_SESSION['num']=='2') echo "selected"; ?> >two</option>
  <option value='3' <?php if($_SESSION['num']=='3') echo "selected"; ?> >three</option>
</select>

You don't necessarily need js to do this. You can simply use php since you're already grabbing the num from the session. Easiest way to do it would be:

<select id="sel" >
    <?php if($_SESSION['num'] == 1): ?>
        <option value='1' selected>one</option>
    <?php else: ?>
        <option value='1'>one</option>
    <?php endif; ?>
    <option value='2'>two</option>
    <option value='3'>three</option>
</select>

But if you want to use javascript(jQuery in particular here), you can do something like this:

<script>
    $(document).ready(function(){
        var num = <?php echo $_SESSION['num']; ?>;

        $('#sel > option').each(function(){
            if($(this).val() == num){
                $(this).prop('selected', true);
            }
        });
    });
</script>

Here's a fiddle.

There are a lot of ways to do this. This is what approach I would take, I'm sure others can provide just as viable or probably better answers.