2012-04-10 6 views
52

Sto tentando di impedire al modulo di inoltrare se una convalida non riesce. Ho provato a seguire questo previous post ma non funziona per me. Cosa mi manca?Arresta il modulo dall'invio, utilizzando Jquery

<input id="saveButton" type="submit" value="Save" /> 
<input id="cancelButton" type="button" value="Cancel" /> 
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> 
<script type="text/javascript"> 

    $(document).ready(function() { 
     $("form").submit(function (e) { 
      $.ajax({ 
       url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
       data: { id: '@Model.ClientId' }, 
       success: function (data) { 
        showMsg(data, e); 
       }, 
       cache: false 
      }); 
     }); 
    }); 
    $("#cancelButton").click(function() { 
     window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })'; 
    }); 
    $("[type=text]").focus(function() { 
     $(this).select(); 
    }); 
    function showMsg(hasCurrentJob, sender) { 
     if (hasCurrentJob == "True") { 
      alert("The current clients has a job in progress. No changes can be saved until current job completes"); 
      if (sender != null) { 
       sender.preventDefault(); 
      } 
      return false; 
     } 
    } 

</script> 
+0

che funzionano nel codice sopra sta arrestando il modulo da presentare? Cosa sta facendo la funzione showMsg? Perché stai usando sender.preventDefault(); L'argomento del mittente è un evento? preventDefault() è usato per fermare il normale comportamento di un elemento su qualche evento come il clic ecc. – DG3

+0

si riferisce a e: evento –

risposta

100

Ancora, AJAX è asincrono. Quindi la funzione showMsg verrà chiamata solo dopo la risposta di successo dal server .. e l'evento di invio del modulo non attenderà il successo di AJAX.

Spostare e.preventDefault(); come prima riga nel gestore di clic.

$("form").submit(function (e) { 
     e.preventDefault(); // this will prevent from submitting the form. 
     ... 

Vedi di seguito il codice,

voglio che sia HasJobInProgress permesso == false

$(document).ready(function() { 
    $("form").submit(function (e) { 
     e.preventDefault(); //prevent default form submit 
     $.ajax({ 
      url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
      data: { id: '@Model.ClientId' }, 
      success: function (data) { 
       showMsg(data); 
      }, 
      cache: false 
     }); 
    }); 
}); 
$("#cancelButton").click(function() { 
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })'; 
}); 
$("[type=text]").focus(function() { 
    $(this).select(); 
}); 
function showMsg(hasCurrentJob) { 
    if (hasCurrentJob == "True") { 
     alert("The current clients has a job in progress. No changes can be saved until current job completes"); 
     return false; 
    } else { 
     $("form").unbind('submit').submit(); 
    } 
} 
+0

non lo impedirà in tutte le situazioni? –

+0

su quali condizioni si desidera che l'evento sia consentito. Probabilmente è necessario impedirne l'invio, quindi attendere la risposta AJAX e attivare l'invio manualmente. –

+0

Voglio che sia consentito HasJobInProgress == False –

3

provare il codice qui sotto. e.preventDefault() è stato aggiunto. Ciò rimuove l'azione evento predefinita per il modulo.

$(document).ready(function() { 
    $("form").submit(function (e) { 
     $.ajax({ 
      url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
      data: { id: '@Model.ClientId' }, 
      success: function (data) { 
       showMsg(data, e); 
      }, 
      cache: false 
     }); 
     e.preventDefault(); 
    }); 
}); 

Inoltre, lei ha detto che si voleva la forma di non inviare con la premessa di convalida, ma non vedo alcuna convalida il codice qui?

Ecco un esempio di alcune convalida aggiunto

$(document).ready(function() { 
    $("form").submit(function (e) { 
     /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */ 
    if(!$('#inputID').val()){ 
     e.preventDefault(); // This will prevent the form submission 
    } else{ 
     // In the event all validations pass. THEN process AJAX request. 
     $.ajax({ 
      url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
      data: { id: '@Model.ClientId' }, 
      success: function (data) { 
       showMsg(data, e); 
      }, 
      cache: false 
     }); 
    } 


    }); 
}); 
+0

Non sto effettivamente convalidando un campo. Questa parte dell'ajax del codice chiama un metodo che controlla se un lavoro per il client è già in corso. Non voglio consentire più processi per lo stesso client da accodare. –

+0

e.preventDefault() quindi risolverebbe il tuo problema-> – Downpour046

15

uso anche questo:

if(e.preventDefault) 
    e.preventDefault(); 
else 
    e.returnValue = false; 

Becoz e.preventDefault() non è supportato in IE (alcune versioni). In IE è e.returnValue = false

+9

nel caso tu usassi jQuery puoi tranquillamente usare 'e.preventDefault()'. jQuery si prenderà cura della compatibilità con x-browser. – staabm

+0

Cool, non sapevo che – gskema

+0

Dalla [jQuery su] (http: //api.jquery.it/on /) API: "Restituendo false da un gestore di eventi chiamerà automaticamente' event.stopPropagation() 'e' event.preventDefault() '." Continua dicendo: "Il valore A' false' può anche essere passato per il gestore come una scorciatoia per 'function() {return false;}" " – Paul

3

Un approccio diverso potrebbe essere

<script type="text/javascript"> 
    function CheckData() { 
    //you may want to check something here and based on that wanna return true and false from the   function. 
    if(MyStuffIsokay) 
    return true;//will cause form to postback to server. 
    else 
     return false;//will cause form Not to postback to server 
    } 
    </script> 
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" })) 
    { 
    ......... 
    ......... 
    ......... 
    ......... 
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/> 
    } 
Problemi correlati