TheTruth TheTruth - 17 days ago 5
HTML Question

Trying to get 2 values from 2 different spans

Hey guys I am trying to get 2 values on click from 2 different span. I have several tables that have betslip and bet number odds on it, and what I just want to do is to get the name and bet odds and store it to a variable in jquery then I'll push it to a betslip. my only problem is I can't seem to get the correct values. Here's the HTML:

<td>
<a href="#" id="bet">
<span id="betslip">Lautoka FC</span>
<span id="betnum"> 5/6</span>
</a>
</td>
<td>
<a href="#" id="bet">
<span id="betslip">Draw</span>
<span id="betnum">11/5</span>
</a>
</td>


Here's my jquery code:

$(document).ready(function() {
$('#betslip, #betnum').click(function() {
var bet = $(this).text();
var num = $(this).text();
alert("name: " + bet + "num: " + num);
});


});


I'm getting the wrong values. Thanks for the help!

A.J A.J
Answer

this will refer the element that is clicked. You may need to select element again if you need both the values. You may use classes if scenario of multiple combination comes in.

Example Snippet:

$(document).ready(function() {
  $('.bet').click(function() {
    var bet = $(this).find(".betslip").text();
    var num = $(this).find(".betnum").text();
    console.log("name: " + bet + " num: " + num);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
  <a href="#" class="bet">
    <span class="betslip">Lautoka FC</span> 
    <span class="betnum"> 5/6</span>
  </a>
</td>
<td>
  <a href="#" class="bet">
    <span class="betslip">Draw</span>
    <span class="betnum">11/5</span>
  </a>
</td>