Kwaadjei
Kwaadjei

Reputation: 309

How to append a string variable in Jquery html elememt attribute

Please , I have a JQuery code when appends data to a div element sucessfully like this

 $('#conversation').append('<div id="receiver"><p><b>' + username + ':</b> ' + data + '</p></div><br>');

Now supposing I want to have an anchor tag which will have a hyperlink inside as an atrribute and I want to pass a variable to that href attribute not the link itself since I don't know the kind of link that will be sent. I have problems tring to append this.

 $('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>');

This does not work. Any idea how to go about this. This is my whole code snippet

socket.on('updatechat', function (username, data) {
//showing username and the message sent
var checkifdataisalink=data;
var check=checkifdataisalink.split('://')
if((check[0]=='http')||(check=='https'))
{
    $('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>');
}else{
$('#conversation').append('<div id="receiver"><p><b>' + username + ':</b> ' + data + '</p></div><br>');
}

});

Upvotes: 0

Views: 108

Answers (2)

lshettyl
lshettyl

Reputation: 8171

Apart from the missing quote, your or part of the if condition was missing [0]. See below.

//For demo purposes only
var check = ["http", "other-part-of-the-url"];
var username = "user";
var data = "data";
// --;--

if(check[0] == 'http' || check[0] == 'https') {
    $('#conversation').append('<div id="receiver"><p><strong>' + username + ':</strong> <a id="link" href="' + data + '">' + data + '</a></p></div><br/>');
} else {
    $('#conversation').append('<div id="receiver"><p><strong>' + username + ':</strong>' + data + '</p></div><br/>');
}

Demo@fiddle

Upvotes: 1

hamed
hamed

Reputation: 8033

Change

$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>')

into:

$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +'"></a></p></div><br>');

Just one ' was missing after data

Upvotes: 1

Related Questions