chiangy77 chiangy77 - 1 month ago 4
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.

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


JS:

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

$(this).find(".total").val(hp);
}

Answer

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();

    $(ele).find(".total").text(hp);
}

Demo


Note

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):

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

    $(this).find(".total").text(hp);
});
Comments