maciejka
maciejka

Reputation: 948

Detect which button was clicked in html table

I have the html table with columns where each of them contains button and dropdownlists.

<table class="table" border="1">
   <thead>
      <tr>
         <td>
            <p>
               Terminy
            </p>
            <br/>
            <p>
               Warsztat
            </p>
            <p>
               Liczba uczestników
            </p>
         </td>
         @foreach(DateTime date in Model.AssignedAttractions.Keys.ToList())
         {
         <td>
            <p>
               @date.ToShortDateString()
            </p>
            <p>
               @(ReservationAttractions.Days[date.DayOfWeek.ToString()])
            </p>
            <p>
               @Html.DropDownList("AttractionsAvaiableAttractions", Model.AvaiableAttractions)
            </p>
            <p>
               @Html.DropDownList("AttractionsQuantityParticipants", Model.ParticipantsQuantity)
            </p>
            <p>
               <input type="button" value="Wybierz" />
            </p>
         </td>
         }
      </tr>
   </thead>
</table>

The number of columns can be different. How can I get using javascript which button was clicked and get selected item from dropdownlists which are in columns where the clicked button is located?

Used model to fill table.

public class ReservationAttractions
    {

        public List<SelectListItem> AvaiableAttractions { get; set; }

        public List<SelectListItem> ParticipantsQuantity { get; set; }

        public Dictionary<DateTime,List<string>> AssignedAttractions { get; set; }

    }

Upvotes: 1

Views: 1451

Answers (5)

adiga
adiga

Reputation: 35259

You can add a click handler for the button. And then get the value selected in the dropdowns like this:

$(document).ready(function () {
    $("thead td input[type='button']").click(function () {
        // gets the td for which button was clicked
        var $td = $(this).closest("td"); 
        // gets the selected Attraction for that particular td
        var selectedAttractions = $td.find("[name^='AttractionsAvaiable']").val();
        // gets the selected Participants for that td
        var selectedParticipants = $td.find("[name^='AttractionsQuantity']").val();
    });
});

MVC adds name attributes to form elements. And when there is a loop it appends extra things to differentialte the elements. The [name^='AttractionsAvaiableAttractions'] is a Attribute Starts With Selector. This will return the select element. From that, you can get the .val() to get the value selected in the dropdwons.

Upvotes: 2

gaetanoM
gaetanoM

Reputation: 42054

How can I get using javascript which button was clicked and get selected item from dropdownlists which are in columns where the clicked button is located?

You can traverse up the dom till the closest ancestor cell and so you can find all dropdown of your interest.

how to differ which button was clicked?

You don't need to differ. You can only consider all dropdown are children of the same cell.

Hence, the elements are:

 $(this).closest('td').find('select option:selected')

In javascript:

this.closest('td').querySelectorAll('select')

$('[type="button"]').on('click', function(e) {
    var selectedValues = $(this).closest('td').find('select option:selected').map(function(idx, ele) {
        return this.textContent;
    }).get();
    console.log('jQuery: ' + selectedValues);
})

document.querySelectorAll('[type="button"]').forEach(function(ele, idx) {
    ele.addEventListener('click', function(e) {
        var selectedValues = Array.from(this.closest('td').querySelectorAll('select')).map(function(ele, idx) {
            return ele.options[ele.selectedIndex].textContent;
        });
        console.log('javascript: ' + selectedValues);
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
    <thead>
    <tr>
        <td>
            <p>
                Terminy
            </p>
            <br/>
            <p>
                Warsztat
            </p>
            <p>
                Liczba uczestników
            </p>
        </td>
        <td>
            <p>
                09/09/2017
            </p>
            <p>
                10
            </p>
            <p>
                <select>
                    <option value="a">a</option>
                    <option value="b">b</option>
                    <option value="c">c</option>
                    <option value="d">d</option>
                </select>
            </p>
            <p>
                <select>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                </select>
            </p>
            <p>
                <input type="button" value="Wybierz">
            </p>
        </td>
    </tr>
    </thead>
</table>

Upvotes: 0

VikDev
VikDev

Reputation: 121

You can try something like this in pure vanilla JS to find which row is clicked.

<button type="button" onclick="handleTblBtnClick">

To just get the id

function handleTblBtnClick() {
console.log(arguments[0].target.id);
}

To get more details like row and column number you can try this :

    function handleTblBtnClick(event) {
    console.log(event.target.id);
    console.log("Row :" + event.target.parentNode.parentNode.rowIndex + 
                "Column :" + event.target.parentNode.cellIndex);
    }

Upvotes: 0

Raj Parekh
Raj Parekh

Reputation: 94

You can bind ID to each button. So based on the button ID you can make Ajax request that will populate the drop down list based on the value passed.

Upvotes: 0

Soviut
Soviut

Reputation: 91742

You can pass the index or model id each button click handler.

<button type="button" onclick="onClick(@id)">

Then you can use that ID in your click handler to determine which model was clicked.

function onClick(id) {
  console.log(id + ' was clicked');
}

Upvotes: 0

Related Questions