2

Currently, I am passing a list of object from controller to a view, and generate labels by the object's name.

What I am trying to do is to generate a jQuery function that will Dynamically create functions (toggle a form with relative lable id) for each label after being clicked.

The jQuery function is not working, I could not output the corrent jQuery function in the webpage...... Could you give me soem hints?

<table>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.Label(item.productName, new { @id = item.productId})
            </td>
        </tr>    
    }
</table>


<script type="text/javascript">
    $(document).ready(function () {
        @foreach (var item in Model)
    {
        $(@item.productId).click)(function({
            //do something
       }));
    }

    });
</script>

Thanks very much!

2
  • 1
    your JS syntax is wrong, for starters. $('@item.productId').on('click', function() {}); is more what you want, however a cheaper and faster way is to give all those labels a class name, and only have one click handler; ie $('.product_lbl').on('click', function() { /* Do something for whichever label was clicked */ }); Commented Jul 22, 2013 at 1:58
  • Also, $('#idGoesHere') would help. Commented Jul 22, 2013 at 1:59

1 Answer 1

2

your JS syntax is wrong, for starters. What you want to do is to give all those labels a class name (such as product_lbl) or a data attribute (if you don't like semantic class names) such as product-lbl. This way you don't have to do a second loop to add click event handlers. You'll only need one, like so:

$('.product_lbl').on(
    'click', 
    function() { /* Do something for whichever label was clicked */ }
);

OR

$('[product-lbl]').on(
    'click', 
    function() { /* Do something for whichever label was clicked */ }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.