Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - onchange this.form.submit() not working for web form

been working on this way too long...but can't seem to identify the problem. Already read dozens of articles on stackoverflow and elsewhere.

when I click and change the value, it doesn't auto-submit:

   <form id="orderbyfrm" name="orderbyfrm" action="http://staging.whiterabbitexpress.com/" method="post" class="orderbyfrm">
            <input name="s" value="<?php echo $wre_search_txt?>" type="hidden">
            <label for="orderby" class="sortByLabel">Sort by&nbsp;</label>
            <select class="sortByDropdown" name="orderby" id="orderby" onchange="this.form.submit();">
                <option value="Relevance">Relevance</option>
                <option value="likes" selected="selected">Likes</option>
            <option value="comments" selected="comments">Comments</option>
            </select>
</form>

in Chrome inspector I see an error "Uncaught TypeError: Cannot call method 'submit' of null" onchange

I also tried onchange="javascript:document.orderbyfrm.submit" but that didn't work either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Probably you have element or JS object called form or submit somewhere, conflicting with the real form.

Most safe way is using document.getElementById:

<select onchange="SubmitForm('orderbyfrm');">

And the JavaScript:

function SubmitForm(formId) {
    var oForm = document.getElementById(formId);
    if (oForm) {
        oForm.submit(); 
    }
    else {
        alert("DEBUG - could not find element " + formId);
    }
}

Further debugging with good old alert.. instead of the alert("DEBUG ... have this:

var sDebugInfo = "found " + document.forms.length + " forms: 
";
for (var i = 0; i < document.forms.length; i++) {
    var curForm = document.forms[i];
    sDebugInfo += "name: " + curForm.name + ", id: " + curForm.id;
    sDebugInfo += "
";
}
alert(sDebugInfo);

Depending on what you get, debug should continue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...