Converting String Into Integer In Javascript
Posted By : Vinay Tiwari | 25-Sep-2017
In this blog, we are going to learn about parseInt() function in Javascript. When we click on "plus" sign, the value will be incremented & click on "minus" sign the value will be decremented. The parseInt() function parses a string value and returns an integer value. In this function, the old value variable is in a string format with help of parseInt() function the string value will be converted to integer format.
Now, we will define the code structure
(HTML)
$(".counter").click(function() { var $counter = $(this); var oldValue = $(".form-control").find("span").text(); //Increment value up one if ($counter.text() == "+") { var newVal = parseInt(oldValue) + 1; } else { // Don't allow decrement value below zero if (oldValue > 0) { var newVal = parseInt(oldValue) - 1; } } //Drop the new-value into the span tag if(newVal <= 9){ $(".form-control").find("span").text('0'+newVal); }else { $(".form-control").find("span").text(newVal); } });
In this function, first, we can do save the "old" value of span tag inside the variable (var old value). If "plus" button is clicked the value will be incremented up one & clicked on "minus" button the value will be decremented down one & finally drop the new value inside the span tag.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vinay Tiwari
Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.