How to append input in the same field after enteri

2019-09-01 15:00发布

I have an input field and I want to append its text while typing in it and persisting the previous value in it

Following is the code

<input type="text" id="txt1" name="type_name" value="Value1-" onchange="dosomething()">

What I want is when the user starts typing it the starting text of input field should remain there which is "Value1-" and append the text in it like "Value1-3433".

I hope you get my point a little help on this will be appreciated.

标签: jquery html
4条回答
2楼-- · 2019-09-01 15:51

is this what you want ?

DEMO

jQuery

$('#txt1').on('keyup',function(){
    console.log($(this).val().substr( 0 , 7)) ;
    if($(this).val().substr( 0 , 7) != "Value1-") {
        $(this).val('Value1-');
    }
});

HTML

<input type="text" id="txt1" name="type_name" value="Value1-" >
查看更多
唯我独甜
3楼-- · 2019-09-01 15:55

Working Fiddle

  1. Append a label with position:absolute
    HTML

    <label id="lbl" for="txt1"></label> <input type="text" id="txt1" name="type_name" value="" />

    And fire an onchange event, to change add the Value1- and users input...

  2. Add Value1 onchange event

    $('#txt2').change(function () { var str = $(this).val().replace('Value1-',''); $(this).val('Value1-'+str); });

  3. Finally, I guess what you needed is here...

$('#txt3').keypress(function (e) { var pos = $(this).getCursorPosition(); if (pos < 7 ||(pos==7 && e.keyCode == 8) ) { e.preventDefault(); } });

Source : Made with great support from this answer by @MarkB29

查看更多
Rolldiameter
4楼-- · 2019-09-01 15:59

If I got it correct,with pure JavaScript,this is what you need to do:

  1. Call a function start() when the page loads with <body onload="start()">. Print the text "Value1-" in the input TextField. Since this function is called only once,the Value1- will be printed only once.
  2. Create another function append() which you should call using onchange() and do:
    `document.getElementById('outputText').value=document.getElementById('txt1').value.

Hope this helps.

查看更多
做自己的国王
5楼-- · 2019-09-01 16:04

Use the following code to achieve this.

Jquery code:

$('#txt1').on('keyup',function(){

var str=$(this).val();
var newstr = str.substring(0, 7);

if(newstr != "Value1-")
{       
    $(this).val("Value1-");
}  

});

HTML Code:

<input type="text" id="txt1" name="type_name" value="Value1-">

Working Jsfiddle link

http://jsfiddle.net/spdZW/1/

查看更多
登录 后发表回答