0

I realize this is javascript 101 and there are many questions along these lines on SO but I am extremely rusty on JS and can't seem to get this to work.

I am trying to change a parameter in some javascript B that calls a widget using another script A. It is important that A set the value in B before B is called so that B uses the desire value.

Here is the code I have right now:

A.
    <script type="text/javascript">
    function getName() {
    return "Raoul Walsh";
    }
    </script>
B.     
     <script type="text/javascript">
      new MyView.widget(
      {
      "name": "getName()",
      "locale": "en"
    }
      );
      </script>

The widget is not recognizing the value I want: 'Raoul Walsh' but instead recognizing the value 'getName()'. In other words it does not realize, I'm trying to call a function.

BTW, I also tried setting the value using the DOM unsuccessfully.

How can I set the value for the widget script before it executes so that it executes using my desired value.

Thanks in advance for any suggestions

1 Answer 1

1

You don't need the quotes, simply call getName()

<script type="text/javascript">
    function getName() {
        return "Raoul Walsh";
    }
</script>
<script type="text/javascript">
  new MyView.widget({
      "name": getName(),
      "locale": "en"
    });
</script>

In case javascript doesn't recognize the function, there may be some scoping issue going on that are hard to debug without having the full page.

In that case, you can fix the problem by attacching the function to the window object

<script type="text/javascript">
    window.getName = function() {
        return "Raoul Walsh";
    }
</script>
<script type="text/javascript">
  new MyView.widget({
      "name": window.getName(),
      "locale": "en"
    });
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

That worked with "Raoul Walsh" hardcoded in the function as in my question. Is there any way, I could change that value dynamically? I tried creating a supposedly global variable myvar = "Raoul Walsh" and returning that in the function with return myvar.. But it did not work. I would like to call a javascript function that sets the variable dynamically. If you'd prefer I can put this in another question.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.