1

hey guys im trying to get the value of the text box before the button, suppose that the buttons and text box can be increment thats why im using one .click function only. im new in jquery thats why still trying the posible way to get it. this is what I tried.

<html>
<head>
    <style type="text/css">
        #container{
            width:500px;
            height:300px;
            background-color:#F9F9F9;;
        }

    </style>
    <script type="text/javascript" src="jquery-1.8.3.min.js"> </script>
    <script type="text/javascript">     

        $(document).ready(function(){ 
            $('#trigger').click(function (){

            var prev =  $(this).prev('input[type=text]');
            var val = $(prev).val();
            alert(val);
            });

        });
    </script>
</head>


<body>
    <table>
        <tr>
            <td><input type="text"></td>
            <td><input type="button" id="trigger" value="submit"></td>
        </tr>
        <tr>
            <td><input type="text"></td>
            <td><input type="button" id="trigger" value="submit"></td>
        </tr>
        <tr>
            <td><input type="text"></td>
            <td><input type="button" id="trigger" value="submit"></td>
        </tr>
        <tr>
            <td><input type="text"></td>
            <td><input type="button" id="trigger" value="submit"></td>
        </tr>
        <tr>
            <td><input type="text"></td>
            <td><input type="button" id="trigger" value="submit"></td>
        </tr>
    </table>


</body>
</html>
1
  • 1
    Multiple elements with the same ID isn't going to work with your ID selector
    – wirey00
    Nov 21, 2012 at 15:51

1 Answer 1

1

You need to assign a common class as html elements are supposed to have unique ids.

Live Demo

$('.myclass').click(function() {

    var prev = $(this).parent().prev().find('input[type=text]');
    var val = $(prev).val();
    alert(val);
});​

If you want to do it with id as you can not use class as you have in question then you can use id select this way.

Live Demo

$('[id=trigger]').click(function() {
    var prev = $(this).parent().prev().find('input[type=text]');
    var val = $(prev).val();
    alert(val);
});​
2
  • don't forget to traverse to the parent td first
    – wirey00
    Nov 21, 2012 at 15:51
  • i forget about the td. now i know that traversing is very important in jquery DOM manipulation.
    – Aoi
    Nov 22, 2012 at 0:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.