Capturing and processing data as soon as it is entered - javascript

Looking for your suggestion on a good way to handle the below.
Need a fast input form for a receive scan webform app. This will be collecting barcodes scanned off of packages one right after another.
the scans will be coming in from a bluetooth scanner into a input field.
after the scan the scanner will insert a CR.
At that point I just want to capture the data and pass it onto a controller for processing, clear the field and return control immediately back to the webpage for the next scan.
The biggest two problems are:
Speed – it has to be fast as they are doing real time scanning.
Keeping the input field the focus all the time so that when they
scan they are not in some other field on the screen. They will start off in the input field, I just need to make sure they go right back to it after each scan automatically.
Any thoughts on how you would best handle?
Here is my HTML:
<input type="text"
id="barcode"
name="barcode"
value=""
onchange="location.href='#Url.Action("scanned", "receiveScan")?barcode=' + $('#barcode').val()"><br>
And this is the controller action:
public ActionResult scanned(string barcode)
{
//code to process goes here
return Ok();
}
Afterwards it resets the webpage to a blank page.
Instead what I need to do is just blank the input field and put the focus back to it.
I do have it working by modifying the controller to be:
public ActionResult scanned(string barcode)
{
var test = barcode;
//code to process goes here
return RedirectToAction("receiveScan", "home");
}
But it has been pointed out that reposting the entire page is not a good idea.
I will try one of the solutions below as soon as I can get back to it.
Thanks for the help, here is the code that worked --
$('#textArea1').val('Scans - ');
$(function () {
$("#barcode").on("change", function (e) {
// get the current value
var barcode = $('#barcode').val();
// if there's no text, ignore the event
if (!barcode) {
return;
}
// clear the textbox
$("#barcode").val("");
// var holdit = $('#textArea1').val();
$('#textArea1').val($('#textArea1').val() +' '+ barcode);
// post the data using AJAX
$.post('#Url.Action("scanned", "receiveScan")?barcode=' + barcode);
});
})

Instead of performing a full postback, you should be using an AJAX call to ensure that the page is not completely reloaded.
Here's an example of how you could do this (untested, might have typos):
<input type="text" id="barcode" name="barcode"/>
$(function()
{
$("#barcode").on("change", function (e)
{
// get the current value
var barcode = $('#barcode').val();
// if there's no text, ignore the event
if (!barcode)
{
return;
}
// clear the textbox
$("#barcode").val("");
// post the data using AJAX
$.post('#Url.Action("scanned", "receiveScan")?barcode=' + barcode);
});
Note that this assumes that the device will actually paste the entire data at once. If you find that the event is firing too often, you will need to implement some throttling around the change event.

Related

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

Search in mysql by Javascript

Good morning , I'm trying to do a check if the cpf entered already exists in the database , I'm using laravel , someone could help me in this function please ?
In my controller I seek and I list all cpfs in bank :
$cpfduplicado = UsuarioEsic::lists('doc', 'id')->all();
foreach ($cpfduplicado as $cpf)
if ($cpf == $request->cpf)
$cpf = 'verdadeiro';
// return redirect('/Esic/CadastroFisica');
return redirect('/Esic/Sucesso');
I'm not sure how to make a function in javascript to get this data and set a custom browser validity , I did something like this:
$(function cpfdupli(input) {
$('.btnCadastroo').on('click', function (json){
if (json.cpf === 'verdadeiro'){
document.getElementById('cpff');
input.setCustomValidity('Cpf já existe.');
} else {
input.setCustomValidity('');
}
});
});
I am beginner in the field and do not really know how to do this work, I just wanted the cpf existed already setasse one CustomValidity in the browser and not let him continue with the registration , if anyone can help me or give me other ways of how solve this I would be very grateful!
PS: Any questions about the code will be available to provide.
ok i will attempt to try and do what your looking for:
Say the html input is something like:
<input type="text" value="" id="cpff" />
Then we have some js to get the details within the above input box, the below does this on each lette typed into the input so its constantly checking as the user types then giving a visual reposnse as the user types so they now if its taken or not as typing:
$('input#cpff').on('keyup', function(evt){
//-- get for value on keyup
var inputValue = this.value;
//-- call to the controller to check
$.ajax({
url : '/check/cpff/',
type: 'POST',
data {cpffValue : inputValue},
success : function(res){
console.log(res);
if(res === 'succcess'){
//-- output a tick icon to let the user know all is ok so far
} else {
//-- output an red x to sai no its been used
}
},
error : function(msg, x){
console.log(msg);
}
})
});
So for each letter typed in the input box the code sends the value to the route /check/cpff and then this returns a boolean / string back to see if its ok or not, hopefully your still with me?
Route:
Route::post('/check/cpff', ['uses' => 'ControllerName#checkCPFF']);
Controller
Class ControllerName extends Controller {
public function checkCPFF(Request $request){
//-- get the ajax data variable -- cpffValue
$formValue = $request->get('cpffValue');
//-- lets chec to see if we have an entry with those values
$doesItExsist = ModelName::where('field_name',$formValue);
//-- if we have a result from the DB then return not allowed
return ($doesItExsist) ? 'not-allowed' : 'allowed'
}
}
SO the above controller takes the data value that the form submits, then checks the required db table and does a search for that value, if it cannot then the user has a valid entry if there is a value found then the user must change their entry etc
its a bit crude and i have nothing to test this with etc so might / will need better working / writing to work as such, you can always change the js to do the same on submitting the form instead etc,
here is a link to test out the input section. to veiw the result open the console up so you can see the values being typed. Example of keyup
i hope it gives your a sort of starting base for help...

Request to Asp page misses if called very fast

I have a website with is made in classic asp. On one page there are 5 textboxes and 5 labels. When users type some value in the textbox then using javascript (added on Onchange event) another asp page is called which done some calculations, fetches some database values based on the value typed and return the result to caller page to be displayed in the corresponding label. Same Page is called for all the textboxes for fetching result. My problem is if user types at normal speed and move to other textbox(using tab) at a normal speed the second page is called properly and result displayed properly in labels, but if the user type very fast then the request for the value of one textbox is not completed and other is send and as a result there is no result value coming for first one. Is there is any way to handle this.
Thanks
If you don't want to refactor the whole thing to use XHRequests, there's a simple solution. Have a "request in progress" flag that is checked in your onchange event. If a request is in progress, queue the current action. In the result display code, check the queue and execute the next action, if any. If there are no remaining actions, reset the flag.
Here's a basic outline in code:
var requestInProgress = false;
var pendingActions = [];
function OnChangeHandler(onChangeFunction) {
if(requestInProgress) {
pendingActions.push(onChangeFunction);
}
else {
requestInProgress = true;
onChangeFunction();
}
}
function ResponseHandler()
{
//Your regular response handling code
if(pendingActions.length > 0) {
var nextFunction = pendingActions.shift();
nextFunction();
}
else {
requestInProgress = false;
}
}
I'm no JS expert, so I'm sure that this could be cleaned up a little bit, but it should handle overlapping events just fine.

How do I set up a timer to prevent overlapping ajax calls?

I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works:
$(function() {
// Wire up search textbox
$('input.Search').bind("keyup", update);
});
update = function(e) {
// Get text from search box
// Pass to web method and bind to concessions grid
$.ajax({
...
success: function(msg) {
displayResults(msg, filterParams);
},
});
}
displayResults = function(msg, filterParams) {
// Databind results grid using jTemplates
// Show results on map: Pass parameters to KML generator and overlay on map
}
Depending on the search, there may be hundreds of results; and so the work that happens in displayResults is processor-intensive both on the server (querying the database, building and simplifying the KML on the fly) and on the client (databinding the results grid, overlaying big KML files on the map).
I like the immediacy of getting progressively narrower results as I type, but I'd like to minimize the number of times this refreshes. What's the simplest way to introduce an N-second delay after the user stops typing, before running the update function?
Instead of calling update() directly, call a wrapper that checks to see if there are any pending delayed updates:
$('input.Search').bind("keyup", delayedUpdate);
function delayedUpdate() {
if (updatePending) {
clearTimeout(updatePending);
}
updatePending = setTimeout(update, 250);
}
function update() {
updatePending = false;
//$.ajax(...
}
You should also probably add:
$('input.Search').bind("blur", update);
This will do an immediate update when the user leaves the field. But make sure you also add handling for the case where the user leaves the field while there's a pending delayed update (cancel the delayed update first).
As a first approach, what about something like :
$('input.Search').bind("keyup", function() { setTimeout(update, 5) } );
(not sure about the exact setTimeout syntax).
You can also keep a variable to track whether the timeout has already been scheduled or not.
You can use Window.SetTimeOut(YourRefreshMethod) , when the YourRefereshMethod gets called, it will check number of characters being typed so far , and compare it to the some counter, the counter will starts with 0 value, so the initial call will do nothing other than updating the counter with the current characters typed count, the second time your method get called , it will check the number of characters typed, if it matches the previous number recorded by the counter , then it means the user didn't type anything new and you can fire your Refresh method, otherwise you will update the counter value

Categories

Resources