jQuery Mobile: Why are onClick and onKeyPress events not working? - javascript

In my jQuery Mobile code, I have some onClick and onKeyPress events but they are not firing. I am converting my client's website to a mobile version that includes lot of javascript functions. I don't know if it works if I convert everything into jQuery but I prefer not to do so and would like to keep the javascript functions as it is.
Is there a way to make this work entirely with javascript and not with jQuery?
onClick="javascript:alert('test');" seems to work fine. It's just the functions that are not being called.
http://jsfiddle.net/jetlag/CtkTV/1/
HTML:
<div data-role="fieldcontain">
<label for="textA">Input A</label>
<input class="inputField" id="textA" value="" type="text" onFocus="javascript:clearText(this);" value="This is default text A" />
</div>
<div data-role="fieldcontain">
<label for="textB">Input B</label>
<input class="inputField" id="textB" value="" type="text" onKeyPress="javascript:keyPressEvent(e);" onFocus="javascript:clearText(this);" value="This is default text B" />
</div>
<div class="ui-grid-b">
<div class="ui-block-a"><input type="button" id="goButton" onClick="javascript:goButtonPress();" value="Go" />
</div>
<div class="ui-block-b"><input type="button" id="testButton" onClick="javascript:alert('Alerted!');" value="Alert" />
</div>
</div>
Javascript:
function keyPressEvent(e) {
var evt = e || window.event;
var keyPressed = evt.which || evt.keyCode;
if (keyPressed == 13) {
document.getElementById('goButton').click();
evt.cancel = true;
}
}
function goButtonPress() {
alert('Button Pressed");
}

Working example: http://jsfiddle.net/Gajotres/aLB6T/
While there's nothing wrong with inline java script you should not use it when working with jQuery Mobile. Because of its architecture it can cause big problems. That is why if possible use classic jQuery.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#testButton', function(){
alert('Alerted!');
});
$(document).on('click', '#goButton', function(){
alert('Button Pressed');
});
$(document).on('keypress', '#textB, #textA', function(evt){
var keyPressed = evt.which || evt.keyCode;
alert(keyPressed);
if (keyPressed == 13) {
document.getElementById('goButton').click();
evt.cancel = true;
}
});
});

There is no e it should be event in your markup. i.e javascript:keyPressEvent(event)
<input class="inputField" id="textB" value="" type="text" onKeyPress="javascript:keyPressEvent(event);" onFocus="javascript:clearText(this);" value="This is default text B" />
Also
Your quotes are at wrong:-
function goButtonPress() {
alert('Button Pressed"); <-- here quotes should match
}
Fiddle
See events

Related

how to assign the "Enter key" to an onclick event?

here i have number input bar with a tag assigned as button , i have an onclick function . how can i make the oncklick to be executed when the user press enter ? ( at this point the user will input a number in the box and press the button with the mouse - how can i make it so the user will input the number and press Enter and the same onclick function will be executed ? )
many thanks in advance.
i tried some codes but they wont work
enter code here
<div id="foot1">
<form action="" method="" name="vform">
<input type ="number" min="0" max="10000000"
placeholder="PEEM it!" value="" id="footbar" />
<div id="foot2">
<li class="foot" alt="foot" title="FOOT (ft)" onclick="runfoot()"></li>
</div>
</div>
You can use the keydown event or similar (keyup, keypress):
document.addEventListener('keydown', function(event) {
const ENTERKEY = 13;
if (event.keyCode === ENTERKEY) {
runfoot()
}
});
https://developer.mozilla.org/en-US/docs/Web/Events/keydown
Just use jQuery's click:
$(document).on("keydown", e => {
if (e.key == "Enter") {
$(".foot").click();
}
});
You can try this:
<div id="foot1">
<form action="" method="" name="vform" onsubmit="return false">
<input
type="number"
min="0"
max="10000000"
placeholder="PEEM it!"
value=""
id="footbar"
/>
<div id="foot2">
<li class="foot" alt="foot" title="FOOT (ft)" onclick="runfoot()">
</li>
</div>
</form>
</div>
<script>
document
.getElementById('footbar')
.addEventListener('keyup', function(event) {
const key = 13;
if (event.keyCode == key) {
runfoot();
}
});
</script>

Call function when press ENTER

I've this code below:
<div class="search-container">
<input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
<div class="label-search" ng-click="vm.goSearch()"></div>
<button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>
How can I call a JS function when I press "enter" in the input?
If you're looking to do it in raw javascript you can use the below binding to bind the enter key for the whole document to the function you wish to call.
// Load in the enter keybindings
document.onkeydown = function (e) {
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
vm.clearQuery()
}
}
you can always wrap it in a form and call onsubmit and just change vm.goSearch() to your actual function.
<form onsubmit="return function(){vm.goSearch();return false;};">
<div class="search-container">
<input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
<div class="label-search" ng-click="vm.goSearch()"></div>
<button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>
</form>
You can try with something like this:
// Get the input field you want
var input = document.getElementById("search-value");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Cancel the default action, if needed
event.preventDefault();
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Trigger the button element with a click
document.getElementById("ElementId").click();
//or function call here
}
});
Here is a useful tips
handle events with HTML/DOM
try ng-keypress event and read keyCode = 13 for enter.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName" ng-keypress="keypress($event)">
<br>
<br>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.keypress=function(e) {
if(e.keyCode == 13) {
console.log('Enter');
}
}
});
</script>

how to close a modal if you click on overlay

I can't figure out why my code doesn't work, I would appreciate if you help me, I need when you click on overlay or close button, overlay will be close.
<div class="callback-form promo">
<form name='promoform' id="promoform">
<span class="close-btn close">✖</span>
<input type="text" name="name" placeholder="Имя" maxlength="30">
<input type="tel" name="phone" placeholder="Телефон" maxlength="20">
<input class="callback-submit" type="submit" value="Отправить" name="save" id="sendPromo" disabled>
</form>
</div>
js:
$(".callPromo").click(function() {
$(".callback-form.promo").css("display", "block");
$(".close").click(function() {
$(".callback-form.promo").css("display", "none");
});
$(".callback-form.promo").on("click", function(e) {
var clicked = $(e.target);
var x = $(".callback-form.promo #promoform");
console.log(clicked);
if (clicked != x) {
$(".callback-form.promo").css("display", "none");
}
});
});
Your .close click event and callback-form.promo firing in same time. Use stopPropagation() for no firing other.
Try below.
$(".callPromo").click(function() {
$(".callback-form.promo").css("display", "block");
});
$(".close").click(function(e) {
$(".callback-form.promo").css("display", "none");
e.stopPropagation();
});
$("#promoform input").on("click", function(e) {
e.stopPropagation();
})
$(".callback-form.promo").on("click", function(e) {
e.stopPropagation();
var clicked = $(e.target);
var x = $(".callback-form.promo #promoform");
console.log(clicked)
if (clicked != x) {
$(".callback-form.promo").css("display", "none");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="callback-form promo" style="background:red;width:300px;height:300px">
<form name='promoform' id="promoform">
<span class="close-btn close">✖</span>
<input type="text" name="name" placeholder="Имя" maxlength="30">
<input type="tel" name="phone" placeholder="Телефон" maxlength="20">
<input class="callback-submit" type="submit" value="Отправить" name="save" id="sendPromo" disabled>
</form>
</div>
So it looks like your HTML you've provided doesn't match what the jQuery is looking for, .callPromo but perhaps this is just your activator and you've not included it? Also you have two additional click events nested in your initial click event. This isn't necessary and may be what is causing you the issue. Try putting all three click events in the same scope.

How to force "enter key" to act as "tab key" using javascript?

I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do.
I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript
This will handle multiple input fields.
Here is the jQuery version:
http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Here is the pure javascript version:
http://jsfiddle.net/TnEB5/5/
(you probably want to get the sibling differently)
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
handle keypress instead and return false back to the browser:
http://jsfiddle.net/EeyTL/
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<script type="text/javascript">
document.getElementById('Text1').onkeypress = function (e) {
if (e.which === 13) {
document.getElementById("Text2").focus();
return false;
}
};
</script>
You'll need to explicitly set the tabindex property of the input fields for a generic solution. Something like
<input id="Text1" type="text" tabindex="1" />
<input id="Text2" type="text" tabindex="2" />
<script type="text/javascript">
$('input').keypress(function(e){
if(e.which==13){
$("[tabindex='"+($(this).attr("tabindex")+1)+"']").focus();
e.preventDefault();
}
});
</script>
this solution uses jquery to assign the event handler for all input type elements on the page, sets focus to the element with the next highest tabindex property, and prevents the form from submitting when enter is pressed using e.preventDefault(). Here's a jfiddle
<input type="text" value="" onkeyup="doNext(this);"> a <br>
<input type="text" value="" onkeyup="doNext(this);"> b <br>
<input type="text" value="" onkeyup="doNext(this);"> c <br>
function doNext(el){
if(event.keyCode=='13'){
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
}
Althought the post is old, I hope my answer can help someone in need. I have a smilar situation:
I have a very large form for an employee scheduler application with different types of input fields. Some of the input fields are hidden sometimes and not other times. I was asked to make the enter key behave as the tab key so the users of the form could use the 10-key when creating thier employees schedule.
Here is how I solved my problem:
$(document).ready(function () {
var allInputs = $(':text:visible'); //(1)collection of all the inputs I want (not all the inputs on my form)
$(":text").on("keydown", function () {//(2)When an input field detects a keydown event
if (event.keyCode == 13) {
event.preventDefault();
var nextInput = allInputs.get(allInputs.index(this) + 1);//(3)The next input in my collection of all inputs
if (nextInput) {
nextInput.focus(); //(4)focus that next input if the input is not null
}
}
});
});
What I had to do was:
Create a collection of all the inputs I want to consider when tabbing. in my case it is text inputs that are visible.
Listen for a keydown event on the inputs in question, in my case all text field inputs
When the enter is pressed on my text input, determine what input is next to be focused.
If that input is valid, bring it into focus.
I am using this code for advancing to next input field. I hate to press TAB key. And this solution works in IE & Firefox:
<script type="text/javascript">
function tabE(obj,e){
var e=(typeof event!='undefined')?window.event:e;// IE : Moz
if(e.keyCode==13){
var ele = document.forms[0].elements;
for(var i=0;i<ele.length;i++){
var q=(i==ele.length-1)?0:i+1;// if last element : if any other
if(obj==ele[i]){ele[q].focus();break}
}
return false;
}
}
</script>
HTML Content
<form id="main">
<input name="" type="text" onkeypress="return tabE(this,event)">
<input type="submit" value="Ok">
</form>
Here is a easy solution for you.
Basically you include the enter2tab.js file and then add the enter2tab class on each object where you want enter to be treated as js.
https://github.com/AndreasGrip/enter2tab
You can obviously look at the code to understand what it does and how..
I believe using e.preventDefault(); is safer than returning false.

Canceling onkeypress event after changing focus

My users want this form to advance focus to the next field when enter is press instead of submitting the form. I've added an onkeypress handler to the test input to change the focus when enter is press.
In the code below, when keydown function changes focus, I see the cursor jump to the new textbox but then the form gets submitted as if I pressed the enter key again. I thought that by returning false in my event handler the event would not be passed on but that does not seem to be the case. I've seen this behavior in both Chrome and Firefox.
Could someone tell me what I am missing?
<form action="" name="confirmation" method="post">
<fieldset>
<div class="clearfix">
<label for="id_event_fuel_amount">Quantity:</label>
<div class="input">
<input type="text" id="event_fuel_amount_id" name="event_fuel_amount" onkeypress="keydown(event, 'event_purchase_amount_id')" />
</div>
</div>
<div class="clearfix">
<label for="id_event_purchase_amount">Sale:</label>
<div class="input">
<input type="text" id="event_purchase_amount_id" name="event_purchase_amount" />
</div>
</div>
<input type="hidden" name="state" value="3" id="id_state" />
<input type="hidden" name="time_stamp" value="2011-09-24 14:34:06" id="id_time_stamp" />
<input type="hidden" name="purchase" value="66" id="id_purchase" />
<input type="submit" value="Save"/>
</fieldset>
</form>
<script>
function keydown(e,s){
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (code==13){
document.getElementById(s).focus();
return false;
}
}
</script>
Try
e.preventDefault();
That should prevent the event from firing the form submit.
I think this might help:
<script type="text/javascript">
document.getElementById('hello').onkeydown=function(e){
var e=window.event || e;
if (e.keyCode == 13) return false;
}
</script>
<input type="text" id="hello" />
Here is a demo: jsFiddle demo

Categories