Frame
Frame

Reputation: 95

How to select 1st row from table using JQuery

I want to select first row from table data when page first loads. My $('#Home').on('click', '#tblStyles .HomeSelect', function () { does not hit. Please suggest me here I am going wrong.

Report View

<ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" href="#Home">Home</a></li>          
        </ul>
        <div class="tab-content">
            <div id="Home" class="tab-pane fade in active">
                @Html.Partial("~/Views/Home/Home.cshtml", Model.clsHome)
            </div>

        </div>

Home View

<div class="panel panel-default">
        <table id="tblStyles" class="table table-hover">
            <tr class="no-hover" style="border-top:hidden">
                <th>
                    @Html.DisplayNameFor(m => m.ProductName)
                </th>            

            </tr>

            @foreach (var item in Model)
            {
                <tr class="HomeSelect" data-productcode="@item.ProductCode">

                    <td align="right">
                        @Html.DisplayFor(modelItem => item.ProductCode)
                    </td>

                </tr>
            }
        </table>
    </div>
            @using (Html.BeginForm("Home", "Home", FormMethod.Post, new { id = "Form" }))
        {
            <div id="mypartial"> </div>

        }

Scripts

   $(document).ready(function () {             
            $('#Home').find('#tblStyles tr:first').addClass("selected").click();              
        });

     $('#Home').on('click', '#tblStyles .HomeSelect', function () {

            var id = $(this).data('productcode');

Upvotes: 0

Views: 2081

Answers (1)

Shyju
Shyju

Reputation: 218722

Your jQuery selector $('#Home').find('#tblStyles tr:first') will give you the first table row. That does not mean that it is the first table row with the CSS class HomeSelect. Infact your selector will give you the first row, which is the table header (Where you are calling the DisplayNameFor helper method.

Your click event handler is wired up for elements with HomeSelect CSS Class. So make sure when you invoke the first tr's click event, you follow the same pattern.

Make sure you are invoking the click event using JavaScript after wiring up the click event handler. I suggest you wire up any event handlers inside the jquery ready event.

$(function () {
    $('#Home').on('click', '#tblStyles .HomeSelect', function () {
        var id = $(this).data('productcode');
        alert(id);
    });

    // Invoke click on the first row with "HomeSelect" CSS class
    // The header row does not have that class.
    $('#Home').find('#tblStyles tr.HomeSelect:first').click();  
});

Upvotes: 2

Related Questions