Отправка формы с помощью onclick и onsubmit

#javascript #forms #function #onclick #onsubmit

#javascript #формы #функция #onclick #onsubmit

Вопрос:

Я пытаюсь настроить систему «Нажмите, чтобы пообщаться» для моей компании. Для этого требуется форма, которая фиксирует некоторую информацию от пользователя. Когда вы отправляете форму, предполагается, что она откроет новое окно с помощью скрипта в файле .js.

Я попытался добавить некоторую проверку, которая привела как к onclick, так и к функции onsubmit. Когда форма отправляется без проверки, она открывает новое окно с помощью BG.startChatWithIssueForm(this.form, true); функции. Но по какой-то причине, когда я включаю onsubmit для проверки, onclick полностью игнорирует его.

Я пытался вложить BG.startChatWithIssueForm(this.form, true); функцию в разные места formValidator() функции, но это все равно приводит к появлению запроса на загрузку файла вместо открытия нового окна.

Не уверен, что я делаю неправильно. Я изучал это в течение нескольких недель и, похоже, ничего не могу придумать. Javascript определенно не моя сильная сторона, поэтому буду признателен за любую помощь.

Смотрите код ниже:

JS:

 function Bomgar() {
    var _host = "";
    var _protoRe = /^(http|https):///;
    
    /* private */
    function _createURL(params, forPopup) {
        var qStr = "";
        for (var k in params) {
           qStr  = "amp;" encodeURIComponent(k) "=" encodeURIComponent(params[k]);
        }
        qStr = "popup=" (forPopup ? "1" : "0")   "amp;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 amp;amp; !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 amp;amp; e.value amp;amp; e.type amp;amp; e.type != 'button' amp;amp; 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-код:

 <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>
  

Комментарии:

1. Исправлен отступ кода. Это мой 2c, пусть кто-нибудь другой ответит на ваш вопрос.

Ответ №1:

Вы пробовали заменить кнопку отправки обычной кнопкой, выполнить проверку в обработчике onClick, а затем отправить форму из обработчика onClick?

Редактировать: например, заменить

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

с помощью

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

Тогда, возможно, используйте функцию Javascript, подобную этой (я не уверен точно, в каком порядке вы хотите, чтобы это происходило):

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

Редактировать: ваша функция проверки, вероятно, должна возвращать 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;
}
  

Комментарии:

1. Есть ли шанс, что вы могли бы привести мне пример? Я не думаю, что я это еще пробовал.

2. Это действительно близко. На самом деле теперь функция BG.startChatWithIssueForm открывается корректно, но она все равно выполняется независимо от того, проверяется форма или нет. Есть идеи о том, как сделать это условием проверки?

3. Если вы хотите предупреждать пользователя только об одном недопустимом поле для каждой отправки формы, вы можете изменить эти valid = false; строки на return false; и изменить return valid; в конце на return true;

4. Это позаботилось об этом! Большое спасибо за вашу помощь!