简体   繁体   中英

Kendo button calling a javascript function on click

I have a HTML input like this:

<input type="submit" name="saveForm" value="Save" onclick="return validateForm()"/>

here's the validateForm function called when the button is clicked:

function validateForm() {
    if (someErrorCondition) {
        alert("error");
        return false;
    }
    reallySubmitForm();
}

I want to replace this button with a Kendo Button, and I'm doing like this:

@(Html.Kendo().Button()
    .Name("save")
    .HtmlAttributes( new {type = "submit"})
    .ImageUrl(Url.Content("~/Images/save.png"))
    .Events(e => e.Click("return validateForm"))    <---------  here's the problem
    .Content("Save")
)

The problem is that, if I have

.Events(e => e.Click("return validateForm"))

the button isn't rendered correctly: the "return" word is messing it up. If I have this

.Events(e => e.Click("validateForm"))

it's rendered correctly and the function is called. However, when clicked, the button submits the form anyway, without caring with validation.

How can I achieve the former behaviour with this Kendo Button?

Try to use e.preventDefault() instead of returning false in order to stop the submit event. That's the recommended way anyway. :)

I have tried with only " return " and it works. But using e.preventDefault() does not do the trick for me.

Try Following code:

@(Html.Kendo().Button()
.Name("save")
.HtmlAttributes( new {type = "submit"})
.ImageUrl(Url.Content("~/Images/save.png"))
.Events(e => e.Click("validateForm"))
.Content("Save"))

function validateForm(e) {
  if (someErrorCondition) {
    alert("error");
    e.preventDefault();
  }
 else {
      reallySubmitForm();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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