Ravshan Abdurasulov Ravshan Abdurasulov - 4 months ago 8
jQuery Question

jQuery Simple Calculation not working and not showing any error

I want to create calculator filtering it through

data-filter
. I am beginner in programming also in jquery so not be strict. I wrote script however its not working and not showing any error.

<form>
<select id="kraska">
<option value="0.99" data-filter="1">test1</option>
<option value="4" data-filter="2">test2</option>
</select>
<input id="metr" type="text" />
<button id="calculate" type="submit">Calculate</button>
<p id="result"></p>
</form>
<p id="result"></p>


$('#calculate').click(function(){
if ($('#kraska').data('data-filter') == 1) {
var result = $('#kraska').val() * $('#metr').val();
};

if ($('#kraska').data('data-filter') == 2) {
var result = $('#kraska').val() / $('#metr').val();
};

$('#result').html(result)
})



Answer

You need to make a few corrections in your code:

  1. When you are using data method for getting any data-attribute's value, you need to use the attribute name without the data- part.
  2. You are trying to get the data-attribute's value for the select element, while you have specified them on your option elements. So, you need to select the :selected option instead.
  3. I have also removed button's type submit, though you can handle it with e.preventDefault() in your click handler even if you want to keep it as a type="submit" button.

$('#calculate').on("click", function(e){
    if ($('#kraska option:selected').data('filter') == 1) {
        var result = $('#kraska').val() * $('#metr').val(); 
    };

    if ($('#kraska option:selected').data('filter') == 2) {
        var result = $('#kraska').val() / $('#metr').val();
    };

    $('#result').html(result)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
    <select id="kraska">
      <option value="0.99" data-filter="1">test1</option>
      <option value="4" data-filter="2">test2</option>
    </select>
    <input id="metr" type="text" />
    <button id="calculate">Calculate</button>
    <p id="result"></p>
</form>
<p id="result"></p>

Comments