Dan D Dan D - 4 days ago 4
HTML Question

Hiding an object in a dropdown in Javascript

I recently posted a question that was answered (thank you guys for all of your help!!), and just had a follow up if anyone can help me.

I wanted to see if it was possible to hide certain elements in a dropdown in Javascript. Here is the code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<p>The price is: <span id="price_selected"></span></p>
<script language="JavaScript">
$("option[value='124']").html('1 Box [$12.95]')
$("option[value='125']").html('2 per Case [$22.95]')
$("option[value='126']").html('6 per Case [$62.95]')


$('select').on('change',function(){
str = $("option:selected").html()
var n = str.indexOf("$");
var nx = str.indexOf("]");
var price = str.substring(n+1,nx);

$('#price_selected').html("$"+price);
});
</script>


In this code, can I hide the prices so that they do not show up in the dropdown? For example, the dropdown will show "1 Box", but will output "The price is: "12.95". Also, is it possible to show "The price is: 12.95" (the first option) as soon as the page loads? As of now, it only says "The price is:" until the dropdown is clicked.

I just signed up to this forum, so apologies if anything seems vague. Thank you!!

EDIT:

It would have probably been more helpful if I included this with my post. This is the HTML for the dropdown box, but it was automatically generated, and I cannot modify it:

<SELECT name="SELECT___TK46BW___9" onChange="change_option('SELECT___TK46BW___9',this.options[this.selectedIndex].value)">
<OPTION value="124" SELECTED>1 Box</OPTION>
<OPTION value="125" >2 per Case [Add $10.95]</OPTION>
<OPTION value="126" >6 per Case [Add $50.00]</OPTION>
</SELECT>

Answer

Here's one way to do it. Add the price to each option by using a data attribute (data-price), and then retrieve that data.

I also added the selected price on load like you asked.

$("option[value='124']").html('1 Box').data('price', '12.95');
$("option[value='125']").html('2 per Case').data('price', '22.95');
$("option[value='126']").html('6 per Case').data('price', '62.95');

$('select').on('change', function() {
  str = $("option:selected").data('price')
  $('#price_selected').html("$" + str);
});

// run on load
$('#price_selected').html("$" + $('select option:selected').data('price'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  Choose an amount:
  <select>
    <option value="124"></option>
    <option value="125"></option>
    <option value="126"></option>
  </select>
</p>

<p>
  The price is: <span id="price_selected"></span>
</p>

Comments