简体   繁体   中英

Append new line of text without using “.append”

I have a dropdown that has contacts in there, ie John , Bob , etc. and a button next to it that when it's clicked, it will display the contact's phone number in my <textarea></textarea> .

Each time when I pick a contact and press the button, I want to display the number in my textarea and each additional contact's number I add I want the number to display below the previous number. So basically I need a line break between each number like this.

1234567890

5557778888

When I use my first function using .append , it works the way I want however, if I edit the numbers or take out numbers, I can't use my button to add numbers to the textarea anymore. I realized from this SO article that it's because the text nodes and the value can be disconnected.

Then I tried using .val , however this just replaces the numbers in my textarea instead of appending below it.

What would be the best way to solve this problem? Thanks!

Let me know if you need any additional information.

My javascript functions:

Using .append()

    selectOption: function() {

        $('#addContact').click(function() {
            $('#toPhoneNumber').append($('#toAdd option:selected').data('number') + '&#xA;');

        });

    },

Using .val()

    selectOption: function() {

        $('#addContact').click(function() {
            $('#toPhoneNumber').val($('#toAdd option:selected').data('number') + '\n');

        });

    },
var nums =[];
.
.
selectOption: function() {
  $('#addContact').click(function() {
    var num =$('#toAdd option:selected').data('number'); 
    if (nums.indexOf(num)==-1) nums.push(num);
    $('#toPhoneNumber').val(nums.join( '\n'));
  });
},

With val you can try:

selectOption: function() {
        var temp = $('#toPhoneNumber').val();
        $('#addContact').click(function() {
            $('#toPhoneNumber').val(temp + $('#toAdd option:selected').data('number') + '\n');

        });

    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM