How to use enter key in bootstrap modal, like tab key - javascript

How to use enter key like tab in forms which is in bootstrap3 modal. Below code working properly in html forms, but not working in bootstrap modal
<script>
function OnKeyPress(field, event)
{
if (event.keyCode == 13) {
for (i = 0; i < field.form.elements.length; i++)
if (field.form.elements[i].tabIndex == field.tabIndex + 1) {
field.form.elements[i].focus();
if (field.form.elements[i].type == "text")
field.form.elements[i].select();
break;
}
return false;
}
return true;
}
</script>
The function is calling like this
<input type="text" class="form-control enter modal-count" id="Name" value="" tabindex="1" onKeyPress="return OnKeyPress(this, event)">

It seems that onkeyPress doesnt register all events like ESC etc ,
http://www.w3schools.com/jsref/event_onkeypress.asp
You can use onKeyDown but im wondering why you have return in there and not just the function immediately.

Related

Automatic keypress on page load

I have an input area where a value has been preset. I would like to make it so that on page-load the "enter" button is pressed on the keyboard to submit the value.
Here is the code:
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
}
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
A solution where I would not need to press enter and the value is submitted is also welcome!
I guess code below would work.
$('#login-input').keypress(function(e) {
if (e.which === 13 && $(this).val() != '') {
console.log('triggered')
player_name = $(this).val();
logged = 1;
}
})
const event = new Event('keypress')
event.which = 13
document.querySelector('#login-input').dispatchEvent(event)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
The doc
If you want it to run after page loaded, use onload event. The solution may look like this:
<script>
function f() {
// Test it:
// alert("Hello, page loaded!");
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="f()">
If you do want user to have a glimpse on your pre-filled login form and inform about what is happening, you may make a delay with setTimeout function, which will fire in 0.5 sec after onload event happened.
<script>
function f() {
$('#some_element').text('Signing you in...');
player_name = $('.some_place').val();
logged = 1;
}
</script>
<body onload="setTimeout(f, 500)">
Or you can call the event handler with a faked keypress like this:
function kpress(e) {
if (e.which === 13 && $(this).val() != '') {
player_name = $(this).val();
logged = 1;
console.log(player_name,logged);
}
}
kpress.call($('#login-input').keypress(kpress),{which:13});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="console_content">
<label>Username:</label><input maxlength="10" class="textarea" id="login-input" autocomplete="off" value="Anonymous" type="text">
</div>
I use the output from the jQuery event binding as the object context for the Function.prototype.call() method and add a "simplified" event object as {which:13}.

Chrome Alert Box Submits Page Even if Returning False

In my application I have a textbox to search for items. In this textbox I want the user to have to enter at least 2 characters before searching. If there's less than 2 characters then I want to display a simple alert box telling the user to enter at least 2 characters. On my text box code looks like:
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
alert('Please ENter at Least 2 Characters');
//return false;
obj.select();
obj.focus();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" name="txtSearch" />
In my javascript the function on every keystroke from the user, it checks the keyCode being pressed looking for the 'Enter' input. If the user presses 'Enter' and the number of characters in the textbox is less than 2 then it should alert the user and return false. But regardless the form is still submitted when the user presses 'Enter'.I also noticed it doesn't hit the 'doEnterKey' function it just submits the form. Any help or suggestions is appreciated.
In Internet Explorer everything works as should, the javascript code stops wait for input from the user then continues, returning false. However in chrome the alert box is displayed it and it still submits the form, almost as if it's not returning the false back to the element.
Pass the event object in the call and on ENTER prevent event default.
I used the keypress event and tested on IE, FF and Chrome.
Now the alert message on form submit will not happen because the ENTER is prevented.
function checkSearchLen(event, obj, defaultEnterButton) {
event = event || window.event;
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
event.preventDefault();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<form action="http://www.google.com" onsubmit="alert('submit');">
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeypress="checkSearchLen(event, this,'MenuBar_imgSearchGo');" name="txtSearch" />
</form>
The best method to deal with this kind of problems is by using Jquery...just a few lines of Jquery code is capable of doing what you did in the entire program!
Another alternate answer is to do checking in form submit event and cancel that submit event based on invalid input. This will prevent page post back. Actually, this is the same approach that ASP.Net framework takes when a page has ASP.Net validators in it with client-side validation turned on.
Also, there is no need to cancel the event in doEnterKey, so I have commented two lines in that function.
The following code will work as I have tested on my side. There are two aspects to the logic being used:
A global variable stopSubmit decides if form submit event will be canceled or not. If this variable is true then form submit event will cancel.
The original form submit event code of the form is being pre-pended with our custom JavaScript that will return a false in case the form submit needs to be canceled. This is happening when body loads for the page i.e. body's onload event calls setFormSubmit to modify existing form submit code. If everything was valid, then original form submit code executes without issues and page posts back.
<body onload="setFormSubmit()">
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server"></asp:Label>
<div>
First name:
<input type="text" name="FirstName" value="Mickey" /><br />
Last name:
<input type="text" name="LastName" value="Mouse" /><br />
<input type="submit" value="Submit" />
<input type="text" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" />
<input type="submit" value="Submit" id="MenuBar_imgSearchGo"/>
</div>
<script>
var stopSubmit = false;
function setFormSubmit() {
document.forms[0].setAttribute("onsubmit", " var stopPostback = StopPostback(); if(stopPostback === true) { return false; } " + (document.forms[0].onsubmit === null ? "" : document.forms[0].onsubmit));
}
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value === 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
stopSubmit = true;
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
return false;
} else {
stopSubmit = false;
doEnterKey(defaultEnterButton);
}
}
function doEnterKey(s) {
if (event.keyCode == 13) {
//event.returnValue = false;
//event.cancel = true;
document.getElementById(s).click();
}
}
function StopPostback() {
if (stopSubmit === true) {
stopSubmit = false;
return true;
}
return false;
}
</script>
</form>

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

how to detect copy and paste in javascript?

I have two fields, one is emailid and another is password in my form. I want to prevent the user from pasting into those fields. They should be forced to enter manually, like Google Forms.
2020 update
There are copy and paste events you can use to prevent these actions, or to modify the data being copied or pasted. (see the links for browser support)
<input type="text" onpaste="return false">
Or the longer javascript version:
const elem = document.getElementById('nopaste');
elem.addEventListener('paste', (event) => {
event.preventDefault();
});
<input type="text" placeholder="can paste"><br>
<input type="text" id="nopaste" placeholder="can not paste">
You could disable ctrl+v combination and right click as well.
for IE, you may tap into following event handlers:
onpaste="return false;"
oncut="return false;"
oncontextmenu="return false;"
oncopy="return false;".
Here is a workaround for all browsers:
function noCTRL(e) {
var code = (document.all) ? event.keyCode : e.which;
var ctrl = (document.all) ? event.ctrlKey : e.modifiers & Event.CONTROL_MASK;
var msg = "Sorry, this functionality is disabled.";
if (document.all) {
if (ctrl && code == 86) {
//CTRL+V
alert(msg);
window.event.returnValue = false;
} else if (ctrl && code == 67) {
//CTRL+C (Copy)
alert(msg);
window.event.returnValue = false;
}
} else {
if (ctrl == 2) {
//CTRL key
alert(msg);
return false;
}
}
}
In HTML section, your fields would look like:
Email :<input name="email" type="text" value=""/><br/>
Password :<input name="password" type="password" value=""/><br/>
Confirm Email :<input name="email" type="text" value="" onkeydown="return noCTRL(event)"/>
Confirm Password :<input name="password" type="password" value="" onkeydown="return noCTRL(event)"/>
I don't think user can copy password fields if input type is password
Hope this helps.
Note:
Disabling JavaScript in browser will let users do whatever they want
Always Keep this in mind: respect user's freedom.
You should use onpaste. The paste event fires when the user attempts to paste text.
HTML
<h3>Play with this text area:</h3>
<textarea id="editor" rows="3">Try copying and pasting text into this field!</textarea>
<h3>Log:</h3>
<p id="log"></p>
JavaScript
function logCopy(event) {
log.innerText = 'Copied!\n' + log.innerText;
}
function logPaste(event) {
log.innerText = 'Pasted!\n' + log.innerText;
}
const editor = document.getElementById('editor');
const log = document.getElementById('log');
editor.oncopy = logCopy;
editor.onpaste = logPaste;
2022 UPDATE:
For Input Elements to receive onChange event on paste action, mention onpaste option as below
<input onpaste='return true' onChange={handleChange}/>
Copy
document.addEventListener("copy", (e) => {
console.log("copy")
});
Paste
document.addEventListener("paste", (e) => {
console.log("paste")
});

Stop the ENTER key from being used in a dojo textarea dijit?

i am trying to limit the height of the dojo's dijit.Textarea by preventing users from hitting the enter key while typing. How can i prevent the enter key from being used? i have the below code but its not wroking.
<input type="text" dojoType="dijit.form.Textarea" maxLength="99" onkeydown="return noEnter" />
function noEnter(evt) { if (evt.keyCode == dojo.keys.ENTER) {
console.log('enter pressed');
evt.stopPropagation();
return false; }else{
console.log(evt.keyCode + ' pressed');
return true; }}
Dojo has a method that can be used for this purpose called stopEvent. Perhaps you could use it like this:
<input type="text" dojoType="dijit.form.Textarea" maxLength="99" onkeydown="noEnter" />
function noEnter(e){
if(e.keyCode == dojo.keys.ENTER){
dojo.stopEvent(e);
}
}
Use a dijit.form.SimpleTextarea which is a straight replacement for <textarea>, that is: it does not automatically adjust the height.

Categories

Resources