ReshaD
ReshaD

Reputation: 946

Use $(this) instead of an ID in javaScript

Is there any solution to use $(this) instead of and ID in option select in javaScript?

 var tot = 5 * ($( "#firstOne option:selected" ).text());

In the example above, I want to use $(this) instead of #firstOne, in order to be able using this function for multiple option select.

UPDATE

jsFiddle

$(document).ready(function() {

  document.getElementById("totalPrice").innerHTML = 0 + " €";
});

function addToPrice() {
  var tot = $("#totalPrice").val();
  tot = 5 * ($(this).find("option:selected").text());
  tot = tot + " €"
  document.getElementById("totalPrice").innerHTML = tot;

}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

<div>

  <table class="itemList">
    <tr>
      <td style="width: 170px">
        <span>Arancina Pistacchio</span>
      </td>
      <td>
        <span style="margin-left: 110px;">2.5 &euro;</span>
      </td>
      <td>
        <select style="margin-left: 30px" onChange="addToPrice();">
          <option value="one">0</option>
          <option value="two">1</option>
          <option value="three">2</option>
          <option value="four">3</option>
        </select>
      </td>
    </tr>
  </table>

</div>

<div>

  <table class="itemList">
    <tr>
      <td style="width: 170px">
        <span>Arancina Melanzana</span>
      </td>
      <td>
        <span style="margin-left: 110px;">2.5 &euro;</span>
      </td>
      <td>
        <select style="margin-left: 30px">
          <option value="one">0</option>
          <option value="two">1</option>
          <option value="three">2</option>
          <option value="four">3</option>
        </select>
      </td>
    </tr>
  </table>

</div>

<div class="totPrice">Total :</div>
<div class="totPrice" style="font-size: 20px; font-family: Helvetica" id="totalPrice"></div>

Upvotes: 1

Views: 36

Answers (3)

guradio
guradio

Reputation: 15555

you can use

$( "option:selected",this ).text()

DEMO

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Is there any solution to use $(this) instead of and ID in option select in javaScript?

Yes, try

var tot = 5 * ( $(this).find("option:selected" ).text());

You needed to do multiple things in your fiddle

  1. Select No Wrap - In Head option

  2. Select jQuery version

  3. Pass the current object this as the argument to the function.

Upvotes: 1

sacgro
sacgro

Reputation: 469

I got if what you mean. Use like following:

var tot = 5 ;
$( "option:selected" ).each(function(){
tot = tot * $(this).text();
});

Upvotes: 3

Related Questions