Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - How Do I Insert a Character into an input

Tags:

jquery

Can someone help me out with this please...

I am doing a web form. I would like to insert the dollar sign into some INPUTs that have a numberfield class. I want the user's content to follow the dollar sign or course.

This inserts the dollar sign OK, but the content ends up in front of it.

$('input.numberfield').val('$');

NOTE - the dollar sign is required because this is financial data (nothing to do with jquery! :) )

in other words - someone types in '100' and it becomes '$100')

like image 594
swisstony Avatar asked Feb 22 '10 02:02

swisstony


People also ask

How to add special characters in jQuery?

The plugin “Special Input” creates a responsive keyboard based on jQuery and CSS to insert special characters in textbox (input / textarea). It appends a virtual keyboard with text input, where users can select characters to insert.

How to add first child in jQuery?

The . prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use . append() ).

What is input in jQuery?

version added: 1.0jQuery( ":input" ) The :input selector basically selects all form controls.


2 Answers

You can do something like this:

$('input.numberfield').each(function() {
  $(this).val('$' + $(this).val());
}

In 1.4, a simple more complete solution for your scenario:

 $('input.numberfield').keyup(function() {
   $(this).val(function(i,v) {
     return '$' + v.replace('$',''); //remove exisiting, add back.
   });
 });
like image 85
Nick Craver Avatar answered Oct 17 '22 14:10

Nick Craver


Why make your life complex? Just put the dollar sign into the HTML outside of the input element...

<span style="border: inset 1px black; padding: 1px;">
  $<input style="border: none; padding: 0;">
</span>
like image 31
Happy Avatar answered Oct 17 '22 14:10

Happy