lyyka
lyyka

Reputation: 560

Select specific <option> from <select> while having a value from PHP

I have the following HTML code for my element and it is populated with elements.

<select name="category" class = "form-control">
  <option value = "Awearness">Awearness</option>
  <option value = "ITandTechnology">IT and Technology</option>
  <option value = "Physics">Physics</option>
  <option value = "Sport">Sport</option>
  <option value = "Science">Science</option>
  <option value = "Social">Social</option>
</select>

I also have PHP code above tag that gets me value of category from MySQL database. So for example:

...$category = "Sport";...

What I need to know is, is there a way to select certain option when page loads that corresponds to $category variable I got in PHP? So if

...$category = "Sport";...

it selects the Sport option from tags.

Upvotes: 0

Views: 69

Answers (2)

Shivam Som
Shivam Som

Reputation: 141

I suggest using JavaScript along with your php. For example,

<?php
$cat = 'Sport';
?>

<!DOCTYPE html>
<html>
<body>

<select name="category" class = "form-control" id = "i1">
  <option value = "Awearness">Awearness</option>
  <option value = "ITandTechnology">IT and Technology</option>
  <option value = "Physics">Physics</option>
  <option value = "Sport">Sport</option>
  <option value = "Science">Science</option>
  <option value = "Social">Social</option>
</select>

 <script>
    var a= document.getElementById('i1');
a.getElementsByTagName('option');

for(i=0;i<a.length;i++)
{

   if(a[i].value=='<?php echo $cat;?>')
   {
       a[i].setAttribute("selected","selected");
           break;
   } 

}

</script>   



</body>
</html> 

Upvotes: 0

M. Eriksson
M. Eriksson

Reputation: 13635

To set an option as selected on page load we can use the selected attribute.

<option value="some-value" <?= $category == 'some-value' ? 'selected' : '' >>....</option>

Then do the same for each option in your list.

Upvotes: 2

Related Questions