Pressing enter in a html input box and following a hyperlink - javascript

In my php file I have the following:
<a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] .'&record=' . $record_number . '"">' . $record_number . '</a>
This sends a user somewhere based on the current page value and record value, it is framed in a pagination type situation, so it goes to the next record, it works, its fine.
I also have a text input box, the idea is that a user can type a number and press enter and if that record exists the user goes to that record. If for instance the user chooses record 23, the code would be like this:
<a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] .'&record=23"">23</a>
So far so good, obviously I'll add in an if ($record_number >= $max_record) for good measure.
Now the question, I would like the users to be able to enter a value into an input box, press enter and follow the hyperlink, how is this achieved?
<input type="text" style="width:200px;" class="form-control float" id="defaultFormControlInput" placeholder="Go to record" aria-describedby="defaultFormControlHelp">
--- UPDATE ---
The below is the 'enter' function so the event listener knows when the enter key is pressed. Given #imvain2's answer below a 'Go' hyper link is displayed and when the link is clicked it functions as required. However, I would like to bypass the link creation so that when 'enter' is pressed then the link is followed without the need for creating a hyperlink first.
document.querySelector('#input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
let url = "?page=artefact&record=" + e.target.value;
goLINK.classList.toggle("active");
goLINK.href = url;
}
});

You can use javascript.
I'm using URLSearchParams to get the query string parameter for page. Then in an keyup event I'm looking for the enter button and putting together the URL and adding it an anchor and displaying that anchor by toggling a class called active
let input = document.querySelector("#defaultFormControlInput");
let goLINK = document.querySelector(".goLINK");
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
input.addEventListener("keyup",function(e){
if(e.keyCode == 13){
let url = "?page=" + (params.page || "1") + "&record=" + e.target.value;
goLINK.classList.toggle("active");
goLINK.href = url;
}
});
.goLINK{display:none;}
.goLINK.active{display:block;}
<input type="text" style="width:200px;" class="form-control float" id="defaultFormControlInput" placeholder="Go to record" aria-describedby="defaultFormControlHelp">
<a class="goLINK" href="">Go</a>

Related

how to make "enter" summit a textarea

I need to know how to send a message in my textarea using enter, not only with the submit button.
This is my code.
function onSend () {
const textareaValue = $textarea.value;
if (textareaValue !== '') {
const template = `<div class="conversation-active">
<img src="Foto1.png" alt="Avatar">
<div class="box-message">
<p class="name">Michael Alean</p>
<span class="time-message">${timeNow}</span>
<div class="message">
<p>${textareaValue}</p>
</div>
</div>`;
$chat.innerHTML += template;
$textarea.value = '';
}
}
you can use like this:
firstly declare named pressed function.
this function checks whether the enter key is pressed. if pressed to the enter key will be manually trigger to onSend function.
function pressed(e) {
// Has the enter key been pressed?
if ( (window.event ? event.keyCode : e.which) == 13) {
// If it has been so, manually trigger onSend function
onSend();
}
}
Secondly you should add to textarea props the this code
onkeydown="pressed(event)"
like this:
<textarea name="myTextArea" onkeydown="pressed(event)"></textarea>
The enter key creates linefeeds (LFs) in a textarea so I suspect you're using the wrong type of input field.
Normally, for input type=”text” or input type=”url” you can use the event...
onchange="alert('OK');"
Which does fire when you press the enter key but not in a textarea.
Forcing a textarea to fire with the enter key; although not impossible, is pretty stupid and a sign that you are using the wrong field type.

HTML Input type text not accepting space keystrokes

I’m having a very odd issue with an input type text field… it won’t accept “space” keystrokes. For example, if I want to write John Smith, the input only would allow JohnSmith (no spaces). There are a couple of particularities about this field. It is dynamically created, and it has been embedded inside a SumoSelect (jQuery Dropdown Plugin) dropdown list. The idea is that if I need to enter a new option that’s is not available, I can enter it in the input field, and it is added to the dropdown list.
Adding option JS code:
$('#aip').SumoSelect();
$('.aipPanel .options').append('<li class="opt" id="addAIP" style="padding-right: 0;width: 94%;"><input placeholder="Add new AIP" style="width:75%;" id="addNewAIPInput" onkeypress="myFunction(event)" type="text"/><a class="btn btn-large" href="#" style="background:#699;line-height:30px;padding:.3em;width:20%;margin-left:0.8em;height:28px;color:#fff;font-weight:700;border-radius: 4px;" id="addNewAIPBtn"><i class="fas fa-plus-square"></i></a></li>');
$("#addNewAIPBtn").click(function() {
var inputValue = $('#addNewAIPInput').val();
if (inputValue !== '') {
$('#aip')[0].sumo.add(inputValue);
$('#aip')[0].sumo.reload();
$('#aip')[0].sumo.selectItem(inputValue);
}
});
I added an onkeypress function just for testing. It recognizes all keystrokes except... "space":
function myFunction(event) {
var x = event.which || event.keyCode;
console.log("The Unicode value is: " + x);// It works just fine!!!
if(event.which === 32){
console.log('space entered'); // Nothing happens here!!!
event.target.value = event.target.value + ' ';// just for testing
}
}
Everything else works just fine. The new option is added to the dropdown list. I can enter any letter on the input box, but not "spaces".
Any ideas what could be happening here?

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Is it possible to make input act like a link (Chrome)

I want an input type="button" act like a link to the browser (so, it is possible to right click on the input and see context menu for the links(open link in a new tab, open link in a new window etc).
I have a form with a submit button:
<input type="submit" value="Run Query"/>
In order to create a link and have this context-menu, I replaced input with:
Run Query
But this way "open link in a new tab" opens the same page(due to the href attribute).
I know that you can just ctrl+click on the <input type="submit"/> to open it in a new tab, but if the input tag is present, there is no context menu for it in Chrome.
Is it possible to create an input that would have the same context menu as a link? Or any trick to tell the browser to add this functionality to the input tag?
If I understand your problem correctly, you want to submit the form to a new tab?
Then you could use target="_blank" on the form element.
<form action="" method="POST" target="_blank" >
<input type="submit" />
</form>
This will use the query string to pass the value of each input field to a new window or tab and submit it. It won't work if you're posting files (a workaround would be to immediately upload the file when selected, give it an id and store that in a hidden field, so the file id is the one being posted).
Note that this is an example and you should use something better for dealing with query strings and browser compatibility (it's only tested on Chrome). You should test it thoroughly in other browsers before shipping this! I also have no clue how it's going to work in browsers for iOS/Android/Windows Phones etc. What I'm trying to say is that you probably shouldn't use this.
<body>
<form action="http://google.com">
<input type="text" name="stuff" value="" />
<input type="text" name="q" value="" />
Submit
</form>
<script>
!function () {
var form = document.querySelector("form")
var submitButton = document.querySelector("a")
var queryString = location.search.slice(1).split("&").reduce(function (seed, str) {
var pair = str.split("=")
seed[pair[0]] = decodeURIComponent(pair[1])
return seed
}, {})
Object.keys(queryString).forEach(function (qsKey) {
var formEl = form.querySelector("[name='" + qsKey + "']")
if(formEl)
formEl.value = queryString[qsKey]
})
if(queryString.submit)
form.submit()
submitButton.addEventListener("contextmenu", updateHref) // Update on right click
submitButton.addEventListener("click", function (e) {
if(e.altKey || e.ctrlKey || e.shiftKey || e.which === 2 /* middle mouse button */) {
updateHref()
} else {
e.preventDefault()
form.submit()
}
})
function updateHref() {
var values = [].slice.call(form.elements).map(function (el) {
return el.name + "=" + encodeURIComponent(el.value)
})
submitButton.href = location.pathname + "?submit=1&" + values.join("&")
}
}()
</script>
</body>

Scan barcode into a specific textbox

I am working on bar-code scanners. The bar-code scanner that I am using is a plug-n-play type and scans the code automatically wherever you place the cursor. But what i want is that whether i can scan it to a specific text-box on a web page everytime my scanner reads a code
For eg, if my form looks like this
<input type="text" name="txtItem" id="txtItem" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemId" id="itemId" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemName" id="itemName" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemQty" id="itemQty" class="m-wrap w-120" tabindex="6">
so everytime i scan a code it should always appear in the txtitem text-box no matter where my current focus is.
Can anybody guide me or help me find a solution here??
Some Barcode Scanners act just like another input device. The form cannot tell the difference between information being entered by a keyboard vs. a scanner unless you use a timer to monitor how quickly it is entered.
Some scanners "paste" the values in to the focused control - others send each individual key stroke.
The following JSFiddle is able to detect when input occurs when characters are sent individually on a single control:
http://jsfiddle.net/PhilM/Bf89R/3/
You could adapt this to make it a delegate for the whole form and remove the input from the control it was input into and put it into the correct form.
The test html for the fiddle is this:
<form>
<input id="scanInput" />
<button id="reset">Reset</button>
</form>
<br/>
<div>
<h2>Event Information</h2>
Start: <span id="startTime"></span>
<br/>First Key: <span id="firstKey"></span>
<br/>Last Ley: <span id="lastKey"></span>
<br/>End: <span id="endTime"></span>
<br/>Elapsed: <span id="totalTime"></span>
</div>
<div>
<h2>Results</h2>
<div id="resultsList"></div>
</div>
The Javascript for the sample fiddle is:
/*
This code will determine when a code has been either entered manually or
entered using a scanner.
It assumes that a code has finished being entered when one of the following
events occurs:
• The enter key (keycode 13) is input
• The input has a minumum length of text and loses focus
• Input stops after being entered very fast (assumed to be a scanner)
*/
var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
var minChars = 3;
// handle a key value being entered by either keyboard or scanner
$("#scanInput").keypress(function (e) {
// restart the timer
if (timing) {
clearTimeout(timing);
}
// handle the key event
if (e.which == 13) {
// Enter key was entered
// don't submit the form
e.preventDefault();
// has the user finished entering manually?
if ($("#scanInput").val().length >= minChars){
userFinishedEntering = true; // incase the user pressed the enter key
inputComplete();
}
}
else {
// some other key value was entered
// could be the last character
inputStop = performance.now();
lastKey = e.which;
// don't assume it's finished just yet
userFinishedEntering = false;
// is this the first character?
if (!inputStart) {
firstKey = e.which;
inputStart = inputStop;
// watch for a loss of focus
$("body").on("blur", "#scanInput", inputBlur);
}
// start the timer again
timing = setTimeout(inputTimeoutHandler, 500);
}
});
// Assume that a loss of focus means the value has finished being entered
function inputBlur(){
clearTimeout(timing);
if ($("#scanInput").val().length >= minChars){
userFinishedEntering = true;
inputComplete();
}
};
// reset the page
$("#reset").click(function (e) {
e.preventDefault();
resetValues();
});
function resetValues() {
// clear the variables
inputStart = null;
inputStop = null;
firstKey = null;
lastKey = null;
// clear the results
inputComplete();
}
// Assume that it is from the scanner if it was entered really fast
function isScannerInput() {
return (((inputStop - inputStart) / $("#scanInput").val().length) < 15);
}
// Determine if the user is just typing slowly
function isUserFinishedEntering(){
return !isScannerInput() && userFinishedEntering;
}
function inputTimeoutHandler(){
// stop listening for a timer event
clearTimeout(timing);
// if the value is being entered manually and hasn't finished being entered
if (!isUserFinishedEntering() || $("#scanInput").val().length < 3) {
// keep waiting for input
return;
}
else{
reportValues();
}
}
// here we decide what to do now that we know a value has been completely entered
function inputComplete(){
// stop listening for the input to lose focus
$("body").off("blur", "#scanInput", inputBlur);
// report the results
reportValues();
}
function reportValues() {
// update the metrics
$("#startTime").text(inputStart == null ? "" : inputStart);
$("#firstKey").text(firstKey == null ? "" : firstKey);
$("#endTime").text(inputStop == null ? "" : inputStop);
$("#lastKey").text(lastKey == null ? "" : lastKey);
$("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
if (!inputStart) {
// clear the results
$("#resultsList").html("");
$("#scanInput").focus().select();
} else {
// prepend another result item
var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
$("#resultsList").prepend("<div class='resultItem " + inputMethod + "'>" +
"<span>Value: " + $("#scanInput").val() + "<br/>" +
"<span>ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "</span></br>" +
"<span>InputMethod: <strong>" + inputMethod + "</strong></span></br>" +
"</span></div></br>");
$("#scanInput").focus().select();
inputStart = null;
}
}
$("#scanInput").focus();
The code above does not support copy/paste, but in our situation this is unlikely to happen anyway.
You need to listen on "paste" event using jQuery
$("input").on("paste",function(e){
$("#txtItem").focus();
});
Here is a example:
http://jsfiddle.net/T6VdS/
I would think the scanner is just being seen as a text input device like a keyboard and outputting text. Unless there is a way to identify that text then the answer is likely to be that there isnt an easy solution.
If the code you are receiving is always in the same form and can be identified with a regular expression you might be able to move it into the correct box by somehow buffering the input (I would expect the scanned code to come in a series of keypresses that are far faster than a human would input) and running a regex over it...
Add a prefix to the text that the scanner outputs (almost all scanner will let you do this) and then when any input starts with that prefix you know its the scanner.
To catch the input with jquery you might do something like this:
//presuming the scanner acts like a keyboard
$(document).keypress(function (e) {
//do something to match the 'key presses'
//focus to the input and put the rest of the string in there
});
The best way is to put
data into scanned code. Almost all scanners support such programming. Many of them can be programmed via control barcodes, that printed in manual.
I use the Ctrl+Char for Symbol scanner,
F9 data F10 for Honeywel bluetooth scanner.
Wasp scanner does not support Ctrl+character combination. So I use
[Data] format for Wasp.
Then I catch the first symbol (say [ char) in program an position the cursor in search box. Upon receiving the last character (in my case ] char) send the contents of into search routine.

Categories