Luqman
Luqman

Reputation: 163

How to set default button in ASP.Net MVC

This is my HTML code :

@using (Html.BeginForm("Index", "EmployeeList", FormMethod.Post, new {defaultbutton = "searchBtn" }))
            {
  @Html.TextBox("SearchString", ViewBag.SearchString as string, new { @id = "SearchString", @class = "form-control", placeholder = "Search Name" })

<button type="submit" name="MyButton" value="Export" class="btn btn-sm btn-danger">

<button type="submit" name="MyButton" value="Search" id="searchBtn" class="btn btn-sm btn-warning">
}

According to my page design I have to write "Export" button's html code before "Search" button.

While I press enter after filling search text 'export' button gets clicked, instead of that I need 'Search' button clicked.

Upvotes: 7

Views: 6992

Answers (2)

Brian
Brian

Reputation: 25824

If you'd prefer to have a defaultbutton on any form, it's easy enough to add one. Below is a trivial example. Note that I required the defaultbutton to be a selector rather than an id, but it's easy enough to require prefix a hash if you prefer it to accept ids.

Also note that using the name "defaultbutton" runs the risk of conflicting with someone else's code (and the lack of a data- prefix means it might conflict with a possible "defaultbutton" feature added to a future html spec).

Below is a simple example. Changing closest to check for a defaultbutton attribute will allow a single form to have different default buttons for different components.

//Load this script on any pages that need to support default buttons.
$(document).bind('keydown', function(e) {
    if (e.which === 13) {
        var button = $(e.target);
        if (button.attr('type') != 'text') {
            return true;
        }
        var parentform = $(e.target).closest('form');
        var selector = parentform.attr('defaultbutton');
        var targetbutton = parentform.find(selector);
        if(targetbutton.length > 0) {
            targetbutton.trigger('click');
            return false;
        }
        return true;
    }
});
<!-- Example usage.  Just add a defaultbutton attribute to your form-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form defaultbutton='#candy'>
  <input type='text' id='text' placeholder='text' />          <br /><br />
  <input type='submit' value='toys'  id='toys' onclick='alert("Toys") ;return false;' />
  <br /><br />
  <input type='submit' value='candy' id='candy' onclick='alert("Candy");return false;' />
  <br /><br />
  <input type='submit' value='money' id='money' onclick='alert("Money");return false;' />
  <br /><br />
</form>

Upvotes: 0

Murad
Murad

Reputation: 543

You can handle kewdown event :

 <script type="text/javascript">
$(document).bind('keydown', function (e) {
    if (e.which === 13) { // return
        $('#searchBtn').trigger('click');
    }
});
  </script>

Upvotes: 13

Related Questions