1

How I can implement that if I click button then it loads data where is select option and then it auto selects that option. But it cant select by value="". It should select by text.

Example my button is:

<button class="roomBtn" data-title="Studio Exclusive">Book now</button>

And if I click that button it loads data in modal and there is select option field where is multiple different options but cant select option by value. It has to be select by text what contains data-title="" value.

<select class="room-select">
   <option value>Select product</option>
   <option value="12">500€ - Studio Prime</option>
   <option value="13">750€ - Studio Exclusive</option>
</select>

So it has to select that option Studio Exclusive because it contains that title.

I've tried this but it didn't work:

jQuery(document).ready(function($) {
        let buttonText = $(".roomBtn").attr("data-title");
        $(".room-select option:contains('" + buttonText + "')")
        .filter(function(i){
            console.log($(this).text());
            return $(this).text() === buttonText;
        })
        .attr("selected", true)
    }); 
HCU-Memory
  • 15
  • 4
  • Does this help https://stackoverflow.com/questions/1888931/set-dropdown-value-by-text-using-jquery? – Greg Sep 13 '21 at 18:33

1 Answers1

1

You can match with indexOf using the value of data-title.

$(".roomBtn").on("click", function(){
  let title = $(this).attr('data-title');
  let val = $(".room-select option").filter((i, e) => {
    return e.innerHTML.indexOf(title) > -1;
  }).val();
  $(".room-select").val(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="roomBtn" data-title="Studio Exclusive">Book now</button>

<select class="room-select">
   <option value>Select product</option>
   <option value="12">500€ - Studio Prime</option>
   <option value="13">750€ - Studio Exclusive</option>
</select>
Liftoff
  • 24,717
  • 13
  • 66
  • 119
  • Can I trigger it later because my plugin adds new modal div to bottom of body after I click so at the moment that code doesnt work becuase select option doesnt exist before click. – HCU-Memory Sep 13 '21 at 18:39
  • Yes, just call the inner part of the function (inside the click's callback) whenever you wish to change the value. – Liftoff Sep 13 '21 at 18:40
  • Thank you. Your code is perfect and helped a lot. Learned again new thing. :) – HCU-Memory Sep 13 '21 at 18:56