1

I have a common <input type="text" id="foo" />

I can select all text on click by $("#foo").select();

The field does already contain a number (e.g. 25.40)

How can I select only the 25 part?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Fabio B.
  • 9,138
  • 25
  • 105
  • 177
  • 1
    This question is very vague, will the answer always be 25.40? Are you trying to round down numbers so 25.40 becomes 25? Are you wanting only the first two characters of whatever input is in the box? It could mean a lot of answers. – Chris Dixon Apr 14 '11 at 09:57
  • 1
    @thedixon: I think it is pretty clear: Instead of selecting the whole text, only the part before the dot should be selected. Granted, if we knew the reason *why*, then there might be another, simpler solution. – Felix Kling Apr 14 '11 at 09:58
  • If this is the case, the answer is below. – Chris Dixon Apr 14 '11 at 10:00
  • I think Fabio need to provide more detail as @thedixon suggested. it's a input text type, it can be anything user enter – Sufendy Apr 14 '11 at 10:19
  • possible duplicate of [Partially select text inside text field](http://stackoverflow.com/questions/2999076/partially-select-text-inside-text-field) – Felix Kling Apr 14 '11 at 10:33

2 Answers2

5

For cross-browser support, you could use my Rangy Inputs jQuery plug-in for this, which will also work on textareas: http://code.google.com/p/rangyinputs/

With it, you can select everything before the decimal point as follows:

var $foo = $("#foo");
$foo.focus();
$foo.setSelection(0, $foo.val().indexOf("."));

jsFiddle example: http://jsfiddle.net/3XkJE/2/

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • FYI: You can add resources to jsfiddle, which makes the JavaScript code area a bit cleaner: http://jsfiddle.net/fkling/3XkJE/3/ :) – Felix Kling Apr 14 '11 at 10:37
  • @Felix: Thanks. I did know about that and it does work for this. For some of my other projects, the files in SVN wouldn't work when linked to directly because they have logging calls that are removed by a build script. – Tim Down Apr 14 '11 at 10:42
1
var split = $("#foo").val().split(".");
var result = split[0];
Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
  • 1
    `$("#foo").select()` will return `$("#foo")`, not the selected text. And anyway, this would never select only part of the text. It is not about *getting* the value, it is about *selecting/marking* the text. – Felix Kling Apr 14 '11 at 10:01
  • I went on the original script he posted - I guess he should use val(). – Chris Dixon Apr 14 '11 at 10:02
  • 1
    You didn't understand the problem. Read what `.select()` is doing: http://api.jquery.com/select/ – Felix Kling Apr 14 '11 at 10:03