简体   繁体   English

使用onclick和onsubmit提交表单

[英]Submitting a form with onclick and onsubmit

I'm trying to setup a 'Click to Chat' system for my company. 我正在尝试为我的公司设置一个“点击聊天”系统。 It requires a form which captures some information from the user. 它需要一种可以从用户那里获取一些信息的表格。 When you submit the form, it's supposed to open a new window using the script in the .js file. 提交表单时,应该使用.js文件中的脚本打开一个新窗口。

I tried to add some validation, which resulted in both an onclick, and an onsubmit function. 我尝试添加一些验证,这导致了onclick和onsubmit函数。 When the form is subitted without the validation in place, it opens a new window using the BG.startChatWithIssueForm(this.form, true); 如果在未进行验证的情况下对表单进行了替换,它将使用BG.startChatWithIssueForm(this.form, true);打开一个新窗口BG.startChatWithIssueForm(this.form, true); function. 功能。 But, For some reason, when I include the onsubmit for validation, the onclick ignores it completely. 但是,由于某种原因,当我包含onsubmit进行验证时,onclick会完全忽略它。

I've tried nesting the BG.startChatWithIssueForm(this.form, true); 我试过嵌套BG.startChatWithIssueForm(this.form, true); function in different spots in the formValidator() function, but it still results in a file download prompt instead of opening a new window. 函数在formValidator()函数的不同位置出现,但是仍然会导致文件下载提示,而不是打开新窗口。

Not sure what I'm doing wrong. 不知道我做错了什么。 I've been researching this for weeks, and can't seem to come up with anything. 我已经研究了好几个星期,似乎什么也没想出来。 Javascript is definitely not my forte, so any assistance would be greatly appreciated. 绝对不是我的强项,因此,我们将不胜感激。

See the code below: 请参阅以下代码:

JS: JS:

function Bomgar() {
    var _host = "";
    var _protoRe = /^(http|https):\/\//;

    /* private */
    function _createURL(params, forPopup) {
        var qStr = "";
        for (var k in params) {
           qStr += "&"+encodeURIComponent(k)+"="+encodeURIComponent(params[k]);
        }
        qStr = "popup="+(forPopup ? "1" : "0") + "&c2cjs=1" + qStr;

        return _host+"api/start_session.ns?"+qStr;
    };

    function _openWindow(params) {
        return window.open(_createURL(params, true), 'clickToChat', 'toolbar=no,directories=no,status=no,menubar=no,resizable=yes,location=no,scrollbars=no');
    };

    function _redirectWindow(params) {
        window.location.href = _createURL(params, false);
    };

    function _startChat(params, doFull) {
        var w = _openWindow(params);
        if (w && !w.closed) { return; }
        else if (doFull) { _redirectWindow(params); return; }
    };

    function _startChatWithSurveyValues(surveyValues, fallbackToFullWindow) {
        surveyValues.issue_menu = '1';
        _startChat(surveyValues, fallbackToFullWindow);
    };

    /* public */

   // Set the public site hostname that click to chat should be started on.
   this.setSite = function(siteHostname) {
        if (!_protoRe.test(siteHostname)) { siteHostname = "http://"+siteHostname; }
        if (siteHostname[siteHostname.length-1] != '/') { siteHostname += '/'; }
        _host = siteHostname;
    };

    // Start a click to chat session using a session key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
    this.startChatWithSessionKey = function(sessionKey, fallbackToFullWindow) {
        var p = {short_key: sessionKey};
        _startChat(p, fallbackToFullWindow);
    };

    // Start a click to chat session using a session key and external key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
    this.startChatWithSessionKeyAndExternalKey = function(sessionKey, externalKey, fallbackToFullWindow) {
        var p = {short_key: sessionKey, external_key: externalKey};
        _startChat(p, fallbackToFullWindow);
    };

    // Start a click to chat session using just an issue id and no other front end survey fields.
    this.startChatWithIssueId = function(issueId, fallbackToFullWindow) {
        _startChatWithSurveyValues({id: issueId}, fallbackToFullWindow);
    };

    // Start a click to chat session by passing the entire front end survey form element.
    // This will submit all non-button input element values on the form.
    // Any unexpected survey field names will be ignored.
    this.startChatWithIssueForm = function(formElement, fallbackToFullWindow) {
        var params = {};
        for (var i = 0; i < formElement.elements.length; i++) {
            var e = formElement.elements[i];
            if (e.name && e.value && e.type && e.type != 'button' && e.type != 'submit') {
                params[e.name] = e.value;
            }
        }
        formElement = undefined;
        params.issue_menu = '1';
        _startChat(params, fallbackToFullWindow);
        return false;
    };

    // Start a session with a representative id and name.
    this.startChatWithRepIdName = function(repId, repName, fallbackToFullWindow) {
        var p = {id: repId, name: repName};
        _startChat(p, fallbackToFullWindow);
    };

    return this;
}
var BG = Bomgar();

HTML Code: HTML代码:

<script type="text/javascript" src="https://***.******.com/api/clicktochat.js"></script>
<script type="text/javascript">
BG.setSite("https://***.******.com");
</script>
<script type='text/javascript'>
function formValidator(){
    // Make quick references to our fields
    var issueid = document.getElementById('issueid');
    var username = document.getElementById('username');
    var userid = document.getElementById('userid');
    var issuedesc = document.getElementById('issuedesc');

    // Check each input in the order that it appears in the form

    if(madeSelection(issueid, "Please choose an issue"))
        {

        if(notEmpty(username, "Please enter your name"))
            {

            if(isAlphanumeric(username, "Numbers and Letters Only for name"))
                {

                if(notEmpty(userid, "Please enter your user ID"))
                    {

                    if(isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
                        {

                        if(notEmpty(issuedesc, "Please type a description of your problem"))
                            {  
                            }
                        }
                    }
                }
            }
        }
    }

    //check to make sure user selected their issue
    function madeSelection(elem, helperMsg){
        if(elem.selectedIndex == 0 ){
            alert(helperMsg);
            elem.focus(); // set the focus to this input
            return false;
        }else{
            return true;
        }
    }

    //check to make sure user entered something in the particular field
    function notEmpty(elem, helperMsg){
        if(elem.value.length == 0){
            alert(helperMsg);
            elem.focus();
            return false;
        }else{
            return true;
        }
    }

    //check to make sure user only entered numeric characters
    function isNumeric(elem, helperMsg){
        var numericExpression = /^[0-9]+$/;
        if(elem.value.match(numericExpression)){
            return true;
        }else{
            alert(helperMsg);
            elem.focus();
            return false;
        }
    }

    //check to make sure user only entered alpha characters
    function isAlphabet(elem, helperMsg){
        var alphaExp = /^[a-zA-Z]+$/;
        if(elem.value.match(alphaExp)){
            return true;
        }else{
            alert(helperMsg);
            elem.focus();
            return false;
        }
    }

    //check to make sure user entered only alpha or numeric characters
    function isAlphanumeric(elem, helperMsg){
        var alphaExp = /^[0-9a-zA-Z]+$/;
        if(elem.value.match(alphaExp)){
            return true;
        }else{
            alert(helperMsg);
            elem.focus();
            return false;
        }
    }
</script>
<script type="text/javascript">

/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul@REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function handleEnter (field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) {
        var i;
        for (i = 0; i < field.form.elements.length; i++)
           if (field == field.form.elements[i])
               break;
        i = (i + 1) % field.form.elements.length;
        field.form.elements[i].focus();
        return false;
    }
    else
        return true;
} 
</script>


<form action="https://***.******.com/api/start_session.ns" onsubmit="return formValidator();"  method="get">
What issue are you having?
<select onkeypress="return handleEnter(this, event)" id="issueid" name="id">
<option value="">Choose</option>
<option value="1">I need help getting started</option>
<option value="2">I am receiving an error</option>
</select>
<br />
Your First and Last Name: <input onkeypress="return handleEnter(this, event)" type="text" id="username" name="customer_name" /><br />
Your User ID (ABC1234): <input onkeypress="return handleEnter(this, event)" type="text" id="userid" name="customer_id" /><br />
Describe Your Issue: <textarea onkeypress="return handleEnter(this, event)" id="issuedesc" name="customer_desc"></textarea><br />
<input onkeypress="return handleEnter(this, event)" type="hidden" name="issue_menu" value="1" />
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
<br>
<input onkeypress="return handleEnter(this, event)" type="button" name="reset_form" value="Clear" onclick="this.form.reset();">

</form>
</body>

Have you tried replacing the submit button with a regular button, doing the validation in the onClick handler, and then submitting the form from within the onClick handler? 您是否尝试过用常规按钮替换“提交”按钮,在onClick处理程序中进行验证,然后从onClick处理程序中提交表单?

Edit: eg replace 编辑:例如替换

<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />

with

<input onkeypress="return handleEnter(this, event)" type="button" value="Submit" onclick="BG.handleSubmit(this.form, true);" />

Then maybe use a Javascript function like this (I'm not sure exactly what order you want these things to happen in): 然后也许使用这样的Javascript函数(我不确定这些事情发生的确切顺序):

BG.handleSubmit = function(formElement, fallBackToFullWindow) {
    if (!formValidator())
        return;
    BG.startChatWithIssueForm(formElement, fallBackToFullWindow);
    formElement.submit();
    return false;
}

Edit: Your validation function should probably return false if it finds something invalid. 编辑:如果发现无效,您的验证函数可能应该返回false。

function formValidator(){
    // Make quick references to our fields
    var issueid = document.getElementById('issueid');
    var username = document.getElementById('username');
    var userid = document.getElementById('userid');
    var issuedesc = document.getElementById('issuedesc');

    var valid = true;

    // Check each input in the order that it appears in the form

    if(!madeSelection(issueid, "Please choose an issue"))
        valid = false;

    if(!notEmpty(username, "Please enter your name"))
        valid = false;

    if(!isAlphanumeric(username, "Numbers and Letters Only for name"))
        valid = false;

    if(!notEmpty(userid, "Please enter your user ID"))
        valid = false;

    if(!isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
        valid = false;

    if(!notEmpty(issuedesc, "Please type a description of your problem"))
        valid = false;

    return valid;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM