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)


 
+ 00 +
 
(Javascript)
$(".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);
	}
});

 

 

Declaration
 

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

 

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..