简体   繁体   中英

Keep data in html form after form submitted

i was trying to keep the input in html form field after submission occur. so, i've used like

<input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'column_name' ?>" />

its working nicely if input type is text . its not working with <textarea> & <select> .

<textarea> s don't have a value attribute. They have a body:

<textarea name="myField2"><?php echo isset($_POST['myField2']) ? $_POST['myField2'] : 'column_name' ?></textarea>

Likewise, <select> s do not have a value attribute . The value of a <select> is determined by the contained <option> s which have the selected attribute . This one is left as an exercise to the reader. Hint: you'll need to iterate over the <select> 's <option> s and conditionally add the selected attribute to one or more of the <option> s.

For textarea:

<textarea><?php echo isset($_POST['myField']) ? $_POST['myField'] : 'column_name' ?></textarea>

For select:

<select>
   <option value='xx' <?php echo isset($_POST['myField'])&&$_POST['myField']=='xx'?'selected="selected"':''?>>XX</option>
   <option value='yy' <?php echo isset($_POST['myField'])&&$_POST['myField']=='yy'?'selected="selected"':''?>>YY</option>
</select>

If you have are using jQuery, I prefer to populate the select using javascript:

<select name='myField'>
    <option value='xx'>XX</option>
    <option value='yy'>YY</option>
</select>
<?php if(isset($_POST['myField'])):?>
<script type='text/javascript'>
    $("select[name=myField] option[value='<?php echo $_POST['myField']';?>']").attr("selected","selected");
</script>
<?php endif; ?>

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