Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting Select value on page load

Tags:

html

jquery

php

Many instances when I have html like this, i follow it with jquery to set the value. However I feel this is not the best way to do it and was looking for alternatives.

 <select class='papertype' name='papertype'>
      <option value='glossy'>Glossy</option>
      <option value='matte'>Matte</option>
      <option value='luster'>Luster</option>
      <option value='metallic'>Metallic</option>
 </select>

$(document).ready(function(){
    $('.papertype').val('<?php print $image->paper_type; ?>');
}

Im hoping to do this without using any type of javascript, completely server side. An important factor thats causing the problem is that the page I am coding right now has multiple instances of .papertype, all of which will have different values. Thanks for any help!

like image 436
Johnny Craig Avatar asked Jul 06 '26 18:07

Johnny Craig


2 Answers

 <select class='papertype' name='papertype'>
      <option value='glossy' <?php echo ($image->paper_type == 'glossy' ? ' selected="selected"' : ''); ?>>Glossy</option>
      <option value='matte' <?php echo ($image->paper_type == 'matte' ? ' selected="selected"' : ''); ?>>Matte</option>
      <option value='luster' <?php echo ($image->paper_type == 'luster' ? ' selected="selected"' : ''); ?>>Luster</option>
      <option value='metallic' <?php echo ($image->paper_type == 'metallic' ? ' selected="selected"' : ''); ?>>Metallic</option>
 </select>

Of course, you can do that in a more elegant way on a higher abstraction level with arrays etc., but you get the idea.

like image 191
Quasdunk Avatar answered Jul 09 '26 07:07

Quasdunk


<?php
$options = Array(
    'glossy' => 'Glossy',
    'matte' => 'Matte',
    'luster' => 'Luster',
    'metallic' => 'Metallic'
);
echo "<select class='papertype' name='papertype'>";
foreach($options as $k => $v) {
    echo "<option value='$k'";
    if( $image->paper_type == $k) echo " selected";
    echo ">$v</option>";
}
echo "</select>";
?>

Something like that?

like image 38
Niet the Dark Absol Avatar answered Jul 09 '26 06:07

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!