chiangy77 chiangy77 - 1 year ago 45
Javascript Question

Unable to extract value using jQuery

I have a function to calculate when there is a change in one of the 3 input boxes and then display that answer. I'm able to trigger the function when there's a change but I'm unable to get the values from each of the inputs. Below are html and js snippets.

<th class="gen-specific g3 g4 g5 g6">IVs</th>
<th class="gen-specific g3 g4 g5 g6">EVs</th>
<tr class="hp" onchange="hp_calculator()">
<input class="base" value="100" />
<td class="gen-specific g3 g4 g5 g6">
<input class="ivs calc-trigger" value="31" />
<td class="gen-specific g3 g4 g5 g6">
<input class="evs calc-trigger" type="number" min="0" max="252" step="4" value="0" />
<td><span class="total">341</span>


function hp_calculator() {
var hp = $(this).find(".base").val()*$(this).find(".iv calc-trigger").val()+$(this).find(".ev calc-trigger").val();


Answer Source

Firstly this is going to be the window and not the element. Pass the element inside your handler instead and use the parameter.

<tr class="hp" onchange="hp_calculator(this)">

Then you need to change your class selectors.class1.class2 for a many class selector, and then .text() to change the text of the span element. A final note is you left off the "s" in both ivs and evs:

function hp_calculator(ele) {  
    var hp = $(ele).find(".base").val()*$(ele).find(".ivs.calc-trigger").val()+$(ele).find(".evs.calc-trigger").val();




It's generally bad practice to give event handlers inline. Rather I would recommend you to attach them directly in JavaScript, this way this will work as you would expect. Here is an example how you would do so in jQuery (demo):

    var hp = $(this).find(".base").val()*$(this).find(".ivs.calc-trigger").val()+$(this).find(".evs.calc-trigger").val();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download