Ad

Php Html Form Select Option To Populate Text Field Jquery

- 1 answer

I'm editing a wordpress plugin:

It currently has a dropdown option list for a user, and based on that user, I want to fill a text field with that users email.

selection option dropdown:

<div>
    <label for="Customer_ID"></label>
    <select name="Customer_ID" id="Customer_ID" />
    <option value='0'>None</option>
    <?php foreach ($Customers as $Customer) { ?>
      <option value='<?php echo $Customer->Customer_ID; ?>'><?php echo $Customer->Customer_Name; ?></option>
    <?php } ?>
    </select>
</div>

The customer email is stored in $Customer->Customer_Email

And Im trying to fill in the following value when a user changes the selected user:

<div class="form-field">
  <label for="Order_Email"></label>
  <input type='text' name="Order_Email" id="Order_Email" />
</div>

I've played around with filling the Order_Email with the following script, but it just sents the value as the customer_id. How do I change the value to the email

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#Customer_ID').on('change', function () {
        var selection = $(this).val();
        $('#Order_Email').val(selection);
    });
});
</script>
Ad

Answer

You could just add a title attribute to the options to equal whatever the email value is:

Play around with it here: http://jsfiddle.net/7BUmG/3876/

This might not be the best solution and hacky, but it should do the trick. This will also break after the plugin is updated

<div>
    <label for="Customer_ID"></label>
    <select name="Customer_ID" id="Customer_ID" />
    <option value='0'>None</option>
    <?php foreach ($Customers as $Customer) { ?>
      <option title='<?php echo $Customer->Customer_Email; ?>'value='<?php echo $Customer->Customer_ID; ?>'><?php echo $Customer->Customer_Name; ?></option>
    <?php } ?>
    </select>
</div>

and

$(document).ready(function(){
    $('#Customer_ID').change(function() {
    var email = $(this).find("option:selected").attr("title");
    $('#Order_Email').val(email);
});
});
Ad
source: stackoverflow.com
Ad