简体   繁体   中英

How to “append” a value with jQuery instead of replace it completely?

The way I understand val works is that when you do

$(".foo").val("x") 

you literally replace the value for the input. Does anything in jQuery 2.x support a "append" like function instead? I found a unit/integration like scenario that would let me reproduce a real but ... except that val replaces the input's value completely instead of "just adding a single char" like my end user would.

Access the callback function of .val( cb ) and return the current value concatenated with a string of your choice:

 $(".foo").val(function(i, currVal) { return currVal + "whatever"; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="foo" tyle="text" value="A-"> <!-- A-whatever --> <input class="foo" tyle="text" value="B-"> <!-- B-whatever --> 

If you want a jQuery method like .valAppend() than you can create one:

$.fn.valAppend = function( str ) {
  return this.val( this[0].value + str );
};

// Use like:
$(".foo").valAppend( "whatever" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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