1

When adding text to an element, jQuery's append() function adds quotation marks around text. I want to change that, and instead separate values by comma or whatever I come up with. Is there an alternative to append() that will do that ?

To give it some context, I'm using jQuery to dynamically write to a hidden <input> element.

Currently after a few additions (using append) the resulting HTML looks like this:

<input type="hidden">"first"
    "second"
    "third"
</input>

In an ideal world, the HTML should come out looking like this:

<input type="hidden">first, second, third</input>

Using jQuery to read, concatenate, and then replace the original <input> text might work, but I don't see a function that will do a wholesale replace of innerHTML (I'm assuing it's called that).

Thoughts ?

JHarnach
  • 3,944
  • 7
  • 43
  • 48

4 Answers4

3

in jquery:

<div id="test"></div>

$('#test').append('a');
$('#test').append('b');

will look like this (in chrome dev tool):
<div id="test">
"a"
"b"
</div>

while

<div id="test"></div>

$('#test').html($('#test').html() + 'a');
$('#test').html($('#test').html() + 'b');

will look like this:

<div id="test">ab</div>

the dom tree in both cases is the same, only it shows it in chrome dev tool with the quotes (they are not really there, right click -> edit as html and they will disappear)

galchen
  • 5,252
  • 3
  • 29
  • 43
1

The big problem here is that input values are set in the value attribute, not as an inner child:

<input type="hidden" id="myInput" name="myInput" value="first">

To do what you seem to want, you'd probably want to change the value of the input with .val():

$('#myInput').val($('#myInput').val() + ', second');
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
0

Alternatively you could append text to a hidden span:

<style> #hidden { display:none; } </style>

<span id="hidden"></span>

<script>
var x; // Where 'x' is the data that you would like to append.
$('#hidden').append(x);
</script>
Josiah
  • 1,117
  • 5
  • 22
  • 35
0
(function($) {
    $.fn.iappend = function(str) {
        return this.each(function(){
            var $this = $(this);
            if($this.val().length > 0) {
                $this.val($this.val() + "," + str);
            } else {
                $this.val($this.val() + str);
            }
        });
    };
})(jQuery);

I haven't fully tested it yet.. but it should work..

$("#hidden").iappend("first").iappend("second").iappend("third");

output

Hello,World,!

rlemon
  • 17,518
  • 14
  • 92
  • 123