Skip to content Skip to sidebar Skip to footer

Jquery Populating Select Box But After Post Options Disappear

I have an SVG map. When someone clicks on a state say, 'Kansas' it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - T

Solution 1:

When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.

First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:

<select id="SelItem" name="SelItem">

Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):

$(document).ready(function(){
    <?phpif (!empty($_POST['SelItem'])): ?>
        var posted_state = '<?phpecho$_POST['SelItem'];?>';
        if (stateData[posted_state] !== undefined) {
            var itemval= '<optionvalue="'+posted_state+'"selected>'+ stateData[posted_state].fullName+'</option>';
            $("#SelItem").html(itemval);
        }
    <?phpendif; ?>
});

EDIT: An alternative to the above would be to put it in the html for the select tag:

<selectid="SelItem"name="SelItem"><?phpif (!empty($_POST['SelItem'])): ?><optionvalue="<?phpecho$_POST['SelItem'];?>"selected><?phpecho$_POST['SelItem']; // this would be better if you can replace it with fullname ?></option><?phpelse: ?><option></option><?phpendif; ?></select>

Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.

EDIT:

To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).

So in php if you have something like:

$states = array(
    'AK' => 'Alaska',
    'AL' => 'Alabama',
    // etc...
);

Then you can use the posted state abbreviation to get the fullname:

if (array_key_exists($_POST['SelItem'], $states))
    $fullname = $states[$_POST['SelItem']];

Post a Comment for "Jquery Populating Select Box But After Post Options Disappear"