19

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 prettier, maybe 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 at...

Something like this would be great:

 $("#abc").valueAttribute += "test"
 $("#abc").val().content += "test"
 $("#abc").val().add("test")
6
  • 1
    Be careful with any solution that uses .value (including the first part of my answer). It will only work for <input> elements. You may end up pulling your hair out one day if abc becomes a <textarea>. Aug 3, 2009 at 19:50
  • yes I know, it will only be for input elements :)
    – marcgg
    Aug 3, 2009 at 19:54
  • possible duplicate of Append text to input field Aug 26, 2014 at 14:51
  • 1
    I wish Stack Overflow had a feature where the author of an old accepted answer could propose moving the check mark to a newer answer. In this case, Felix's answer is better. Jul 23, 2015 at 17:06
  • @PatrickMcElhaney I changed the accepted answer to Felix's :)
    – marcgg
    Jul 27, 2015 at 8:09

5 Answers 5

24

You could go back to the original DOM element.

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

Otherwise, you'd have to write a plugin

 $.fn.appendVal = function (newPart) {
   return this.each(function(){ $(this).val( $(this).val() + newPart); });
 };

 $("#abc").appendVal("test");
4
  • 3
    Plugin is nice solution, but shouldn't it do return this.each(function(){ $(this).val( $(this).val + newPart); }); --- preserve chain ability and apply to multiple elements if needed?
    – gnarf
    Aug 3, 2009 at 19:56
  • Yes, gnarf, that's much better. Thanks! I rewrote the plugin using your code. Aug 3, 2009 at 20:08
  • Cool - Deleting my answer then!
    – gnarf
    Aug 3, 2009 at 20:09
  • one last comment on the plugin... return this.each instead of $(this).each - "this" will be a jquery object already - no need to pass it through the jquery function again.
    – gnarf
    Aug 3, 2009 at 20:34
16

Since jQuery 1.4, it is possible to pass a function to .val() which gets the current value as second argument:

$("#abc").val(function(i, val) {
    return val + "test";
});
2

I've never come across anything like that, doesn't mean it doesn't exist though.

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

var temp = $(".abc").val();
temp += "test";
$(".abc").val(temp);
1
  • True, it would look better. I don't worry about scalling since it's a pretty simple function and there is no reason for it to evolve too much.
    – marcgg
    Aug 3, 2009 at 19:27
2

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

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

If you like, you can create functions that operate on selections, such as .add(), which could be implemented like this:

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

which can then be used like this:

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

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

0
<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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.