cindy
cindy

Reputation: 1

Javascript function excute automatically in web2py

I have a checkbox in the frontend, and would like to update database according to the status of checkbox, I also have save button to submit.

Now I got confused. Everytime I turned to changeActive/id page, without clicking the button, it updates database directly.

alert works fine.

this is the code in controller:

def changeActive():
    post=db.student(request.args(0,cast=int))
    def change(value):
        changeStatus=db(db.student.id==post.id).update(is_active=value)
        return changeStatus
    return locals()

This is the code in changeActive.html

{{extend 'layout.html'}}
<h1>it is a test</h1>
<h2>{{=post.name}}</h2>
<h2>{{=post.id}}</h2>
<h2>{{=post.is_active}}</h2>


<input type=checkbox id=is_active>
<input id="save"  type="button" value="save"/>
<script type="text/javascript">
window.onload=function()
    {
        var saveButton=document.getElementById('save');
        saveButton.onclick=function()
        {
            var changeSt=document.getElementById('is_active');
            if (changeSt.checked)
            {
                alert('active')
                {{change('T')}}
            }
            else
            {
                alert ('not active')
                {{change('F')}}
            }
        };
    };
</script>

Upvotes: 0

Views: 571

Answers (1)

Anthony
Anthony

Reputation: 25536

It appears you are expecting Python functions to be executed by the browser after the page has been loaded. This is not how web2py templates work. The templates include Python code, which is executed on the server before the page is sent to the browser. Therefore, the calls to the change() function are happening before the page ever reaches the browser.

What you probably want to do instead is trigger an Ajax call in the browser, which would call a separate function on the server to handle the update. You can handle that via jQuery (or other suitable Javascript options), or use web2py's built-in Javascript ajax() function, as described here.

Upvotes: 1

Related Questions