0

I have a div like this in my view, keep in mind this is inside of a @foreach loop in my razor view:

<div class="testClass">
    <input type="text" class="tempLabel" /> 
                    <input type="button" data-value=@(item.ID) class="testButton3" value="Test Alert" />
</div>

This javascript works:

$(".testButton3").click(function () {    
     alert($(this).attr('data-value'));                
        });

what I want to do is get the value of the textbox inside of my tempClass class when I click the above button. I tried this but it does not work:

$(".testButton3").click(function () {    
         alert($(".tempLabel").($(this).val()));               
            });

Is this possible? Perhaps it is not possible to get the value of the textbox inside a foreach loop....

1
  • Why was this question downvoted? Commented Jul 14, 2016 at 13:45

1 Answer 1

1

They might be multiple elements created by foreach. you can try .prev() method of jquery to reach exact textbox like below.

$(".testButton3").click(function () {    
     alert($(this).prev(".tempLabel").val();                
        });
Sign up to request clarification or add additional context in comments.

4 Comments

You missed a parenthesis but this worked great! Did not know about the .prev method (or the .next for that matter). Great idea!
Welcome buddy .. That was a typo :)
Interesting to note that the two elements need to be inside of a class (testClass in this example) for this to work.
they must be at same level in hierarchy not under same class :)

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.