Textbox hit function on Enter button - javascript

I have a mvc3 application. and on one page i have a textbox that will allow a user to search for a client, now i am struggling with some functionality, as i am a windows form and widows phone 8 developer. i want this text box i have here to execute as i press enter, i have a button that the user can click on to search, but i know most users just click enter! i am using JavaScript to hit function!
Html for button and textbox:
<td>
<input value="Search..." id="SearchText" style="color:GrayText" onchange="SearchText" onfocus="javascript:this.value=''" onblur="javascript: if(this.value==''){this.value='Search...';}" />
<input id="searchbutton" type="button" value="Search" class="button"/>
</td>
Here is the Javascript :
<script type="text/javascript">
$('#searchbutton').click(function(){
var client = document.getElementById('SearchText').value;
var textbox = document.getElementById('SearchText');
var edittext = ", is not available!";
var result = client + edittext;
if (textbox.value == 'Search...') {
alert('Please enter a Client Name to search for ');
textbox.focus();
}
else {
alert(result);
};
});
</script>
how would i get the textbox to also trigger the function as i hit enter on the textbox!
here is how it looks on the form :
very new to this kind of coding, any help will do!
thanks!

$('#searchbutton').click(search);
$('#SearchText').keypress(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
search()
}
});
function search(){
var client = document.getElementById('SearchText').value;
var textbox = document.getElementById('SearchText');
var edittext = ", is not available!";
var result = client + edittext;
if (textbox.value == 'Search...') {
alert('Please enter a Client Name to search for ');
textbox.focus();
}
else {
alert(result);
};
}

$('#SearchText').on('keypress', function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//write your code for search here..like searchbutton on click
}
});

I dont know the exact answer to your question but you could use a tabindex
to press tab to jump to your button and then you can press enter to submit.

try this..
<input type="text" placeholder="Search" id="txtSearch" />
<input type="button" value="Search" id="btnsearch" onclick="return Search();" />
<script type="text/javascript">
$("#txtSearch").keyup(function (event) {
if (event.keyCode == 13) {
$("#btnsearch").click();
}
});
function Search(){
// do Something here.......
}
</script>

Related

Javascript | Pressing the enter button on the keyboard, the HTML button should be pressed

Pressing the enter button on the keyboard, the HTML button (id="botonCorregir") should be pressed automatically, but does nothing.
HTML:
<form id="theFormID" class="text-center">
<input autofocus id="respuestaUsuario" type="text">
<button id="botonCorregir" onclick="corregir()">Responder</button>
</form>
JAVASCRIPT:
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
</script>
<script>
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
For example if y try that, and push enter, doesn´t show alert "hello!". Why?
<script>
if (event.keyCode == 13) {
alert("hello!");
}
</script>
The usual way to do it in html/js is this one:
HTML
<form id="my-form">
<!-- creating a form, we use the on-submit event -->
<input type="text" autofocus id="respuestaUsuario" />
<button type="submit">Responder</button>
</form>
JS
// submit event runs when the user click the submit button or press enter on the input-text
document.getElementById('my-form').addEventListner('submit', evt => {
evt.preventDefault();
corregir();
});
Let me know if it's not clear enough and I'll try to explain it better.
the keyup event listener is for when you release the enter key
plus you can call the corregir function directly instead of triggering a click on the button
try :
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
});
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
also, a submit would be more addapted to this situation since the submit triggers itself on enter if an element of it's form is selected
Try to call the function direktly without clicking the button.
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}

get value of input and redirect to that url which is in the textbox

I have one input textbox and button on my page. actually what I want is --- on click of the button if the textbox is not empty then redirect to URL which is in the textbox... and it should also be redirected when we press enter key in the textbox. I need javascript function for that... I tried many things.. I am totally new...
<input type="text" name="url" id="editbox_search" />
<input type="submit" value="Submit" />
I have tried
function doKey(e) {
if (event.keyCode == 13) {
var x = document.getElementById('<%=editbox_search.ClientID%>');
var val = x.value;
if (val == "") {
return false;
}
else {
window.location = <%= Page.ResolveUrl("~/")%>+'Search/'+val;
}
return false;
}
}
Use:
window.location.replace(newUrl);
Or:
window.location.href = newUrl;

How to submit form with enter key when I have a button, not a submit

I have a form with a button submit type, and I would like it to submit when enter key is pressed. I don't know how to implement this with the JS function I call when submitting the form.
FORM:
<form name="form1">
<textarea name="msg" id="message">
</textarea>
<p id="button">
<input type="button" value="Enter" onclick="submitChat()" id="innerbutton"></p>
JS Function
function submitChat() {
var uname = document.getElementById('nameplace').innerHTML
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
var badname = uname.charAt(0);
if (msg != "" & badname != "<") {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4&&xmlhttp.status==200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','insert.php?uname='+uname+'&msg='+msg,true);
xmlhttp.send();
}
Attach keydown event with the document and call your function if Enter is pressed
$(document).on("keydown",function(e){
var keyCode = e.which || e.keyCode;
if(keyCode == 13) // enter key code
{
submitChat();
}
});
Use a real submit button and move your JavaScript from its click event to the form's submit event. Prevent the default behaviour of the form submission so that normal submission don't happen.
<form id="form1">
<textarea name="msg" id="message">
</textarea>
<p id="button">
<input type="submit" value="Enter">
</p>
and
document.getElementById("form1").addEventListener("submit", submitChat);
function submitChat(event) {
event.preventDefault();
// etc
This should work:
document.getElementById('innerbutton').onkeydown = function(e){
if(e.keyCode == 13){
// your submit function call here
}
};
keyCode 13 is Enter key.

i want alert some thing every time when i pressed enter key

every time time when i pressed the enter key in input field then it should alert some thing but facing problem in doing that here is the code.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(this.value)">
Here is the js code
<script>
function ajxsrch(str)
{
var keycod;
if(window.event)
{
keycod = str.getAscii();
}
if(keycod==13){alert("You pressed Enter");}
}
</script>
I think it is because you aren't passing e to the function and only using window.event which does not work in all browsers. Try this code instead.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)">
<script>
function ajxsrch(e)
{
e = e||event;
var keycod;
if(e)
{
keycod = e.keyCode||e.which;
}
if(keycod==13){alert("You pressed Enter");}
}
document.getElementById("input").onkeyup=ajxsrch;
</script>
Try this..
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(event)">
<script>
function ajxsrch(e)
{
if (e.which === 13) {
alert("You pressed Enter");
}
return false;
}
</script>
Pass the event object to the function call
<input type="text" class="searchfld" id='input' onkeyup="ajxsrch(event)">
Use the event object in the JS and get the key value.
function ajxsrch(ev) {
var ch = ev.keyCode || ev.which || ev.charCode; // Proper way of getting the key value
if(ch == 13) {
alert("You pressed enter");
}
}

Submitting a form with onclick and onsubmit

I'm trying to setup a 'Click to Chat' system for my company. It requires a form which captures some information from the user. When you submit the form, it's supposed to open a new window using the script in the .js file.
I tried to add some validation, which resulted in both an onclick, and an onsubmit function. When the form is subitted without the validation in place, it opens a new window using the BG.startChatWithIssueForm(this.form, true); function. But, For some reason, when I include the onsubmit for validation, the onclick ignores it completely.
I've tried nesting the BG.startChatWithIssueForm(this.form, true); function in different spots in the formValidator() function, but it still results in a file download prompt instead of opening a new window.
Not sure what I'm doing wrong. I've been researching this for weeks, and can't seem to come up with anything. Javascript is definitely not my forte, so any assistance would be greatly appreciated.
See the code below:
JS:
function Bomgar() {
var _host = "";
var _protoRe = /^(http|https):\/\//;
/* private */
function _createURL(params, forPopup) {
var qStr = "";
for (var k in params) {
qStr += "&"+encodeURIComponent(k)+"="+encodeURIComponent(params[k]);
}
qStr = "popup="+(forPopup ? "1" : "0") + "&c2cjs=1" + qStr;
return _host+"api/start_session.ns?"+qStr;
};
function _openWindow(params) {
return window.open(_createURL(params, true), 'clickToChat', 'toolbar=no,directories=no,status=no,menubar=no,resizable=yes,location=no,scrollbars=no');
};
function _redirectWindow(params) {
window.location.href = _createURL(params, false);
};
function _startChat(params, doFull) {
var w = _openWindow(params);
if (w && !w.closed) { return; }
else if (doFull) { _redirectWindow(params); return; }
};
function _startChatWithSurveyValues(surveyValues, fallbackToFullWindow) {
surveyValues.issue_menu = '1';
_startChat(surveyValues, fallbackToFullWindow);
};
/* public */
// Set the public site hostname that click to chat should be started on.
this.setSite = function(siteHostname) {
if (!_protoRe.test(siteHostname)) { siteHostname = "http://"+siteHostname; }
if (siteHostname[siteHostname.length-1] != '/') { siteHostname += '/'; }
_host = siteHostname;
};
// Start a click to chat session using a session key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKey = function(sessionKey, fallbackToFullWindow) {
var p = {short_key: sessionKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using a session key and external key, optionally falling back to a full browser window redirect if the popup window fails to open due to popup blockers.
this.startChatWithSessionKeyAndExternalKey = function(sessionKey, externalKey, fallbackToFullWindow) {
var p = {short_key: sessionKey, external_key: externalKey};
_startChat(p, fallbackToFullWindow);
};
// Start a click to chat session using just an issue id and no other front end survey fields.
this.startChatWithIssueId = function(issueId, fallbackToFullWindow) {
_startChatWithSurveyValues({id: issueId}, fallbackToFullWindow);
};
// Start a click to chat session by passing the entire front end survey form element.
// This will submit all non-button input element values on the form.
// Any unexpected survey field names will be ignored.
this.startChatWithIssueForm = function(formElement, fallbackToFullWindow) {
var params = {};
for (var i = 0; i < formElement.elements.length; i++) {
var e = formElement.elements[i];
if (e.name && e.value && e.type && e.type != 'button' && e.type != 'submit') {
params[e.name] = e.value;
}
}
formElement = undefined;
params.issue_menu = '1';
_startChat(params, fallbackToFullWindow);
return false;
};
// Start a session with a representative id and name.
this.startChatWithRepIdName = function(repId, repName, fallbackToFullWindow) {
var p = {id: repId, name: repName};
_startChat(p, fallbackToFullWindow);
};
return this;
}
var BG = Bomgar();
HTML Code:
<script type="text/javascript" src="https://***.******.com/api/clicktochat.js"></script>
<script type="text/javascript">
BG.setSite("https://***.******.com");
</script>
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
// Check each input in the order that it appears in the form
if(madeSelection(issueid, "Please choose an issue"))
{
if(notEmpty(username, "Please enter your name"))
{
if(isAlphanumeric(username, "Numbers and Letters Only for name"))
{
if(notEmpty(userid, "Please enter your user ID"))
{
if(isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
{
if(notEmpty(issuedesc, "Please type a description of your problem"))
{
}
}
}
}
}
}
}
//check to make sure user selected their issue
function madeSelection(elem, helperMsg){
if(elem.selectedIndex == 0 ){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}else{
return true;
}
}
//check to make sure user entered something in the particular field
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
//check to make sure user only entered numeric characters
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user only entered alpha characters
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
//check to make sure user entered only alpha or numeric characters
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<script type="text/javascript">
/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul#REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
function handleEnter (field, event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
}
else
return true;
}
</script>
<form action="https://***.******.com/api/start_session.ns" onsubmit="return formValidator();" method="get">
What issue are you having?
<select onkeypress="return handleEnter(this, event)" id="issueid" name="id">
<option value="">Choose</option>
<option value="1">I need help getting started</option>
<option value="2">I am receiving an error</option>
</select>
<br />
Your First and Last Name: <input onkeypress="return handleEnter(this, event)" type="text" id="username" name="customer_name" /><br />
Your User ID (ABC1234): <input onkeypress="return handleEnter(this, event)" type="text" id="userid" name="customer_id" /><br />
Describe Your Issue: <textarea onkeypress="return handleEnter(this, event)" id="issuedesc" name="customer_desc"></textarea><br />
<input onkeypress="return handleEnter(this, event)" type="hidden" name="issue_menu" value="1" />
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
<br>
<input onkeypress="return handleEnter(this, event)" type="button" name="reset_form" value="Clear" onclick="this.form.reset();">
</form>
</body>
Have you tried replacing the submit button with a regular button, doing the validation in the onClick handler, and then submitting the form from within the onClick handler?
Edit: e.g. replace
<input onkeypress="return handleEnter(this, event)" type="submit" value="Submit" onclick="BG.startChatWithIssueForm(this.form, true); return false;" />
with
<input onkeypress="return handleEnter(this, event)" type="button" value="Submit" onclick="BG.handleSubmit(this.form, true);" />
Then maybe use a Javascript function like this (I'm not sure exactly what order you want these things to happen in):
BG.handleSubmit = function(formElement, fallBackToFullWindow) {
if (!formValidator())
return;
BG.startChatWithIssueForm(formElement, fallBackToFullWindow);
formElement.submit();
return false;
}
Edit: Your validation function should probably return false if it finds something invalid.
function formValidator(){
// Make quick references to our fields
var issueid = document.getElementById('issueid');
var username = document.getElementById('username');
var userid = document.getElementById('userid');
var issuedesc = document.getElementById('issuedesc');
var valid = true;
// Check each input in the order that it appears in the form
if(!madeSelection(issueid, "Please choose an issue"))
valid = false;
if(!notEmpty(username, "Please enter your name"))
valid = false;
if(!isAlphanumeric(username, "Numbers and Letters Only for name"))
valid = false;
if(!notEmpty(userid, "Please enter your user ID"))
valid = false;
if(!isAlphanumeric(userid, "Numbers and Letters Only for user ID"))
valid = false;
if(!notEmpty(issuedesc, "Please type a description of your problem"))
valid = false;
return valid;
}

Categories