简体   繁体   中英

Select form option on page load

I would like to select the option contained within a php variable on page load.

<?php
$pre = 78;
?>

<select id="form8" name="form8">
<option value="15">15</option>
<option value="25">25</option>
<option value="64">64</option>
<option value="78">78</option>
<option value="82">82</option>
</select>

<script>
$(document).ready(function(){
$("form8").val("<?php echo $pre; ?>");
}
</script>

Expected output should be,

<select id="form8" name="form8">
<option value="15">15</option>
<option value="25">25</option>
<option value="64">64</option>
<option value="78" selected="selected">78</option>
<option value="82">82</option>
</select>

http://jsfiddle.net/qQZVN/1/

$('#form8').val("<?php echo $pre; ?>") ;

Why not just use HTML to set selected='selected' ? Seems easier, and supports non-JS users.

$(document).ready(function(){
$("#form8").val(<?php echo $pre; ?>);
}
$('select#form8').val('<?php echo $pre; ?>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM