Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot pass string to function

I'm using javascript and I try to pass a string to a function , like so

        //example string
        var f="a";

//add button that sends the value of f to the function
     document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere("+f+");'> ";

    function gothere(a){
    alert(a);
    }

I never see the alert and in console I see a is not defined (refers to the f I guess?)

If i set the f var to be a number then I see the alert.

What am I missing?

Thanks in advance

EDIT

I was thinking maybe something like

var buttonnode= document.createElement('input');

document.getElementById("mydiv").appendChild(buttonnode);
buttonnode.onclick=gothere(f);

Wont work for the same reason?

like image 323
user2860857 Avatar asked Dec 25 '22 18:12

user2860857


2 Answers

When your HTML get's rendered, you get onclick='gothere(a);', but the actual a variable doesn't exist in this context, you want to pass the value of f, as a string, so you'll need to use onclick='gothere(\""+f+"\");'. Note the extra quotes inside the parens. This will render to onclick='gothere("a");' thus passing the string.

When using a number, it works, because calling onclick='gothere(5);' is valid, since a variable can't be named 5, and it passes the number.

like image 54
CDspace Avatar answered Jan 12 '23 08:01

CDspace


Actually, you don't have an a in your code. You are using variable f to denote a. So using this would help you:

var f="a";
// write the remains of the code as they are..

function gothere(f) {
  alert(f);
}

Now when you'll call the function, there will be an alert of a in the browser.

Also, try wrapping the content in "" double qoutes to let the code understand that this is a string not a character.

For onclick use

onclick='gothere(" + f + ")'

And now, its onto you to write the value. Maybe the issue is because you're not writing the value for the f.

Try inpecting the error. I am sure there won't be anything.

Or try using the attribute field and change it using jQuery.

like image 32
Afzaal Ahmad Zeeshan Avatar answered Jan 12 '23 08:01

Afzaal Ahmad Zeeshan