javascript - JQuery populating select box but after post options disappear -
i have svg map. when clicks on state say, "kansas" displays form , populates state select box state clicked on say, it's kansas. code - this working fine. code in head.
var itemval= '<option value="'+data.name+'">'+ statedata[data.name].fullname+'</option>'; $("#selitem").html(itemval); when form submitted , posts same page, i'm using
<form method="post" action="theform.php" onsubmit="return validateform(this);"> when page post same page select box empty. select box there no option.
i've searched on google found code below plus few similar ways don't work. i've used code in head , under select no luck.
var selectedval = $("#selitem").val(); $("#selitem").val(selectedval); **html** <select id="selitem"><option></option></select> i've been working on hours can't seem find solution.
can tell me how keep select value after form has been submitted , returns same page?
when page loads need check presence of posted value, , if it's there pass php value either javascript code populate select option, or use directly in html creating select options.
first off, should give select name attribute in html value passed $_post array in php:
<select id="selitem" name="selitem">
here's 1 way can populate in javascript (note code relies on var statedata being in same scope):
$(document).ready(function(){ <?php if (!empty($_post['selitem'])): ?> var posted_state = '<?php echo $_post['selitem'];?>'; if (statedata[posted_state] !== undefined) { var itemval= '<option value="'+posted_state+'" selected>'+ statedata[posted_state].fullname+'</option>'; $("#selitem").html(itemval); } <?php endif; ?> }); edit: alternative above put in html select tag:
<select id="selitem" name="selitem"> <?php if (!empty($_post['selitem'])): ?> <option value="<?php echo $_post['selitem'];?>" selected> <?php echo $_post['selitem']; // better if can replace fullname ?> </option> <?php else: ?> <option></option> <?php endif; ?> </select> note method has couple issues it's written. first off, option text in example won't state full name abbreviation. next, shouldn't trust contents of $_post because malicious user can change value didn't intend be. better validate value of $_post['selitem'] in php code handles post make sure 1 of correct values before using it. why in previous example did check if (statedata[posted_state] !== undefined) before attempting add value select.
edit:
to provide state fullname php need array of states defined on php side (i see in javascript code client side).
so in php if have like:
$states = array( 'ak' => 'alaska', 'al' => 'alabama', // etc... ); then can use posted state abbreviation fullname:
if (array_key_exists($_post['selitem'], $states)) $fullname = $states[$_post['selitem']];
Comments
Post a Comment