I have a simple situation here. lets face html code first =>
<form name="geoKey" method="post" action="index.php">
<fieldset class="gKey">
<legend><input type="checkbox" name="checkUncheck" id="checkUncheck"></legend>
<textarea name="txt" id="txt" cols="34" rows="5"></textarea>
</fieldset>
</form>
and here is javascript =>
function keyPress(e){
var key;
var box = document.getElementById("checkUncheck");
if (window.event){
key = event.keyCode;
} else {
key = e.which;
}
if (key==192){
(box.checked) ? box.checked=false : box.checked=true;
}
}
window.onload = function(){
document.onkeyup = keyPress;
};
so , like you see guys when it is pressed key (numbered 192) checkbox is checking if it is not checked and otherwise too (this is everything working nicely) , but here is a issue => I want that if cursor is focused on textarea and pressed that key (192) in textarea doesn't write anything . please help , thanks :)
Use onkeydown instead and prevent the default browser action by using e.preventDefault:
function keyPress(e){
var key;
var box = document.getElementById("checkUncheck");
if (window.event){
key = event.keyCode;
} else {
key = e.which;
}
if (key==192){
e.preventDefault(); // <-- prevent default action
(box.checked) ? box.checked=false : box.checked=true;
return false;
}
}
window.onload = function(){
document.onkeydown = keyPress;
};
JSFiddle demo.
Related
how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>
I am making a search engine and I would like to know if you can make a changeable href and instead of a button have just a textbox.
Here is what I have:
so can I use a different way that let's me just be able to hit enter instead let me know please
<input id="input" type="url"></input>
<button id="link button"><a id="link" style="text-decoration: none; color: inherit;" href="" TARGET="_BLANK">enter</a></button>
<script src="script.js">
var linkButton = document.getElementById("link button")
linkButton.onclick = function(){
var input = document.getElementById("input").value
document.getElementById("link").setAttribute("href", "http://"+input)
}
</script>
Use this, I hope it resolves the issue:
Check here: https://jsfiddle.net/wh3jefz2/2/
document.getElementById('input').onkeypress = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
var input = document.getElementById("input").value
window.open("http://"+input);
}
}
Another alternative is to use a form
function myfunction(){
var inputbox = document.getElementById('inputval');
document.querySelector('#check').innerText = inputbox.value;
window.open('http://'+inputbox.value);
}
<form onsubmit="myfunction();return false;">
<input name="value" id="inputval"/>
<p id="check"></p>
</form>
can someone help me with my code? everytime I type in my textbox it create multiple textbox but I want to create a program that everytime I hit enter key it create another textbox.
here's my code:
<script language="javascript">
function changeIt() {
var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i><br/>"
}
</script>
<body>
<form name="form" action="post" method="">
<input type="text" name=t1 onkeydown="changeIt()">
<div id="my_div"></div>
</form>
</body>
See this fiddle
What you have done in your code was to create a textfield whenever a key press occurs..To create a textfield only when enter key is pressed you have to check the keycode of the pressed button.
So, Please change your JS a little bit as follows..
function changeIt(event) {
var key = event.which || event.keyCode;
if (key == '13') {
var i = 1;
my_div.innerHTML = my_div.innerHTML + "<br><input type='text' name='mytext'+ i><br/>"
}
}
Please make sure that you replace your <input> also as follows
<input type="text" name=t1 onkeydown="changeIt(event)">
Please read more about keyCode in the docs.. Also, if you want to find out the keyCode of any button, please check keycode.info
Your current JS function is being execute every time a button is pressed because you're use the event onkeydown which will capture any key pressing.
Do this:
<script>
var changed = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
/* YOUR EXECUTION CODE */
}
}
</script>
<form name="form" action="post" method="">
<input type="text" name="t1">
<div id="my_div"></div>
</form>
You are creating a new <input> everytime any key is pressed. Instead, you should check if Enter was pressed using e.key or e.code (note both e.which and e.keyCode are depreacted).
Also, consider using Node.appendChild() instead of innerHTML. Otherwise, every time you add a new <input>, all the existing ones will be re-created and lose their values.
const input = document.getElementById('input');
const inputs = document.getElementById('inputs');
input.addEventListener('keydown', ({ key }) => {
if (key !== 'Enter') return;
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = `mytext${ inputs.children.length }`;
inputs.appendChild(newInput);
});
input {
display: block;
}
<form name="form" action="post" method="">
<input type="text" id="input">
<div id="inputs"></div>
</form>
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode, you can use https://keyjs.dev:
Disclaimer: I'm the author.
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
I have few input fields to update.When press tab key I need move focus to the next field only after success of some validation of the current field. If fails then remain in the same field.
function fieldFocus(e, nxFld){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
e.stopPropagation();
e.preventDefault();
// do validate {}
if (success)
$(nxFld).focus(); //set the focus to the next fld
else
// remain in the same field
}
return false;
}
$(currFld).bind("keydown",function(e) {
return fieldFocus(e, nxtFld);
});
This works fine in IE and Chrome. But in firefox the default focus always fires before the validation. Please help me on this to prevent that default behavior of the firefox.
---- Edited Code related to #Faizul Hasan's code ----
<script>
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
var answer = confirm('Are you sure?')
if(answer)
return true;
else{
// need to stop cursor focus to the next field
e.stopPropagation();
e.preventDefault();
}
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
</script>
This is where Im getting the real problem, before user confirms the focus moves to next field in firefox. But in IE and Chrome its working fine.
Try something like this. This works fine in Chrome and Firefox too.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script>
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
return true;
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
</script>
</head>
<body>
<input type="text" id="first-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="second-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="third-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="fourth-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="fifth-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="sixth-field" onkeydown="fieldFocus(event, this);" />
</body>
Please note this is a sample code for your reference since the way you fire the function is not mentioned in your code. You can use jQuery to easily call the function for keydown event instead of calling it for all input element like onkeydown = functionName(<params>). Hope this would help you.
Updated: Same code but jQuery integrated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="jquery-1.8.2.js"></script>
<script>
$(document).ready(function(){
$('.input-element').each(function(index, value){
$(value).keydown(function(event){
fieldFocus(event, this);
});
});
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
return true;
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
});
</script>
</head>
<body>
<input type="text" id="first-field" class="input-element" />
<input type="text" id="second-field" class="input-element" />
<input type="text" id="third-field" class="input-element" />
<input type="text" id="fourth-field" class="input-element" />
<input type="text" id="fifth-field" class="input-element" />
<input type="text" id="sixth-field" class="input-element" />
</body>
</html>
After few workouts I found something with the Firefox which causes the problem. It is the 'keypress' event.
The 'keypress' event still fires when apply preventdefault() to keydown but only in Firefox.
So I handled the 'keypress' as below and solved my problem.
Hope this will help many others.
var browsFix = false;
function fieldFocus(e, nxFld){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
browsFix = true;
e.stopPropagation();
e.preventDefault();
// do validate {}
if (success)
$(nxFld).focus(); //set the focus to the next fld
else
// remain in the same field
}
return false;
}
$(currFld).bind("keydown",function(e) {
browsFix = false;
return fieldFocus(e, nxtFld);
});
$(currFld).bind("keypress",function(e) {
if (browsFix)
return false;
});