简体   繁体   中英

Assign html <a> tag to a textarea value

I need to assign an <a> tag to a textarea value, separated with a comma. I'm trying to insert email IDs I get from a response of an ajax request. How do I achieve this using JS?

I tried using:

$('reminder_email').value += "<a href='#' id='+id'>+email+</a>";

Assuming that 'reminder_email' is the id of the relevant textarea , and that the response is an array of emails:

var emailAddressesArray = ['emailAddress@host.tld', 'emailAddress2@otherHost.tld'];
$('#reminder_email').val(emailAddressesArray.join(', '));

JS Fiddle demo .

If, on the other hand, you're trying to create the HTML of an a element with a mailto protocol (for copying/pasting elsewhere):

var email = 'emailAddress@host.tld';
$('#reminder_email').val('<a href="mailto:' + email + '">' + email + '</a>');

JS Fiddle demo .

Note that you can't create clickable links within a textarea , as they can't contain HTML ( just text).

If, though, you have an object from which to create your value:

var email = [{
    'address': 'emailAddress@host.tld',
        'id': 'emailOne',
        'text': 'UserNameOne'
}, {
    'address': 'anotherAddress@host2.tld',
        'id': 'emailTwo',
        'text': 'UserNameTwo'
}];
$('#reminder_email').val(function(_, v){
    for (var i = 0, len = email.length; i < len; i++){
        v += '<a href="mailto:' + email[i].address + '" id="' + email[i].id + '">' + email[i].text + '</a>, ';
    }
    return v.slice(0, v.length - 2);
});

JS Fiddle demo .

The reason your code:

$('reminder_email').value += '<a href='#' id='+id'>+email+</a>;

didn't work is twofold:

  1. $('reminder_email') is a selector looking for reminder_email tags (which don't exist); assuming that it's an id you're looking for you'll need to use: $('#reminder_email') instead,
  2. A jQuery object/collection has no .value property, instead use the val() method (without arguments to get the current value, or with an argument to set a new value).

hoping you have jquery imported, try this:

$('reminder_email').val("<a href='#' id='"+id+"'>" + email + "</a>");

are you appending it? why do you use += ?

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