简体   繁体   中英

Populate a list of fields from JSON after picking option in Select field ? PHP, JS, HTML

I am wanting to make my users life's easier by allowing them to complete forms faster.

I have placed a Pulldown/Select field in my form that contains a list of presets that are retrieved from the database.

So far I have managed to encode my PHP object that stores all the values that will go into the fields.

PHP Part

$values = new values(); 
    $field_values = json_encode($values);

JS Part

    <script>

        var field_values = JSON.parse( <?php echo $js_list; ?>);


    </script>

Example of 5 row of the JSON dataset

{"preset_name":["HORIZONTARIFF","1MEGVOICETARIFF","DN18STREAM","DN18STREAMGPRS","DN18STREAMLOWARPU"],"net":["ECL","ECL","ECL","ECL","ECL"],"inclusive":[2,1,0,3,0],"length":["18","12","36","36","36"],"data":[0.0292968448,0.019531264,0.0976562176,0.0976562176,0.0976562176]}

I used JSON.parse() as a tutorial said it is a lot safer than using eval()

All of what I have shown is working great and the JSON'd values are placed into my javascript.

So now I am onto the next stage which is; How on earth do I get these values into my fields on the form?

FYI

My select field is populated using a foreach() in PHP from DB.

I know what the logic is going to be but due to inexperience in Javascript/JSON I have no clue how to implement it.

Logic

  1. User selects option from list
  2. Javascript detects selection made
  3. Javascript finds the value of the selection made.
  4. Javascript searches through the JSON to find the matching value and the data associated with it.
  5. Javascript modifies the other fields and inputs the values from JSON.

Any resources or ideas are welcome!

Thanks for your time! :)

-Merry Christmas!

Something like

for (fieldname in field_values) {
  var o=document.getElementById(fieldname);
  if (o) o.value=fields_values[fieldname];
}

Ofcourse this works only for text fields, but you get the idea

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