Reputation: 29
I have two scripts defined in an HTML page. I call the 'function2' script from an onclick event attached to a Submit button. When I click the submit button, I get an uncaught reference error - function1 is not defined
.
function1
extracts a variable from the URL (I have in the url of the page the following variables: ?m=1&u=2&f=3
).
function2
assigns (one at a time) the url variables to local variables, then assigns these local variables to be the values of 3 hidden form fields (field IDs: msg, mem, and frm).
I added the vars to show up in the console.log but they never make it there since the function isn't defined...
Any ideas what I've done wrong?
<script language="javascript">
function function1(param) {
var pattern = new RegExp('[?&]' + param + '((=([^&]*))|(?=(&|$)))', 'i');
var mz = window.location.search.match(pattern);
return mz && (typeof(mz[3]) === 'undefined' ? '' : mz[3]);
}
</script>
<script language="javascript">
function function2() {
var mm = (function1('m'))();
var uu = (function1('u'))();
var ff = (function1('f'))();
document.getElementById("msg").value=mm;
document.getElementById("mem").value=uu;
document.getElementById("frm").value=ff;
console.log("mm:", mm);
console.log("uu:", uu);
console.log("ff:", ff);
}
</script>
Upvotes: 2
Views: 968
Reputation: 23406
You've IIFEs (Immediately Invoked Function Expression) like:
(function1('m'))();
At first, function1
is executed, then JS tries to invoke the returned value from function1
, but it doesn't return a function, hence an error.
To fix this, just remove the IIFEs, i.e:
mm = function1('m');
Upvotes: 1