How to trigger a function on Enter key - javascript

I would like to add code that allows me to use the enter key in addition to a cursor click to initialize a google map at the location that is submitted via a text box. I have the click part down, the enter key, not so much :(
<input id="address" type="text">
<input id="search" type="button" value="search" onClick="search_func()">
<script>
function search_func() {
var address = document.getElementById("address").value;
initialize();
}
</script>

Here is your solution:
<!DOCTYPE html>
<html>
<head>
<title>WisdmLabs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<input id="address" type="text" onkeypress="handle(event)" placeholder="Type something here">
<input id="search" type="button" value="search" onClick="search_func()">
<script>
function search_func(){
address=document.getElementById("address").value;
//write your specific code from here
alert("You are searching: " + address);
}
function handle(e){
address=document.getElementById("address").value;
if(e.keyCode === 13){
//write your specific code from here
alert("You are searching: " + address);
}
return false;
}
</script>
</body>
</html>
Feel free to ask any doubts or suggestions.

You would want to add a listener to your text box that fires search_func on keydown, when the key pressed is enter (13 is the keyCode for Enter):
<input id="address" type="text" onkeydown="key_down()">
<input id="search" type="button" value="search" onClick="search_func()">
<script>
function key_down(e) {
if(e.keyCode === 13) {
search_func();
}
}
function search_func() {
var address = document.getElementById("address").value;
initialize();
}
</script>

function search_func(e)
{
e = e || window.event;
if (e.keyCode == 13)
{
document.getElementById('search').click();
return false;
}
return true;
}

Related

HTML check user input in form for letters

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>

Textbox focus in phonegap does not work

I am trying this link http://jsfiddle.net/QRj83/ to make it work on my phonegap app. The codes is working properly in the website but not in the phonegap app. There is no error shown and it's strange why is not working. Have someone encountered that problem in phonegap?
This is my code in js:
$('input').keyup(function(e) {
if(e.keyCode == 13) {
$(this).next().focus();
}
});
Html code:
<input type="textbox" />
<input type="textbox" />
<input type="textbox" />
Thank you.
<!DOCTYPE html>
<html>
<body>
<input type="textbox" id="text1" name="text1" />
<input type="textbox" id="text2" name="text2" />
<input type="textbox" id="text3" name="text3" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var name="text";
var count=3;
$( document ).ready(function() {
setIndex();
});
function setIndex() {
for(var i=1;i<=count;i++)
{
document.getElementById(name+i).tabIndex = i;
document.getElementById(name+i).onkeypress = function(event) {
myFunction(event);
}
}
}
function myFunction(event) {
var x = event.which || event.keyCode;
if(x==13)
{
var item=event.target.id;
var tabIndex=parseInt(item.replace(name,""));
if(tabIndex==count)
{
document.getElementById(name+1).focus();
}
else
{
tabIndex=tabIndex+1;
document.getElementById(name+tabIndex).focus();
}
}
}
</script>
</body>
</html>

focus textfield if javascript validation failed

I've this code:
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body>
<form name="frm" action="test.php">
Enter name:<input type="text" name="name" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit"/>
</form>
</body>
</html>
In above code, I'd tried to validate textfields when they lose focus. The script working fine if the name starts with A. But I want if the user enter different name which doesn't start with A it will return the focus to the textfield name. For that I'd written this script:
<script type="text/javascript">
var name = document.frm.name.value;
if(name.indexOf("A") == 0){
alert(name);
}else{
document.frm.name.focus();
}
</script>
then it doesn't works.
Anybody could help with that what should I do to request focus of textfield name?
I've only a little knowledge of javascript.
Just give an id for you form and refer it with document.getElementById('form_id'). Use of name attribute in this context has been deprecated over a decade ago. Also name for input should be something else than "name", rather use username or sth.
HTML:
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" id="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" id="email" onblur=""/>
</form>
JavaScript:
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
Instead of retrieving the id of the form, you can also pass the form to validate() as an argument: onblur="validate(this);". Then use that argument as a form in the eventhandler:
function validate(form){
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
EDIT
Focus doesn't seem to work without a delay, you can try this (the inputhas an id="username"):
function focusTo (elm) {
elm.focus();
return;
}
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
alert('error');
setTimeout(function () {focusTo(form.username);}, 10);
}
}
modifiy your script like this
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body >
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit" onclick="check()"/>
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
alert(name);
document.getElementById('frm').email.focus();
}else{
document.getElementById('frm').username.focus();
}
}
function check()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
}else{
alert("Please enter a name starting with 'A'");
document.getElementById('frm').username.focus();
}
}
//-->
</SCRIPT>
</body>
</html>
You want to execute function validate() on event onblur. in the script you have written the code for focusing, but not added it in a function.
try this document.frm.username.focus(); . i hope it will work.

How to resolve this conflict with jQuery

Can anyone please help me resolve this conflict with my javascript validation?
The form does not submit. But if I remove onsubmit="return btnSubmitPD_OnClick() it redirect the form correctly. But of course I need that function.
Here's my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#Submit').click(function() {
var emailVal = $('#email').val();
$.post('checkemail.php', {'email' : emailVal}, function(data) {
if(data=='exist') {
alert('in'); return false;
}else{
$('#form1').submit();
}
});
});});
</script>
<script type="text/javascript">
function appIsEmail(str){
var at="#";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (str.indexOf(at)==-1) return false;
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
if (str.indexOf(at,(lat+1))!=-1) return false;
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
if (str.indexOf(dot,(lat+2))==-1) return false;
if (str.indexOf(" ")!=-1) return false;
return true;
}
function btnSubmitPD_OnClick(){
frmReg = document.getElementById("form1");
if (!appIsEmail(frmReg.email.value)){
alert("Please enter a valid email address!");
frmReg.email.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php" onsubmit="return btnSubmitPD_OnClick()">
<p>
<input type="text" name="email" id="email" />
</p>
<p>
<input type="button" name="Submit" id="Submit" value="Submit" />
</p>
</form>
</body>
</html>
Several Things:
It is better to bind a submit event to your form, rather than a click event on your submit button, this is to cater for cases where users press enter on the email text field:
$('#form1').submit(function() { // change from $('#Submit').click
Then inside the new submit handler, you call call the email validation method:
var emailVal = $('#email').val();
if(btnSubmitPD_OnClick() === false) return false;
Then, to avoid infinite submit loop, you need to change:
else{
$('#form1').submit();
}
to
else{
$('#form1')[0].submit(); // native submit on form element
}
Or as mplungjan noted in his comment, simply change your
<input type="button" name="Submit" id="Submit" value="Submit" />
To use type="submit"
<input type="submit" name="Submit" id="Submit" value="Submit" />
And add
if(btnSubmitPD_OnClick() === false) return false;
Before your call to $.post

Checking two events in one html tag

I want to check two things in the form, one is onclick and the other "enter" function. So that, alert will be used by clicking the button or pressing "enter". But, "enter" function is not working(There is no problem with "onclick"). Where is the problem? Codes;
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)" onKeyDown="keyevent(event)">
</FORM>
Javascript
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar = form.inputbox.value;
alert ("You typed: " + TestVar);
}
function keyevent(e)
{
if (e.keyCode == 13)
var TestVar2 = form.inputbox.value;
alert ("You typed: " + TestVar2);
}
</SCRIPT>
Thanks
The event onKeyPress should be add to the textbox to call keyevent function to check for enter key. Here is a quick sample from your code:
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar = form.inputbox.value;
alert ("You typed: " + TestVar);
}
function keyevent(form, e){
if (e.keyCode == 13) {
var TestVar2 = form.inputbox.value;
alert ("You typed: " + TestVar2);
}
}
</SCRIPT>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE="" onkeypress="keyevent(this.form, event)"><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)" onKeyDown="keyevent(event)">
</FORM>
You might also want to add onSubmit="return false;" in the form tag to prevent the form to be submitted user press enter key in the textbox.
If you can use jQuery, you could try something like this:
<html>
<head>
<title>test</title>
</head>
<body>
Enter something in the box: <br />
<input type="text" id="inputbox" value="">
<input type="button" id="button1" Value="Click">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
var inputbox = null;
var button1 = null;
var keyEvent = function(event) {
if(13 == event.keyCode) {
alert("you've typed: " + inputbox.val());
return false;
}
};
var button1_Click = function(event) {
if('' != inputbox.val()) {
alert("you've typed: " + inputbox.val());
}
};
$(function() {
inputbox = $("#inputbox");
button1 = $("#button1");
inputbox.keypress(keyEvent);
button1.bind('click', button1_Click);
});
</script>
</body>

Categories

Resources