CSharper
CSharper

Reputation: 5580

Razor ForEach, Get value on click

I'm using razor syntax to generate a list of labels.

@foreach(var label in Model.Labels)
{
   @Html.Label(label, new  { id = "??" }) <br /> <br />
}

It renders like this:

item1

item2

What must I do in Jquery to be able to alert the name of the label that was clicked?

If I give it a static Id, the click event only fires on the first element which is because there is multiple labels with the same ID.

Upvotes: 0

Views: 2562

Answers (5)

Ren
Ren

Reputation: 1503

If you have a div wrapping all your labels, then you can use jquery to do something like the below.

Here is the fiddle. Hope this helps.

$(document).ready(function() {
    $('#labelContainer').children().on("click", function(){
                        alert($(this).text());                    
                        }); 
});


<div id="labelContainer">
    <label>test1</label>
    <label>test2</label>
    <label>test3</label>
</div>

Upvotes: 1

Uptown Apps
Uptown Apps

Reputation: 707

Option 1, use data-* Razor:

@foreach(var label in Model.Labels)
{
   @Html.Label(label, new  { data_type = "myLableType" }) <br /> <br />
}

JavaScript:

$(document).on('click', '[data-type="myLabelType"]', function() {
    alert($(this).html());
}

Option 2, use class - class is intended to be used for CSS styling not JS but it will work:

Razor:

@foreach(var label in Model.Labels)
{
   @Html.Label(label, new  { class= "myLableType" }) <br /> <br />
}

JavaScript:

$(document).on('click', '.myLabelType', function() {
    alert($(this).html());
}

Upvotes: 0

SparoHawk
SparoHawk

Reputation: 557

You don't need an ID for each label. It all depends on your HTML structure. If your labels are nested inside another element, you can have that parent element with an ID and then use jQuery to handle the children label: $('#divWithId').children('label').click(function(){}).

Otherwise, as pointed out, you could use a class or data- property to access the labels.

Upvotes: 1

jacqijvv
jacqijvv

Reputation: 880

You don't have to concern yourself with an ID - unless you really want / need to.

You can do this in In your view:

    @foreach(var label in Model.Labels)
    {
       @Html.LabelFor(x => label, new  { @Class = "clickableLabel" }) <br /> <br />
    }

In jquery:

    $(".clickableLabel").click(function ()
    {
        alert($(this).attr("name"));
    })

By using a class, you would be able to click on multiple labels whilst using the same event.

Upvotes: 3

azurelogic
azurelogic

Reputation: 786

You could use the labels themselves as IDs.

@foreach(var label in Model.Labels)
{
   @Html.Label(label, new  { id = label }) <br /> <br />
}

If that doesn't guarantee uniqueness, add some string to the beginning or end of the id.

Upvotes: 0

Related Questions