Is it possible to execute ".value + =" in jQuery?

Classic javascript:

var myvar = document.getElementById("abc"); abc.value += "test"; abc.value += "another test"; 

Jquery:

 $("#abc").val($("#abc").val()+"test"); $("#abc").val($("#abc").val()+"another test"); 

Is there a way to make my jQuery more beautiful, perhaps with a hidden + = function that I could use? I know that .val () is not an attribute, but I feel there must be a way to make this code more beautiful to look ...

Something like this would be great:

  $("#abc").valueAttribute += "test" $("#abc").val().content += "test" $("#abc").val().add("test") 
+17
javascript jquery
Aug 03 '09 at 19:19
source share
5 answers

Since jQuery 1.4, you can pass the .val() function, which receives the current value as the second argument:

 $("#abc").val(function(i, val) { return val + "test"; }); 
+12
Mar 19 2018-11-11T00:
source share

You can return to the original DOM element.

  $("#abc").get(0).value += "test"; 

Otherwise, you will have to write a plugin

  $.fn.appendVal = function (newPart) { return this.each(function(){ $(this).val( $(this).val() + newPart); }); }; $("#abc").appendVal("test"); 
+23
Aug 03 '09 at 19:32
source share

I have never come across anything like that, does not mean that it does not exist, though.

I usually just store val () in a temporary variable and do the manipulation on it, and then call val (temp) on a separate line. It extends the operation to three or more lines, but it is more readable than .val(.val() + "") , IMO. It also scales better than + = if you have a more complex expression for the value.

 var temp = $(".abc").val(); temp += "test"; $(".abc").val(temp); 
+2
Aug 03 '09 at 19:25
source share

$() returns the selection; it does not return the actual resulting object (although in practice it simply returns a list of actual objects). If you want to change the property of the .value object, you can do this:

 $('.abc').each(function(){ this.value += foo; }); 

If you like, you can create functions that work with selections, for example .add() , which can be implemented as follows:

 jQuery.fn.extend({ add: function(k,v) { this[k](this[k]()+v); } }); 

which can then be used as follows:

 $('.abc').add('val', foo); 

... but I don't think this is better than using $().each()

+1
Aug 03 '09 at 19:35
source share
 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript"> (function($){ $.fn.valInc = function(vadd) { var val = $(this).val() + '' + vadd; $(this).val(val); } })(jQuery); $(function(){ $("#tst").valInc('test 2'); }); </script> </head> <body> <input id='tst' value="test" /> </body> </html> 
0
Aug 03 '09 at 19:42
source share



All Articles