JS: Using confirm inside a function

Status
Not open for further replies.

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Why does the first anchor element confirm as expected, but the others do not?

Code:
<html>
<head>
    <script type="text/javascript">
        function RUSure(e) {
            alert("RUSure");
            return e.window.confirm('Are you sure?');
        }
        function MakeSure(e, url) {
            alert("MakeSure");
            var sure = RUSure(e);
            if (sure)
                window.location.hostname = location.hostname + url;
            return sure;
        };
    </script>
    <title>Example</title>
</head>
<body>
    <a href="/?ThisWorksFine" onclick="return confirm('Are you sure?')">This works</a>
    <div><a href="#" onclick=" makesure(e, '/?ThisDoesntCallConfirm');">This doesn't</a></div>
    <div><a href="#" onclick="return makesure(e, '/?ThisDoesntCallConfirm');">This doesn't</a></div>
        <div><a href="/?ThisDoesntCallConfirm" onclick="return RUSure(e);">This doesn't</a></div>
        <div><a href="/?ThisDoesntCallConfirm" onclick="RUSure(e);">This doesn't</a></div>
        <!--The below didn't work either -->
        <!--<script>
            window.onload(function () {
                var aTags = document.getElementsByTagName('a');
                for (var i = 0; i < aTags.length; i++)
                    aTags[i].addEventListener('click', RUSure);
            });
        </script>-->
</body>
</html>
Example code hosted here
 

krimhorn

Ars Legatus Legionis
39,865
e is half the problem. It's trying to reference a variable that doesn't exist as it enters the function. Even if you didn't receive the error "makesure is not defined" you'd still die on "e is not defined".

makesure(e, url) is not defined. It's defined as MakeSure(e, url)

Remove the reference to e everywhere, you're not grabbing an event (you're calling a function) so there's nothing to receive there (and a naked variable in HTML has no meaning unless you've got a global that you do not have). window.confirm() is all you need in RUSure().
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
[url=http:/civis/viewtopic.php?p=28721407#p28721407:hz2cs8iu said:
krimhorn[/url]":hz2cs8iu]e is half the problem. It's trying to reference a variable that doesn't exist as it enters the function. Even if you didn't receive the error "makesure is not defined" you'd still die on "e is not defined".

makesure(e, url) is not defined. It's defined as MakeSure(e, url)

Remove the reference to e everywhere, you're not grabbing an event (you're calling a function) so there's nothing to receive there (and a naked variable in HTML has no meaning unless you've got a global that you do not have). window.confirm() is all you need in RUSure().
Although I was convinced I had tried this before posting this, this does work. Kudos.

I knew I had stared at this way, way too long. . .
 
Status
Not open for further replies.
\n