How can I add a % symbol to user input in a text input field?

When utilizing a number spinner, I'm looking to include the % symbol in the input box by default. I attempted using a span, however, it places the symbol outside the box.

Answer №1

If you want to add a percentage sign to a textbox using CSS, you can use a simple trick. Just include the following code snippet in your project:

.spinner input {
  padding-right: 13px;
}

.spinner .input-group-btn-vertical::before {
  content: "%";
  position: absolute;
  right: 18px;
  top: 7px;
}

This code snippet utilizes the ::before pseudo-element selector to insert the % sign into the textbox. For a live demonstration, refer to the code below:

(function ($) {
  $('.spinner .btn:first-of-type').on('click', function() {
    $('.spinner input').val( parseInt($('.spinner input').val(), 10) + 1);
  });
  $('.spinner .btn:last-of-type').on('click', function() {
    $('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
  });
})(jQuery);
.spinner {
  width: 100px;
}
.spinner input {
  text-align: right;
}
.input-group-btn-vertical {
  position: relative;
  // additional CSS styles
}
// More CSS styles for the spinner and input elements
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="page-header"><h1>Bootstrap 3 input-spinner</h1></div>  
  <div class="input-group spinner">
    <input type="text" class="form-control" value="42">
    <div class="input-group-btn-vertical">
      <button class="btn btn-default" type="button"><i class="fa fa-caret-up"></i></button>
      <button class="btn btn-default" type="button"><i class="fa fa-caret-down"></i></button>
    </div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

(You can also view it in a jsfiddle)

Answer №2

Take a look at this:

(function ($) {
     var minNumber = -100;
     var maxNumber = 100;
     $('.spinner .btn:first-of-type').on('click', function() {
         if($('.spinner input').val() == maxNumber){
             return false;
         }else{
             $('.spinner input').val( parseInt($('.spinner input').val(), 10) + 5 +'%');
         }
     });

     $('.spinner .btn:last-of-type').on('click', function() {
         if($('.spinner input').val() == minNumber){
             return false;
         }else{
             $('.spinner input').val( parseInt($('.spinner input').val(), 10) -5+'%');
         }
     });
  
  $(".spinner input").on("input", function(){
    var intValue = parseInt($(this).val().replace(/%/g, '') ) || 0;
    
    $(this).val( intValue + '%' );
  });
    })(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id=spinner class="container">
  <div class="input-group spinner">
    <input type="text" class="form-control" value="0">
    <div class="input-group-btn-vertical">
      <button class="btn btn-default" type="button"><i class="fa fa-caret-up" style="color: #C41C01">Up</i></button>
      <button class="btn btn-default" type="button"><i class="fa fa-caret-down" style="color: #20AD4E">Down</i></button>
    </div>
  </div>
</div>

Answer №3

If you want to add the '%' symbol to the end of your input using a jQuery change event, here is a simple way to do it.

(function($) {
  var minNumber = -100;
  var maxNumber = 100;
  $('.spinner .btn:first-of-type').on('click', function() {
    if ($('.spinner input').val() == maxNumber) {
      return false;
    } else {
      $('.spinner input').val(parseInt($('.spinner input').val(), 10) + 5 + '%');
    }
  });

  $('.txtinput').on("change", function() {
    var inputVal = parseFloat($(this).val().replace('%', '')) || 0

    if (minNumber > inputVal) {
      inputVal = -100;
    } else if (maxNumber < inputVal) {
      inputVal = 100;
    }

    $(this).val(inputVal + '%');
  });

  $('.spinner .btn:last-of-type').on('click', function() {
    if ($('.spinner input').val() == minNumber) {
      return false;
    } else {
      $('.spinner input').val(parseInt($('.spinner input').val(), 10) - 5 + '%');
    }
  });
})(jQuery);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=spinner class="container">
  <div class="input-group spinner">
    <input type="text" class="form-control txtinput" value="0">
    <div class="input-group-btn-vertical">
      <button class="btn btn-default" type="button"><i class="fa fa-caret-up" style="color: #C41C01"></i>
      </button>
      <button class="btn btn-default" type="button"><i class="fa fa-caret-down" style="color: #20AD4E"></i>
      </button>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving precise passed arguments in the $(document).ready function

I am working on a gridview where I need the rows to expand and display the BatchID that is passed. Currently, I am using href="javascript:switchViews('div<%# Eval("BatchID")%>', 'one');" to pass this information, but I'm stru ...

Revamp Password Security with PHP, Ajax, and JQuery

Working on creating a form to update a user's password. No errors in console but the data isn't updating. The validation part is functioning, so the issue might lie with the Ajax implementation? Note: I am aware of not using mysql in PHP long-te ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...

Achieving responsive masonry layout with Bootstrap 4

I'm attempting to implement the bootstrap 4 masonry effect on my website, but I'm facing issues with card responsiveness. The page is very basic without any special effects. While the page works well when resizing the browser window, it doesn&ap ...

How can I paginate my Facebook friend list using a foreach loop?

Upon fetching the facebook friendlist, I noticed that it retrieves a vast number of photos (a slight exaggeration). I am contemplating how to implement pagination within a foreach loop. Additionally, I am curious if there is a more efficient way to retriev ...

Validating HTML using EJS templates set as "text/template" elements

What is the general consensus on HTML validation when utilizing a framework such as Backbone or Meteor and generating views in the client from EJS templates? An issue arises with the fact that name is not considered an official attribute for a <script& ...

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

Mastering the intricacies of Angular bindings through intuition

I am attempting to grasp the concept of distinguishing between square brackets binding <elem [...]="..."><elem> and parentheses binding <elem (...)="..."<elem>. Is there a rule of thumb that can help differentiate between the two? Pe ...

Having trouble parsing emails in Python using the "imaplib" library, dealing with HTML line character limits, and handling extra non-Unicode characters

In my Python 3 project, I am working on validating emails that are sent to my inbox. I am using imaplib library to achieve this task. While I have successfully retrieved the email content, the mail appears to be unreadable and somewhat corrupted (reference ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

I'm experiencing an issue where my express-session is being reset with every new request, leading me to question if this is related to the development environment I am using (REACT + EXPRESS)

UPDATE - I have ruled out a development environment issue as the same problem persists in production. Thank you for taking the time to look into this. I've searched through numerous questions and attempted various solutions with no success. To give ...

MVC - The challenge of users repeatedly clicking the Submit button

In my MVC application, there are multiple pages where users submit a form by clicking a Submit button. Occasionally, users may click the button multiple times if they don't see an immediate response, causing the form to be submitted twice. To address ...

Customize material-ui themes using useStyles / jss

Is it possible to customize the Material-UI theme using styles without relying on !important? const customTheme = createMuiTheme({ overrides: { MuiInputBase: { input: { background: '#dd7711', padding: 10, }, ...

Could you please provide instructions on how to manipulate the :root CSS variable using JQuery?

Is there a way to update the :root css variable using jquery? :root { --color: #E72D2D; } .box-icon { background-color: var(--color); } I tried but it doesn't seem to work $("#blueColor").click(function(e) { $(":root").css("-- ...

Trying to conceal the scrollbar on MS Edge and Firefox?

Currently, I am working on a scrollable menu that requires the scrollbar to be hidden. In Chrome, I have achieved this by using the following code: .menu::-webkit-scrollbar { display: none; } I would like to know if there is an equivalent solution ...

Having difficulty reaching a div element using either its id or class in a CSS stylesheet

I'm having trouble adding padding to the home section div and I can't seem to access it using either the id or class. Any suggestions on how to solve this issue would be greatly appreciated. Below is the CSS code: body { margin: 0 ; font ...

How can I eliminate text using regular expressions?

Greetings, I am seeking assistance with content removal using regular expressions. Below is the regular expression code I have written: reg = reg.replace(/\|.*?(\|)/g, ''); Input: One-1|two-2|Three-3|Four-4|Five-5 Six-6|Seven-7|Eig ...

Utilizing React Router DOM 6.3.0 to read the pathname from an undefined source

I am currently using react-router-dom version 6.3.0 and have set up the following routes inside my App component <BrowserRouter> <Routes> <Route path='/article/*' element={<Article />} /> </Routes> </Brows ...

Utilizing jQuery to create a recursive AJAX poll with setTimeout to regulate the polling frequency

$(document).ready(function() { (function pollUsers() { setTimeout(function() { $.ajax({ url: "/project1/api/getAllUsers", type: "GET", success: function(userData) { ...

AngularJS - ng-repeat: Warning: Repeated items found in the repeater and are not allowed. Repeater:

I'm currently using ng-repeat to showcase a collection of items fetched from the Twitter API. However, I am encountering an issue where Angular attempts to display the empty list while the request is still being processed, resulting in the following e ...