最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding constant text to inputted text - Stack Overflow

programmeradmin5浏览0评论

I have two input fields, where people can write numbers. And what I need is when a person finished writing in this input field some constant words or symbols are left there near his number.

I think that you didn't get anything from what I wrote above so I will try to explain with this example:

In the upper there are two inputs you see what person printed himself. And two inputs in the bottom are what he gets when he puts his cursor out of the input where he was printing. (I don't need all four inputs, just two...upper two just show the first step and bottom two show the final step)

I think it can be done by javascript... but I couldn't do it by myself and I couldn't find anything in web...

I have two input fields, where people can write numbers. And what I need is when a person finished writing in this input field some constant words or symbols are left there near his number.

I think that you didn't get anything from what I wrote above so I will try to explain with this example:

In the upper there are two inputs you see what person printed himself. And two inputs in the bottom are what he gets when he puts his cursor out of the input where he was printing. (I don't need all four inputs, just two...upper two just show the first step and bottom two show the final step)

I think it can be done by javascript... but I couldn't do it by myself and I couldn't find anything in web...

Share Improve this question edited Sep 20, 2013 at 9:33 Pigalev Pavel asked Oct 18, 2012 at 21:54 Pigalev PavelPigalev Pavel 1,1951 gold badge17 silver badges30 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

You'll need to get a reference to the textbox (try onblur event) and then append your static text to the value property.

I've used the following before, the reason I chose using an image over anything else was because text added to an input dynamically can cause confusion, as well as getting in the way when users wish to edit. Using an image meant it could be constantly there and wouldn't get in the way of the user typing:

It's only written in jQuery because it was lying around, this could easily be rewritten in pure js - and it could easily be optimised.

http://jsfiddle/pafMg/

css:

input { 
  border: 1px solid black;
  background: #fff;
  padding: 2px;
}

markup:

<input class="right-aligned" type="text" />
<input class="left-aligned" type="text" />

code:

In the following code the padding-left and padding-right has to take into account the width of the image you use.

$(function(){
  /* For left aligned additions */
  $('input.left-aligned')
      .css({
          'padding-left': '20px',
          'background-image': 'url(/favicon.png)',
          'background-position' : '2px center',
          'background-repeat': 'no-repeat'
      });
});

The left aligned version is really simple, the right aligned gets a little bit more plex however:

$(function(){
  /* For right aligned additions */
  $('input.right-aligned')
      .bind('keypress keyup', function(e){
          var input = $(this), measure, text = input.val(), x, w, y;
          /// You can calculate text width, but it's not easily cross-browser
          /// easier method, inject the text to a span and measure that instead
          if ( !input.data('measure') ){
              /// only build our measuring span the first time
              measure = $('<span />')
                  .hide() // hide it
                  .appendTo('body')
                  /// try and match our span to our input font
                  /// this could be improved
                  .css({
                      'font-weight':input.css('font-weight'),
                      'font-family':input.css('font-family'),
                      'font-size':input.css('font-size')
                  });
              /// store the measure element for later
              input.data('measure', measure );
          }
          /// handle if the user types white space
          text = text
              .replace(/\s/g,'&nbsp;')
              .replace(/</g,'&gt;');
          measure = input.data('measure');
          measure.html(text);
          w = measure.width();
          y = input.width();
          /// calculate the image position (minus padding)
          x = w + parseInt(input.css('padding-left')) + 2;
          /// take into account the scroll ability of an input
          x -= ( w > y ? w - y : 0 );
          /// reposition our image background on the input
          input
              .css({
                  'padding-right': '20px',
                  'background-image': 'url(/favicon.png)',
                  'background-position' : x + 'px center',
                  'background-repeat': 'no-repeat'
              });
      }).trigger('keyup');
});

Take a look at the blur event using jQuery: http://docs.jquery./Events/blur#fn

Here's a quick sample: http://jsfiddle/jDGg9/

<form>
    Field 1: <input id="ip1" type="text" value="" />
    Field 2: <input id="ip2" type="text" value="" />
</form>
$('#ip1').blur(function() {
    $('#ip1').val($('#ip1').val() + ' month');
});

$('#ip2').blur(function() {
    $('#ip2').val($('#ip2').val() + ' month');
});

Since you didn't specify using jQuery, here's a simple example with basic Javascript using the blur event (as everyone has already specified) although it might make sense to use the onchange event:

http://jsfiddle/A9yVv/1/

<input type="text" id="text1" value="" />
<br />
<input type="text" id="text2" value="" readonly="readonly" />

var text1 = document.getElementById("text1");
text1.onblur = function () {
    var text2 = document.getElementById("text2");
    text2.value = this.value + " month(s)";
};

If jQuery is available this will be much easier, but the code can be rewritten to work without it if it's not.

When an input loses focus, the blur event is fired, and when it regains focus the focus event is fired. If you store the original value (say, using jQuery's data method), you can acplish what you're asking fairly easily:

<input type="text" name="months" class="month" />
<input type="text" name="price" class="price" />

<script>
    jQuery(function($) {
        $('.months')
            .blur(function(event) {
                // This code runs when the input with class "months" loses focus
                var originalValue = $(this).val();
                $(this)
                    .data('original-value', originalValue)
                    .val(originalValue + ' months');
            })
            .focus(function(event) {
                // This code runs when the input with class "months" gains focus
                var originalValue = $(this).data('original-value');
                if (typeof originalValue !== 'undefined') {
                    $(this).val(originalValue);
                }
            });

        $('.price')
            .blur(function(event) {
                // This code runs when the input with class "price" loses focus
                var originalValue = $(this).val();
                $(this)
                    .data('original-value', originalValue)
                    .val('$ ' + originalValue);
            })
            .focus(function(event) {
                // This code runs when the input with class "price" gains focus
                var originalValue = $(this).data('original-value');
                if (typeof originalValue !== 'undefined') {
                    $(this).val(originalValue);
                }
            });

        $('form.myform')
            .submit(function(event) {
                // This code runs when the form is submitted
                // Restore the original values, so they are submitted to the server
                $('.months').val($('.months').data('original-value'));
                $('.price').val($('.price').data('original-value'));
            });

    });
</script>

I've done it all without javascript... The problem was that it changed the value of the input field but I didn't need that.

So I've just made images of '$' and 'month' and added them as a background in CSS to the inputs... In the first input field i wrote a property maxlenth='3' so numbers won't be written over the constant text and in the second field I've done padding-left='15px' in CSS.

Thanks everyone.

发布评论

评论列表(0)

  1. 暂无评论