SolaceBeforeDawn
SolaceBeforeDawn

Reputation: 1053

Jquery Get Dropdown Label and make the default select option item placeholder

I've inherited some php that deals with a dropdown select and need to make one small change: to move the label so that it becomes the default dropdown placeholder (instead of the first option). I could modify the php file, but it may receive an automated update at some point, and then I'd have to modify it again. Instead, I'd like to use jquery to move the label. I've searched the forums and have not quite been able to find what I'm looking for and get it to work.

The code I have inherited looks similar to this;

<form id="currency_converter">
 <label for="currency_switcher" class="currency_switcher_label">Choose a Currency</label>
  <select id="currency_switcher" class="currency_switcher select">
      <? foreach ( $currencies as $currency ) {
       $html .= '<option value="' . esc_attr( $currency ) . '">'</option>';
      } ?>
  </select>
</form>

Which looks something like this :

enter image description here

However, I would like it to show the "Choose a Currency" as the first value / placeholder in the dropdown.

This is what I have but not working:

$("#currency_converter select").each(function() {
    var text = $(this).prev("label").text();
    $(this).children("option[selected='selected']").val(text).text(text);
});

Here is the jsfiddle I'm working on: It works, but it replaces the first dropdown entry and I want to prepend not replace....

http://jsfiddle.net/clappertrapp/79uxp4rt/

Upvotes: 0

Views: 150

Answers (1)

palaѕн
palaѕн

Reputation: 73916

It works, but it replaces the first dropdown entry and I want to prepend not replace....

You can simply do this using prepend method instead and also need to use .prop("selected", true) so that it is selected by default on page load also:

$(function() {
  $("#currency_converter select").each(function() {
    var text = $(this).prev("label").text();
    var $option = $("<option />").attr("value", text).text(text).prop("selected", true)
    $(this).prepend( $option )
  }).prev().hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="currency_converter">
  <label for="currency_switcher" class="currency_switcher_label">Choose a Currency</label>
  <select id="currency_switcher" class="currency_switcher select">
    <option value="USD">USD</option>
    <option value="AUD">AUD</option>
    <option value="GBP">GBP</option>
    <option value="EUR">EUR</option>
  </select>
</form>

Upvotes: 1

Related Questions