JR Agliam
JR Agliam

Reputation: 5

How to select an id through a class when you have multiple elements in the same page that have same class

I have this data Table in which I assigned the id of the rows of the table to a link, essentially having a unique id for each link. I also assigned a class to each link.

What i want to achieve is essentially when i click the button i can assign the value of the id to a textbox by selecting the id through the class.

This is the link that I assigned the class and id to. It is repeated throughout the data table for each item in the table. I run this link in a ajax method in a controller which is why there are pluses in the id as it is a string in the controller.

<a href='{0}' data-toggle='modal' data-target='#DivAppendToPartialView' id='"+item.mobileNumber+"' class='messageBtn'>

This is the function for assigning to the textbox

 $(".messageBtn").click(function () {
        var mobileNumberId = $(".messageBtn").attr("id");
        $("#mobileTxtBox").val(mobileNumberId);
    })

Upvotes: 0

Views: 63

Answers (3)

stijn nel
stijn nel

Reputation: 51

$(".messageBtn").click(function () {
        var data = $(this).attr("id");
        $("#mobileTxtBox").val(data);
    })

Try with $(this), it selects the current 'clicked' button. if you use $('.messageBtn) to save in the var , you save all elements with that class.

Upvotes: 3

Alexander
Alexander

Reputation: 4527

Use val() method for inputs and text() or html() method for another elements.

$(".messageBtn").click(function () {
     var mobileNumberId = $(".messageBtn").attr("id");
     $("#mobileTxtBox").val(mobileNumberId);
     $("#mobileP").text(mobileNumberId);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="mobileP">&nbsp;</p>
<p>
    <input id="mobileTxtBox" type="text">
</p>
<a href='#' data-toggle='modal' data-target='#DivAppendToPartialView' id='"+item.mobileNumber+"' class='messageBtn'>Click ME</a>

Upvotes: 0

sumit chauhan
sumit chauhan

Reputation: 1300

$(".messageBtn").click(function () {
        var mobileNumberId = $(".messageBtn").attr("id");
        console.log(mobileNumberId);
        $("#mobileTxtBox").val(mobileNumberId.substring(mobileNumberId.indexOf('+')+1, mobileNumberId.lastIndexOf('+')));
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle='modal' data-target='#DivAppendToPartialView' id='"+item.mobileNumber+"' class='messageBtn'>click</a>
<input type="text" id="mobileTxtBox">

assigned the exact value of id by removing the + which is coming in your id

Upvotes: 0

Related Questions