user10559318
user10559318

Reputation:

How to click select id value?

Here is the HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price">
 $20
</span>
<p id="in-carHEREt" style="display: none;">in cartHERE</p>
 <span class="needsclick select-widget  enabled" id="size-options-link">Medium</span>
 <select id="size-options" name="size-options" class="select-widget ">
<option value="46158">Medium</option>    
<option value="46159">Large</option>    
 <option value="46160">XLarge</option>    
</select>

 <span id="cart-update"><span class="cart-button">add to cart</span></span>

I tried the following but it won't change the option, stuck at 'Medium'.

document.getElementById("size-options").value = "Large"
document.getElementById("size-options").dispatchEvent(new Event('change'))

document.getElementById("size-options-link").dispatchEvent(new Event('click'))
document.getElementById("size-options-link").value = "Large"

I don't know how to select Large.

Any help is appreciated, I need the answer to be like the above as I am using it in a function in swift called evaluatejavascript.

Thanks

Upvotes: 0

Views: 194

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65873

See comments inline:

// Get all the options into an array
let options = Array.prototype.slice.call(document.querySelectorAll("#size-options > option"));

// Use Array.filter() to locate just the one with the text of "Large"
let large = options.filter(function(item){
  return item.textContent === "Large";
});

// Get the value of that item and set that as the <select> value
document.getElementById("size-options").value = large[0].value;

document.getElementById("size-options").dispatchEvent(new Event('change')) // Fire the change event
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price">$20</span>
<p id="in-carHEREt" style="display: none;">in cartHERE</p>
<span class="needsclick select-widget  enabled" id="size-options-link">Medium</span>
<select id="size-options" name="size-options" class="select-widget ">
  <option value="46158">Medium</option>    
  <option value="46159">Large</option>    
  <option value="46160">XLarge</option>    
</select>

<span id="cart-update"><span class="cart-button">add to cart</span></span>

Upvotes: 1

Vishnu S Krish
Vishnu S Krish

Reputation: 466

You are mistakenly set the Display Text of the <option> instead of its value. You have to set 46159 as value.

document.getElementById("size-options").value = "46159"
document.getElementById("size-options").dispatchEvent(new Event('change'))

Upvotes: 0

Related Questions