Reputation: 23
i'm new in jquery ajax and i need some help.
This is my basic html.
<form id="replayForm1">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(1)">Click Me</button>
</form>
<form id="replayForm2">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(2)">Click Me</button>
</form>
This is my jquery:
<script>
function getmsg(formID) {
var formName = '#replayForm' + formID;
$(formName).submit(function (e) {
e.preventDefault();
var msg_id = $('input[name=msg_id]').val();
var msg_replay = $('input[name=msg_replay]').val();
alert(msg_id + msg_replay);
});
}
</script>
My problem is, when i fill the second form i get empty value. First form don't have problem it return value and don't have problem. How to deal this problem? i try make this form unique to easy submit form just using 1 function.
Upvotes: 2
Views: 56
Reputation: 46660
jQuery will look for the first instance which it finds of the inputs, so use the formName to match the correct ones.
You should also remove the previous event or you will get multiple alerts after the second click on the same button.
function getmsg(formID) {
var formName = '#replayForm' + formID;
$(formName).off('submit').on('submit', function (e) {
e.preventDefault();
var msg_id = $(formName + ' input[name=msg_id]').val();
var msg_replay = $(formName + ' input[name=msg_replay]').val();
alert(msg_id + msg_replay);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="replayForm1">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(1)">Click Me</button>
</form>
<form id="replayForm2">
msg_id:
<input type="text" name="msg_id">
<br>
msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(2)">Click Me</button>
</form>
Upvotes: 2
Reputation: 50346
In both the case the name
is same. Change the name & pass those values to getmsg
function
function getmsg(formID, inputName, msgReplyName) {
var formName = '#replayForm' + formID;
$(formName).submit(function(e) {
e.preventDefault();
var msg_id = $('input[name=' + inputName + ']').val();
var msg_replay = $('input[name=' + msgReplyName + ']').val();
alert(msg_id + ' ' + msg_replay);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="replayForm1">
msg_id:
<input type="text" name="msg_id">
<br> msg_replay
<input type="text" name="msg_replay">
<button onClick="getmsg(1,'msg_id','msg_replay')">Click Me</button>
</form>
<form id="replayForm2">
msg_id:
<input type="text" name="msg_id_2">
<br> msg_replay
<input type="text" name="msg_replay_2">
<button onClick="getmsg(2,'msg_id_2','msg_replay_2')">Click Me</button>
</form>
Upvotes: 1