Ashraf Lobo
Ashraf Lobo

Reputation: 157

JQuery .val is not working

I've got a problem with my jquery. Before you mark this as a repeated question, I've looked through a bunch of similar solutions and found no answer. What I need to do is simple. I have an input of type number in between two buttons, plus(+) and minus(-). Basically, if you click the plus the value of the input is added by 1 and subtracted by 1 if you click the minus.

Here's my Code:

$(function() {
  $("#plus").click(function() {
    var pages_val = $('#pages').val();

    if (pages_val < 0) {
      pages_val = 0;
    } else {
      pages_val += 1;
    }

    $('#pages').val(pages_val);
  });

  $("#minus").click(function() {
    var pages_val = $('#pages').val();

    if (pages_val <= 0) {
      pages_val = 0;
    } else {
      pages_val -= 1;
    }

    $('#pages').val(pages_val);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button id="minus">-</button>
  <input id="pages" name="pages" type="number" value="0">
  <button id="plus">+</button>
</div>

The html is all enclosed in form tags btw. So my problem is when I click any of the buttons the value flickers(blinks) for a second then reverts to an empty input. I checked the code inspector and the value doesn't change. I need the value to remain when the user clicks any of the buttons. Please help. The console shows no logs.

Edit: Who gave my post a -1 without a solution. It's only been up for 6 sec

Upvotes: 4

Views: 3335

Answers (6)

PEPEGA
PEPEGA

Reputation: 2283

Your +/- was wrong use "++" and "--"

$(function(){
    $("#plus").click(function(){
        var pages_val = $('#pages').val();

        if (pages_val < 0){
            pages_val = 0;
        }
        else {
            pages_val++;
        }

        $('#pages').val(pages_val);
    });

    $("#minus").click(function(){
        var pages_val = $('#pages').val();

        if (pages_val <= 0){
            pages_val = 0;
        }
        else {
            pages_val--;
        }

        $('#pages').val(pages_val);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <button id="minus">-</button>
    <input  id="pages" name="pages" type="number" value="0">
    <button id="plus">+</button>
</div>

Upvotes: 4

zer00ne
zer00ne

Reputation: 43895

Primary Problem

"...any of the buttons the value flickers(blinks) for a second then reverts to an empty input."

The code provided from OP has form controls wrapped in a <div> rather than a <form> tag. The following demo presents a more accurate layout since it was mentioned:

"The html is all enclosed in form tags btw"

Problem

A <button> tag behaves as a submit button when it is nested within a <form> tag. So what happens is whenever a button is clicked, it is interpreted as a "submit" event and the <form> tag data is sent to a server if configured to do so, and if not configured, it will be attempted regardless. Each submit, failed or successful incurs the <form> to be reset.

Solution

In order to prevent this reset, add this to each <button> tag:

type="button" 

Possible Problem

Because of the OP code being somewhat error prone and a bit inaccurate, there may be some misinterpretations. Upon initial inspection of OP code, the plus + button was concating values rather than incrementing a number.

Plus Button Clicked 3 times

Result: 0111

Expected: 3

Note: If the minus - button is clicked after clicking the + button without refreshing the code, it will function properly as expected, which is decrementing the value as a real number. But if clicked when the <input> has a value of 0, it does nothing.

Explination

Any value derived from a form control (e.g. <input>, <select>, etc.) is a string not a real number. So when 3 clicks of a plus button gives you this:

0111 

That's a string value concat from 4 strings:

"0" + "1" + "1" + "1" 

Solution

The string value must be converted to a real number value. There are many solutions already presented by other answers posted for this question, so I will just suggest what already implemented in the Demo below:

Instead of using: value +=1 and value -=1

Use this in/decrementing operators: value++ and value--

Under many circumstances, +=1 can be misinterpreted as:

 (this is a string) `value` (so concat) `+` (this string to it) `"=1"`🟊

Whereas this operator: value++ has no ambiguities because it auto typed to a real number:

 (this is a string) `value` (***But*** convert it to a number) `++` (and add it to the default value of number 1)  

🟊 The string value: "=1" would normally concat to =1 literally but since the OP code is using <input type='number'>, only numbers (in the form of a string) remain while non-number types are removed. Hence: 0111 instead of 0=1=1=1 value for the <input type='number' value='0'>

Details on JavaScript Data Types and specifically ++ and --

Demo

$(function() {
  $("#plus").click(function() {
    var pages_val = $('#pages').val();

    if (pages_val < 0) {
      pages_val = 0;
    } else {
      pages_val++;
    }

    $('#pages').val(pages_val);
  });

  $("#minus").click(function() {
    var pages_val = $('#pages').val();

    if (pages_val <= 0) {
      pages_val = 0;
    } else {
      pages_val--;
    }

    $('#pages').val(pages_val);
  });
});
<form>
  <button id="minus" type='button'>-</button>
  <input id="pages" name="pages" type="number" value="0">
  <button id="plus" type='button'>+</button>
</form>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 4

Hastig Zusammenstellen
Hastig Zusammenstellen

Reputation: 4440

It's been answered but here's what I was playing with (it combines your .click functions) https://jsfiddle.net/Hastig/7L01eu2y/

$('.changerer').click(function() {
  var pages_val = $('#pages').val();
  if ($(this).hasClass('minus')) {
    if (pages_val <= 0) {
      pages_val = 0;
    } else {
      pages_val--;
    }
  } else {
    pages_val++;
  }
  $('#pages').val(pages_val);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button class="changerer minus" type="button">-</button>
  <input id="pages" name="pages" type="number" value="0" min="0">
  <button class="changerer plus" type="button">+</button>
</div>

Upvotes: 1

Aref Ben Lazrek
Aref Ben Lazrek

Reputation: 1064

as mentioned in other answer you must use parseInt() because val() give you a string and about the buttons not working thats because the default type of buttons is submit so you need to add button type

<button type="button" id="minus">-</button>

Upvotes: 1

Willem van der Veen
Willem van der Veen

Reputation: 36620

You are adding a string, the string will concatenate instead of performing addition.

$(function() {
  $("#plus").click(function() {
    var pages_val = Number($('#pages').val());

    if (pages_val < 0) {
      pages_val = 0;
    } else {
      pages_val += 1;
    }

    $('#pages').val(pages_val);
  });

  $("#minus").click(function() {
    var pages_val = $('#pages').val();

    if (pages_val <= 0) {
      pages_val = 0;
    } else {
      pages_val -= 1;
    }

    $('#pages').val(pages_val);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <button id="minus">-</button>
  <input id="pages" name="pages" type="number" value="0">
  <button id="plus">+</button>
</div>

The + operator has multiple function when used with strings it will concatenate them (add them together). When you use it with numbers it will add them. In your application the $('#pages').val() was a string. Therefore the + operator performed string concatenation on it which results in values like 11, 111, 1111 etc.

Upvotes: 1

mituw16
mituw16

Reputation: 5250

.val() will return the value as a string. You're doing math operations, so you need to turn your value into a number. Try parseFloat()

var pages_val = parseFloat($('#pages').val());

Upvotes: 4

Related Questions