简体   繁体   中英

Dynamically populate form field, based on two other fields

Say we have a form field and want to populate it with a images based on two other fields. Say these are called COLOUR and STYLE. So if style is 'A' and colour is black, we want to display the unique image representing these choices. If style is 'B' and colour black, another image.

So what is missing from the following?:

add_filter("pre_render", "populate_dropdown");

function populate_dropdown($form){

    if($form["id"] != 1)
        return $form;

    foreach($form["fields"] as &$field)
        if($field["id"] == 1){
            $field["content"] = "DYNAMIC STUFF HERE";
        }

    return $form;
}

why dont you either on page load or using an event handler just get the value of the form inputs and then do what you want based on what they are eg

$(document).ready(function() {
   style = $('#style').val();
   color = $('#color').val();

   if(style=='A' && color=='black') {
      // do something
   }

   if(style=='B' && color=='black') {
      // do something
   }
});

To build on geoffs3310's answer above, you could easily combine that with ajax to do some more complex logic, or even build your custom content from a database.

style = $('#style').val();
color = $('#color').val();

$.ajax({
     type: "POST",
     url: "get_image.php"
     data: { "style" : style, "color" : color },
     success: function(msg) {
          $("#image_field").html('<img src="' + msg + '" />');
     }
});

And in get_image.php:

$color = $_POST['color'];
$style = $_POST['style'];
var $image;

// Logic goes here, setting $image to the appropriate image link

echo $image;

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