I have two different input fields with their own respective submit buttons and I want the user to be able to enter their input into either of the text boxes and then hit the enter key and have the same effect as if they were to click on the submit button. Currently, typing something into the text box and hitting the enter key does nothing. I’m using HTML and JavaScript and ASP .NET MVC3. My code looks like this:
The HTML
<table>
<tr>
<td><span class="labelText">Text1</span></td> <td><input id="text1" type="text" placeholder="Enter Text1"/> </td> <td style="width: 110px; text-align: left; margin-left: 5px"><button class="medium awesome blue" id="sendText1">Send Text1</button></td>
</tr>
<tr>
<td> <span class="labelText">Text2</span> </td> <td><input id="text2" type="text" placeholder="Enter Text2"/> </td> <td style="width: 110px; text-align: left; margin-left: 5px"> <button class="medium awesome blue" id="sendText2">Send Text2</button> </td>
</tr>
The JavaScript
$('#sendText1').click(function () {
$('#text2').val("");
var text1 = $("#text1").val();
$('#loadingUsageInfo').css({ 'visibility': 'visible' });
if (text1 == "" || text1 == 'Enter Text1') {
alert('Enter Text First');
return;
}
$.ajax({
url: '@Url.Action("ShowResult1", "Folder")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ input1: text1 }),
traditional: true,
success: function (result) {
$('#info').html(result);
}
});
});
$('#sendText2').click(function () {
$('#text2').val("");
var text2 = $("#text2").val();
$('#loadingUsageInfo').css({ 'visibility': 'visible' });
if (text2 == "" || text2 == 'Enter Text2') {
alert('Enter Text First');
return;
}
$.ajax({
url: '@Url.Action("ShowResult2", "Folder")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ input2: text2 }),
traditional: true,
success: function (result) {
$('#info').html(result);
}
});
});
Thanks in advance!
Add this below your js code
Trigger – Executes all handlers and behaviors attached to the matched elements for the given event type.
So we’re binding both text inputs on keypress and calling all bindings for the buttons.
Also see how that works on the jsFiddle