1

I have a js file.

File Name: propoties.js

function simple()
{
    alert("simple");
    var text = "Control";
}

These is my html code. What i want is alert that text variable in html.

<html>
<script type='text/javascript' src='path/propoties.js'></script>    
<script>
    simple();
    alert(text); /* It is not working */
</script>
 </html>

Please help me these. Thank you.

1

4 Answers 4

6

Your js file:

var simple=function(){
   var textMultiple = {
        text1:"text1",
        text2:"text2"
    };
   return textMultiple;
}

In your html:

<html>
    <script type='text/javascript' src='./relative/path/to/propoties.js'></script>    
    <script>
      alert(simple().text1);
      alert(simple().text2);
    </script>
 </html>

here is a plunkr demo.

Sign up to request clarification or add additional context in comments.

3 Comments

It's multiple variables. How to call?
Thanks for your answer. i gave the up vote. Thanks for your help.
i am glad it helped... dont forget to vote up answers that helped and select the answer by clicking the tick below it. and if you want to stick to javascript, you should learn its scope. here is good article for it.
1

like you did it the "text" variable is only set in the scope of the function "simple" .

you should make the "text" variable global by declaring it outside the function.

var text = "";

function simple()
{
    alert("simple");
    text = "Control";
}

3 Comments

sorry but it is working. there may be another error somewhere else in the code .... do you get any other JavaScript errors ?
Can you provide any jsfiddle please? Still it's not working.
Thanks for your answer. i gave the up vote. Thanks for your help.
1

If you want to alert the text in external file you need to declare the variable as global like below.

var text = "Control";
function simple()
{
    text="Changed";
    alert("simple");   
}

or you can declare the variable using window keyword

function simple()
{
    alert("simple");   
    window.text = "Control";
}

please check in plunker http://plnkr.co/edit/HjkwlcnkPwJZ7yyo55q6?p=preview

9 Comments

please alert as alert(window.text ) after calling simple() function
First you make sure whether the include path of external js file is correct.
It shows simple alert. Path of external js file is correct.
So, both of my code will work, I have checked in my system
Can you provide any jsfiddle please? Still it's not working.
|
0

Declaring the variable globally will work. ie

var text = "";
function simple()
{
     text = "Control";
}

see plunker

1 Comment

Its too late the answered that question. Thanks for your answer, I gave the tick you Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.