Detener el disparo de onclick cuando onclientclick es false?
¿Es posible usar la propiedad onclientclick
de un botón para hacer una comprobación de cliente? Si la comprobación devuelve true
, entonces activa el evento onclick
. Si la comprobación del lado del cliente devuelve false
, no active el evento onclick
.
¿Es eso posible?
ACTUALIZACIÓN:
Estos 2 funcionan:
Stops the form from submitting:
OnClientClick="return false;"
Allows the form to submit:
OnClientClick="return true;"
Los siguientes 2 no funcionan:
// in js script tag
function mycheck() {
return false;
}
// in asp:button tag
OnClientClick="return mycheck();"
// in js script tag
function mycheck() {
return true;
}
// in asp:button tag
OnClientClick="return mycheck();"
Envía el formulario ambas veces.
¿Por qué es eso?
5 answers
Desea agregar return
dentro de OnClientClick después de llamar a una función. De lo contrario, el botón se publicará incluso si la función devuelve false.
<asp:button ID="Button1" runat="server" OnClick="Button1_Click"
OnClientClick="return checkValidation()" Text="Submit" />
<script type="text/javascript">
function checkValidation() {
return confirm('Everything ok?');
}
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-09 23:05:32
Claro. Si utilizas return false
dentro de tu OnClientClick
evitará que ocurra cualquier navegación. Así que tu código se vería como:
<asp:LinkButton runat="server" OnClientClick="if(!ValidatePage()) { return false;}" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-02 14:52:32
Sí puede, En OnClientClick función llamada use preventDefault()
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
e.preventDefault();
}
}
O
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
return false;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-02 14:50:35
En la página del servidor crea el botón :
var button1 = new Button();
button1.ServerClick += new EventHandler(button1_ServerClick);
button1.OnClientClick = SetJsForSaveBtn();
button1.Attributes.Add("UseSubmitBehavior", "false");
panel.Controls.Add(button1 );
/ / Contiene el código del servidor
private void saveBtn_ServerClick(object sender, EventArgs e)
{
//do something if ClientClick returns true
}
/ / Contiene el código JS para la página
LiteralControl js = new LiteralControl();
panel.Controls.Add(js);
js.Text =@"<script type='text/javascript'>
$(document).ready(function(){
function CheckValidationOnClient(){
if(!ValidatePage()){
return false;
}
else{
return true;
}
};
});
</script> ";
private string SetJsForSaveBtn()
{
var jsfunc = @" return CheckValidationOnClient()";
return jsfunc ;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 15:41:08
Me encontré con este tema también. No le gustaba tener que poner el OnClientClick = return false en cada linkbutton. Con una página simple, es más fácil usar un ancla y evitar que asp llene el href por usted.
Sin embargo, esto no siempre es posible. Así que una conclusión simple es heredar el LinkButton y agregar una variable como AutoPostBack. si false, entonces simplemente anule la salida con el html o agregue el OnClientClick in. Realmente no me gustan las etiquetas en línea.
namespace My.WebControls {
[ToolboxData("<{0}:LinkButton runat=server ID=btn></{0}:LinkButton>"), ParseChildren(true), ToolboxItem(true)]
public class LinkButton : System.Web.UI.WebControls.LinkButton {
private bool _postback = true;
[Bindable(true), Category("Behavior"), DefaultValue(true), Description("Gets or Sets the postback click behavior")]
public bool AutoPostBack { get { return _postback; } set { _postback = value; } }
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
if(!AutoPostBack){
this.OnClientClick = "return false";
}
base.Render(writer);
}
}
}
Muchos los atributos deben ser manejados en un ViewState, pero en este caso creo que estamos bien;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-11 18:42:13