简体   繁体   English

附加文字以在点击时输入(JQuery)

[英]Appending text to input on click (JQuery)

got a little problem on my hands. 我手上有点问题。

I Am appending text to input on click. 我将文本添加到点击输入。 Works fine, but I want to append the text on button click, and on second and each click to append the same text without replicating/adding to the previous appended text. 工作正常,但我想在按钮单击时添加文本,并在第二次和每次单击时添加该文本,以添加相同的文本,而不复制/添加到先前添加的文本。

So, basically on each click to clear the input of any text ( if any ) and append the same text on click. 因此,基本上,每次单击都会清除任何文本(如果有的话)的输入,并在单击时附加相同的文本。

I wrote the following JQuery : 我写了以下JQuery:

$('.button').click(function(){
  $('#inputText').val($('#inputText').val() + 'Text to append');

  if($('#inputText').val() > 0) {
     $('#inputText').val('');
  } else {

}
});

I tried some other conditions but with no success. 我尝试了其他一些条件,但没有成功。 I don't know why. 我不知道为什么

I think that this is what you're looking for. 我认为这就是您要寻找的。

$('.button').on("click", function(){

  var text = "some text";
  var input = $('#inputText');
  var textLocation = $(input).val().indexOf(text);

  if(textLocation === -1){
    $(input).val( $(input).val() + text );
  }else{
    $(input).val( $(input).val().substr(0, textLocation) + text );
  }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM