What's the clearest commonly used idiom for this jQuery snippet?
$('#someTextarea').val( $('#someTextarea').val() + someString );
It feels clunky to wrap the original code in a one-line function
EDIT: So I can pass a function, which is cool... but my real intentions are for jsfiddles, where I currently do stuff like this:
function lazylog (str) {
$('#ta').val( $('#ta').val() + str + '\n' );
}
// or
function lazylogPlain (str) {
document.getElementById('ta').value += str + '\n';
}
// view results of little experiments
lazylog( test1() );
lazylog( test2() );
lazylog( test3() );
// etc...
Don't know if that context would produce different answers or just make me seem really lazy for wanting to type even less than that. console.log
doesn't count, I want the textarea.
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;
});
来源:https://stackoverflow.com/questions/10487850/jquery-val-idiom