0

in asp.net mvc view page write this razor code for create the dynamic button:

  @foreach(var item in ViewBag.MenuLists)
        {
<button id="buttons" value=@item.RecordId >اضافه کردن به سبد خرید</button>

        }


and want to when button fire show the value for user for that purpose write this java script code:

$(document).ready(function () {
            $("#buttons").click(function () {
                var fired_button = $("#buttons").val();
                alert(fired_button);
            });
        });


first dynamic button show the value,but when fire two or higher button dont show me alert,what happen?how can solve that problem?thanks.

ahbar ahbar
  • 11
  • 1
  • 5

2 Answers2

1

You can add class to your buttons, with classes you can access click event for each button, like below code

$(".btn").click(function()
{
alert("you clicked :"+ $(this).val()); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn" value="1">1 </button>
<button class="btn" value="2">2 </button>
<button class="btn" value="3"> 3</button>
Aamir Ali
  • 171
  • 3
  • 11
0

you are getting a handle on the button by id. this is fine but new dynamic buttons dont have the same ID I assume, or shouldnt. If they do you may only have an effect on the first of them [behavior not guaranteed].

another possibility is that since your buttons are loaded onto the DOM dynamically, they may not exist when the document is loaded and the .ready() function is called. You will need to perhaps add a new bit of script for each button while putting it on the page, OR, develop some iterative naming technique for the id of each of them so they can be addressed independently.

in general id should be unique to the item while classes should be unique to similar items. This is a guideline, not a rule, but there are practical reasons for it like getElementByID() compared to getElementsByClass().

I think in your case however it is that new buttons are placed on the DOM after the initialization [.click()] has run.

NappingRabbit
  • 1,888
  • 1
  • 13
  • 18