jquery .val() += idiom

喜夏-厌秋 提交于 2019-11-30 18:00:16

Just don't use jQuery.

document.getElementById('someTextarea').value += someString;

will be clearer, faster, and works as well as the jQuery snippet. If you really want to use the $ selector, with only one element you can also

$('#someTextarea')[0].value += someString; // least to type

Other possibilities are the .val() method with a function

$('#someTextarea').val(function(index, oldValue) { return oldValue + someString; })

or a variant with .each() (which is [nearly] equivalent to what val() does internally for text inputs):

$('#someTextarea').each(function(){ this.value += someString; })

These both need a one-line function expression you didn't like, but they have the advantage of working for more than one selected elements (and not breaking for no matched element) and they also return the jQuery object to preserve the chainability feature.

You can pass a function:

$(...).val(function(index, old) { return old + whatever; });

I don't know about idiomatic but one way to simplify this jQuery expression is to use the overload of val which takes a function object as a parameter. jQuery will pass in the old value to the function and you pass back the new value.

$('#someTextarea').val(function(_, oldValue) { return oldValue + something; }); 
$('#someTextarea').val(function() {
  return this.value + something;
});

or

$('#someTextarea').val(function() {
  return $(this).val() + something; 
});

or

// mentioned by SLaks, JaredPar

$('#someTextarea').val(function(i, oldVal) {
  return oldVal + something;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!