tags:

views:

112

answers:

5

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 (nothign to do with jquery! :) )

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

+5  A: 

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.
   });
 });
Nick Craver
A: 

var store = $("input.numberfield");

store.val("$" + store.val());

jwwishart
A: 

You can pass a function to val() and use a regular expression to add a $ to the front if there isn't one there already:

$("input.numberfield").val(function(i, val) {
  return val.replace(/^\s*(?!\$)/, "$");
});

The above regex means replace a sequence of white space at the beginning of the value that isn't followed by a dollar sign with a dollar sign. This would work too:

$("input.numberfield").val(function(i, val) {
  return val.replace(/^\s*(\$)?/, "$");
});
cletus
these functions are injecting the actual code into my INPUTSs!(not sure whats going on there)Thanks for the very quick responses. What I was wanting was that, when you onlick (anywhere in the input), the cursor would jump to the right side of the dollar sign. Is that possible?
swisstony
@Jared: these aren't injecting the actual code into the inputs. Read the linked documentation for `val()`. They're injecting the **return value** from the function into the inputs. It's a shorthand form of `each(function() { $(this).val(...) }` essentially.
cletus
A: 

Thanks for the very quick responses everyone.

What I was wanting was that, when you onlick (anywhere in the input), the cursor would jump to the right side of the dollar sign. Is that possible?

swisstony
@Jared: If you have comments or questions, post them as comments on other answers, or edit your original question to reflect any new information.
Jonathan Sampson
A: 

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>
Happy