Get the value of an input button

1

I have dynamically created buttons, and I wish that when you click on them you get your value to be able to interact with it.

@for (int i = 0; i < pagesMax; i++)
{
    <input type="button" value=@(i+1) class="bottom" id="id" />
}

I was trying something like this but it did not work for me:

@section scripts
{
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#id").click(function () {
                alert($("#id").attr("value"));
            });

        });

    </script>
}
    
asked by Pablo.P 25.06.2018 в 21:30
source

2 answers

0

Instead of id, assign class . id is only used when you have to identify 1 single element, class when you want to identify several:

@for (int i = 0; i < pagesMax; i++)
{
    <input type="button" value=@(i+1) class="bottom mi-input" />
}

@section scripts
{
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".mi-input").click(function () {
                alert(this.value);
            });

        });

    </script>
}

Note how this.value is used within the event. This to obtain the reference of the element that is being clicked.

    
answered by 25.06.2018 в 21:54
0

You are putting all the buttons the same id so when capturing the value is lost because there are several controls with the same id. Try trying to differentiate the id from the buttons id="id+i "

    
answered by 25.06.2018 в 22:01