0

I have a dropdown on my website where users get to select the payment method. I want an image to appear to the right of the option selected by the user.

I have tried using the below code. This code was taken from this thread: jQuery onchange/onfocus select box to display an image?

JS fiddle link: https://jsfiddle.net/lindychen/102fmpu8/1/

HTML code

  <select name="form_fields[field_5]" id="form-field-field_5" class="elementor-field-textual elementor-size-sm" required="required" aria-required="true">
    <option value=""></option>
    <option value="https://i.imgur.com/4vRsaJa.png">Paypal</option>
    <option value="https://i.imgur.com/ZPC09qT.png">Credit Card</option>
  </select>
</div>

Jquery code

    $("form-field-field_5").change(function() {
        var src = $(this).val();

        $("#form-field-field_5").html(src ? "<img src='" + src + "'>" : "");
    });
});

This is the expected result:

However, currently, I do not see the pictures appearing to the right of the text. Unfortunately, I am not able to change the HTML code used. Thank you.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    While it doesn't immediately solve the issue, the selector you have at the beginning of your jQuery code is wrong. Since you're referencing by ID, remember the `#` at the beginning of your selector. – Jon Warren Nov 03 '19 at 16:59

1 Answers1

0

Like this? You cannot add the image to the dropdown without creating a custom widget

$("#form-field-field_5")
 .after('<span id="img"></span>')
 .change(function() {
  var src = $(this).val();
  $(this).next().html(src ? `<img src="${src}" >` : "");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="form_fields[field_5]" id="form-field-field_5" class="elementor-field-textual elementor-size-sm" required="required" aria-required="true">
  <option value=""></option>
  <option value="https://i.imgur.com/4vRsaJa.png">Paypal</option>
  <option value="https://i.imgur.com/ZPC09qT.png">Credit Card</option>
</select>
mplungjan
  • 169,008
  • 28
  • 173
  • 236