Jquery Click function Function get parameter from another form

I have code like this

    <!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
        $("#btn").click(function(){
            var vname = $("#name").val();
            var vgender = $("#gender").val();
            var vstage =$("#stage").val();
            alert(vname+" Using btn");
    });
    $("#rqst").click(function(){
            var vname = $("#name").val();
            var vgender = $("#gender").val();
            var vstage =$("#stage").val();
            alert(vname+" Using rqst");
    });
});
</script>
</head>
<body>
<div id="main">

<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Gender</label>
<input type="text" name="gender" id="gender" placeholder="Gender"/></div>
<input type="hidden" name="stage" id="stage" value="0" /></div>

</form>
<button id="btn">Send Data</button>
</div>
<div id="result"></div

<br>


Request

<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Gender</label>
<input type="text" name="gender" id="gender" placeholder="Gender"/></div>
<input type="hidden" name="stage" id="stage" value="0" /></div>

</form>
<button id="rqst">Send Data</button>
</div>
<div id="result"></div

</body>
</html>

      

Trying to get value from another form but every parameter has the same name, submit 1st form (fill in name field with Josh), I got correct Ie result (Josh Using Btn) but when submitting 2nd form (enter field name with Ipul), I still got the same value from 1st type as "Ipul Using rqst", Why does jquery just get value from 1st form? Not the second form? Can anyone help me? http://jsfiddle.net/wf6wo0g7/

+3


source to share


2 answers


Yes ID in html must be unique, in this case you can use class. See This

$(document).ready(function(){
        $("#btn").click(function(){
            var vname = $("#form1 .name").val();
            var vgender = $("#form1 .gender").val();
            var vstage =$("#form1 .stage").val();
            alert(vname+" Using btn");
    });
    $("#rqst").click(function(){
            var vname = $("#form2 .name").val();
            var vgender = $("#form2 .gender").val();
            var vstage =$("#form2 .stage").val();
            alert(vname+" Using rqst");
    });
});

      



Fiddle

+1


source


ID - Must be unique in HTML.

DEMO



   $("#rqst").click(function(){
        var vname = $("#name2").val();
        var vgender = $("#gender2").val();
        var vstage =$("#stage2").val();
        alert(vname+" Using rqst");
    });

      

+1


source







All Articles