Search code examples
javascriptjqueryasp.net-mvc-4keypress

jquery keypress function with multiple input with same id


hello everybody ı have a question this is my jquery code

<script type="text/javascript">
    $('#com').keypress(function (event) {
        var comm = $(this).val();

        var keycode = (event.keycode ? event.keycode : event.which);
        if (keycode == 13) {
            var comm = $("#com").val();
            alert(comm);
            var hidid = $("#hidid").val();
            alert(hidid);

            $.ajax({
                cache: false,
                type: "POST",
                url: "/Home/postComment",
                datatype: "json",
                data: { comment: comm, hidid: hidid },
                error: function () {
                    alert("error ");
                },
                success: function () {
                    window.location.href = "/Home/Index";
                }
            });
        }
        event.stopPropagation();
    });
</script>

and I am calling it in controller like this

[HttpPost]
    public JsonResult postComment(string comment,int hidid)
    {
        Repository<whichOne> _rwo = new Repository<whichOne>();
        Repository<Comment> _rc = new Repository<Comment>();

        int _userId = Convert.ToInt32(Session["_userId"]);

        Comment _comment = new Comment
        {
            userId = _userId,
            comment = comment,
            createDate = DateTime.Now,
            isValid = true,
            whichOneId = hidid,
        };

        _rc.Add(_comment);
        _rc.Save();

        return Json(new { success = true });
    }

and I have data which are coming from database and I am trying to get id's of my datas and take comment to post from input

@foreach (var item in Model._mywhichOneHelper)
                {
          @Html.Hidden("hidid",@item.id)
          <input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">}

however I can only reach first data when I hit enter after writing something. Keypress is not working for other datas what can I do for this?

enter image description here

as you see when I write and click enter to first input it works but when I tried this for other datas nothing happens. thank you very much.


Solution

  • The problem here is your jQuery selector is only finding the first element, since it only expects one element to have an id (ids are supposed to be unique).

    It is not a good practice to have multiple elements with the same id - this is part of your problem. If you can redesign your markup so that the elements have unique id's, but share a class (such as class="com") then you can easily write jQuery selectors to find them. In this case, there is still a workaround, you can use a jQuery selector like so: [id=com] instead of #com and this will find all the matching elements instead of only looking for one (expected) element with that unique id.

    Also note I had to change your event handler so that it did not use another jQuery selector, but rather passed the value $self into the closure so that it held the correct unique instance instead of always finding the first.

    $(function() {
      $("[id=com]").keypress(function(event) {
          var $self = $(this);
          var comm = $self.val();
    
          var keycode = (event.keycode ? event.keycode : event.which);
          if (keycode == 13) {
            var comm = $self.val();
            alert(comm);
            event.stopPropagation();
          }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
    <br />
    <input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
    <br />
    <input type="text" class="pull-left input-sm form-control" id="com" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
    <br />

    Even better would be to use unique id's, and select via class, like so:

    $(function() {
      $(".com").keypress(function(event) {
        var $self = $(this);
        var comm = $self.val();
    
        var keycode = (event.keycode ? event.keycode : event.which);
        if (keycode == 13) {
          var comm = $self.val();
          alert(comm);
          event.stopPropagation();
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <input type="text" class="pull-left input-sm form-control com" id="com1" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
    <br />
    <input type="text" class="pull-left input-sm form-control com" id="com2" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
    <br />
    <input type="text" class="pull-left input-sm form-control com" id="com3" name="comments" style="border-radius: 12px;" placeholder="Your Comments...">
    <br />