Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .val() += idiom

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.

like image 894
gruntlr Avatar asked May 07 '12 19:05

gruntlr


People also ask

What does val () in jQuery do?

val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined .

What is $$ in jQuery?

$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.


1 Answers

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.

like image 92
Bergi Avatar answered Sep 21 '22 06:09

Bergi