Murtaza Munshi
Murtaza Munshi

Reputation: 1085

How to pass string in Javascript function dynamically

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.

Upvotes: 1

Views: 2398

Answers (6)

Ivin Raj
Ivin Raj

Reputation: 3429

You can do this one:

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

Upvotes: 2

rajuGT
rajuGT

Reputation: 6404

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 + '\"); ">'

Upvotes: 1

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

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;
    });

Upvotes: 0

Satpal
Satpal

Reputation: 133403

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

Upvotes: 2

Kjell Post
Kjell Post

Reputation: 19

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?

Upvotes: -1

Sunil
Sunil

Reputation: 929

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

Upvotes: -1

Related Questions