noone392
noone392

Reputation: 2158

javascript scope not actually global

var _gquill;
var _gform;

function quillFunctionSetup(quillvar, quillformvar, quillsubmitvar) {   
    _gquill = new Quill("#".concat(quillvar), {
        modules: { toolbar: true },
        theme: 'snow'
    });
   
    _gform = document.getElementById(quillformvar);
    _gform.onsubmit = function(quillsubmitvar, _gquill) {     
        var about = document.getElementById(quillsubmitvar);       
        about.value = _gquill.container.firstChild.innerHTML;
        return false;
    };
}
<script src="https://cdn.quilljs.com/1.0.0/quill.js"></script>
<link href="https://cdn.quilljs.com/1.0.0/quill.snow.css" rel="stylesheet">
<form action="{% url 'SecurityTarget:stview' ST_Title.id %}" method="post" id="overviewform">
  <div id="quilleditor" >{{ST_Title.OverviewDescription}}</div>
  <input type="hidden" name = "new_overview" id="new_overview"/>
  <input type="submit" value="Save Toe Overview" />
</form>
<script type="text/javascript">quillFunctionSetup("quilleditor", "overviewform", "new_overview");</script>

So this doesn't work and I am having trouble understanding why. so the quill portion works fine, and when it was a script defined in line with the html everything worked great. I moved it to the header and then nothing worked because the elements weren't defined yet? so I wrapped it in a function and called it inline, but then my submit button stopeed functioning which I still don't know why, but function(quillsubmitvar, _gquill) adding quillsubmitvar to the line above (it originally wasn't there made it work) which makes no sense sense this is within the scope of the original function.

and still with this code

about.value

never gets assigned ?? also when running this script in this editor it says undefined reference to the function

quillFunctionSetup

but it is defined in the header, and it runs on my website?? I am so confused any help is greatly appreciated.

Upvotes: 0

Views: 56

Answers (1)

jmcgriz
jmcgriz

Reputation: 3358

The issue is in this line: _gform.onsubmit = function(quillsubmitvar, _gquill) {

In this casequillsubmitvar and _gquill aren't being passed in, they're being listed as the names of the parameters that will be passed to that function, in the same way that the first declaration works function quillFunctionSetup(quillvar, quillformvar, quillsubmitvar) {

Javascript is lexically scoped, meaning that anything within quillFunctionSetup already has access to the other variables defined within that closure and anything outside of it, but nothing defined within a separate closure elsewhere (not applicable in this case).

_gform.onsubmit = function() {     
    var about = document.getElementById(quillsubmitvar);       
    about.value = _gquill.container.firstChild.innerHTML;
    return false;
};

Should work as expected

Upvotes: 1

Related Questions