1

I have a javascript function like this

function doIt(link) {
    alert(link);
}

And i call this function in below given JS code, where i am creating an a tag and appending it to my html page on runtime:

jQuery.each(data, function (i, val) {
    var card = '<a href="Views/NewsDetail.html" onclick=" doIt(' + val.Img + '); "> \
                <div class=" card"> \
                <img src='+ val.Img + ' /> \
                <p>'+ val.Title + '</p> \
                </div> \
                </a>';
    document.getElementById('News').innerHTML += card;
});

Say for example our val.Img = 'abcd' When i click the a tag it calls doIt(abcd), but i want to call doIt('abcd') passing it as string.

Is there any workaround for this.

Murtaza Munshi
  • 1,065
  • 4
  • 13
  • 40

6 Answers6

2

You need to escape quotes like

var card ='<a href="Views/NewsDetail.html" onclick="doIt(\'' + val.Img + '\'); "> \
                                                        //^               ^

As per your current implementation the argument abcd is treated as variable thus you must be getting undefined

Satpal
  • 132,252
  • 13
  • 159
  • 168
2

You can do this one:

var card='<a href="Views/NewsDetail.html;" onClick="Test(\'' + val.Img + '\'); "></a>';
Ivin Raj
  • 3,448
  • 2
  • 28
  • 65
1

The below HTML string already used both quotes till the characters doIt(. So any string type values inside the quotes, must be escaped using any of the quote-character.

 var card = '<a href="Views/NewsDetail.html" onclick=" doIt(' + val.Img + '); ">'

to [added quote escape character \"]

 var card = '<a href="Views/NewsDetail.html" onclick=" doIt(\"' + val.Img + '\"); ">'
rajuGT
  • 6,224
  • 2
  • 26
  • 44
0

Yet another option:

   var doItAndRedirect=function(val){
           //do stuff with val here
       window.location = "Views/NewsDetail.html"; 
    }

    jQuery.each(data, function (i, val) {
        var card = '<a href="javascript:doItAndRedirect(\''+ val +'\')">'+
                    '<div class=" card">' +
                    '<img src='+ val.Img + ' />' +
                    '<p>'+ val.Title + '</p>' +
                    '</div>'+
                     '</a>';
        document.getElementById('News').innerHTML += card;
    });
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
-1

It is already a string it just doesn't display '' on alert but at the background it is string only.

Sunil
  • 919
  • 15
  • 25
  • @MurtazaMunshi but you said in your question that function getting called as doIt(abcd); – Sunil Sep 25 '15 at 11:32
-1

doIt("' + val.Img + '");

should do it, but if you have, e.g, " inside val.Img you need to quote those: How do I add slashes to a string in Javascript?

Community
  • 1
  • 1
Kjell Post
  • 19
  • 4