HTML input - Replace selected value by typing - javascript

I have the below input that the user can first click to enable (button1), type the desired new value, and finally save it (button2).
<input class="form-control inputUserValue" onkeypress="return contoso.isNumberKey(this, event,3);"
data-default_value="10,00" value="10,00" disabled="">
The issue: after the field is enabled, the user has first to erase the input content with delete or backspace at keyboard (including when the content is already selected) and then start typing the new value at the blank input field. So, the user can't simply use the mouse to select and just type the new value. This behaviour also occurs at other sections of the software when the input is text.
The idea is to improve the user experience by making it possible to just type the desired new value after button1 pressed, replacing existing and displayed content. The existing text/value should still be displayed, but already selected and ready to be replaced if the user types, or the user may want to deselect and make same minor adjust at the existing text/value.
We've tried onclick="this.select();" when button1 pressed, but still we couldn't type the new value without delete or backspace first.
Can anyone help on how to achieve this?
The HTML is generated and managed with JS. The input is whitin a table-responsive. Our system is designed to work on Chrome.

You were on the right way to use the select() method, but you first need to focus() the input:
usrinput.focus();
usrinput.select();
Working example: (for input type text)
const usrinput = document.querySelector('input');
document.querySelector('#button1').addEventListener('click', function() {
usrinput.disabled = false;
usrinput.focus();
usrinput.select();
});
<button id="button1">enable</button>
<input type="text" value="10,00" disabled>
<button id="button2">Save</button>
Working example: (for input type number)
const usrinput = document.querySelector('input');
document.querySelector('#button1').addEventListener('click', function() {
usrinput.disabled = false;
usrinput.focus();
usrinput.select();
});
<button id="button1">enable</button>
<input type="number" value="10" disabled>
<button id="button2">Save</button>

Related

How do I add the click event to the input field?

I want to add a button property to an entry. For example;
I have an input field that cannot be edited:
When I press the keyboard button it becomes editable:
When the user clicks on the entry field without the need for a different button, it must run a different function. For example barcode scanner. Can an input that is not editable trigger a function? Or can an editable input trigger any function? How do I do this?
As in this application, the barcode event should be triggered by the input field, not the button.
As mentioned in my comment, the UX of the current approach in the question is highly questionable:
It's missing a signifier. There is no clear indication that only that non-editable field - in contrast to all other non-editable ones - triggers something once clicked.
Users, who'd prefer entering the barcode manually, would need to click on the keyboard-button first to make the input field editable, and then, once again, click on the input field to enter data.
Instead, consider to offer both options (entering manually and triggering the camera to scan) within a single input field via its value-help (F4) action:
sap.ui.getCore().attachInit(() => sap.ui.require([
"sap/ui/core/Fragment"
], async (Fragment) => {
"use strict";
const control = await Fragment.load({
definition: `<form:SimpleForm xmlns:form="sap.ui.layout.form"
xmlns="sap.m"
editable="true"
layout="ColumnLayout">
<Label text="Barcode Number" />
<Input width="12rem"
textAlign="Center"
placeholder="XXXXXXXXX"
showValueHelp="true"
valueHelpIconSrc="sap-icon://bar-code"
valueHelpRequest="alert('Scanner triggered!')"
/>
</form:SimpleForm>`,
});
control.placeAt("content");
}));
<script id="sap-ui-bootstrap"
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.layout"
data-sap-ui-async="true"
data-sap-ui-theme="sap_fiori_3"
data-sap-ui-compatversion="edge"
data-sap-ui-excludejquerycompat="true"
data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody"></body>
The value help icon can be set to a barcode one by assigning "sap-icon://bar-code" to the valueHelpIconSrc property (available since v1.84.0) in sap.m.Input.
This approach is beneficial for both - users and developers - because the behavior is now consistent with common user input scenarios, improving familiarity, and for developers, it highly reduces maintenance costs since there is less customization.
If the target UI5 version is lower than 1.84.0 or if the barcode has a fixed length, the control needs to be extended with the method addEndIcon. I explained this in another answer. Here is an example with an extended sap.m.MaskInput:
See https://embed.plnkr.co/EzlF2tkvalJWvSEn?preview
If your non-editable input is non-editable because it has a disabled attribute, you can't attach mouse events to it. (Actually you can, but it won't fire mouse events.)
If you want to fire a click event, you can add the event listener to a parent element, like a div in my example below.
Although it works in Chrome without it, you also need to set pointer-events to none on the input to make the clicks fall through to the parent element in Firefox.
const parentDiv = document.querySelector("div");
const input = document.querySelector("input");
parentDiv.addEventListener("click", (e) => {
input.removeAttribute("disabled");
input.focus();
// or you can open the barcode scanner, etc.
});
input {
font-size: 2rem;
padding: 0.5rem 1rem;
}
input[disabled] {
pointer-events: none;
}
<div>
<input type="text" value="disabled field" disabled>
</div>
It could also work with label if the label contains the input:
<label>Barkod No:
<input type="text" value="disabled field" disabled>
</label>
Try this, replacing the displayDate funcion with your own enable function:
document.getElementById("myBtn").addEventListener("click", displayDate);
Which then calls the CSS change:
input[type="text"]:enabled {
}
https://www.w3schools.com/js/js_htmldom_eventlistener.asp

How to make the entire values to be selected when shift+tab is used after tab out in angular8

i have an input field as amount, in which currency formatting has been done. Here i enter some values and come out using tab. Now i use shift+tab and go to the same field, so in this case i want the cursor is in the last digit i mean first number from right. Instead i want the present values to be selected by default instead of keeping cursor on the last digit.
Example: i typed 213.98 it got formatted to $213.98 after tab out, when i again tab in here, the cursor is next to 8, instead i want 213.98 to be selected and based on arrow keys or mouse i can move to number i wish to change.
Also, when i do ctrl+Z, it has do undo all changes.
HTML:
<input type="text" class="form-control" placeholder="Amount in dolars"
formControlName="amount" autocomplete="off" currencyInput maxDigits="9" [ngClass]="{ 'is-invalid': eoInfo.amount.dirty && eoInfo.amount.invalid }">
TS:
this.eoInfoForm = this.FB.group({
amount: ['', Validators.required],
});
DEMO:DEMO
You can auto select all text by adding onClick="this.select();" on your input.
If you want to do be able to do ctrl+z you need to add a listener for your input state like this: (input)="update($event.target.value);" then in the update method you can do this.history.push(value);. So now you should have an array called history with all different values that have been passed through.
Now to listen to ctrl+z keybind to undo a value you add (keyup.control.z)="onKeydown($event)" to the input and in the method you pop your history and set your new value to the the latest item in the history array. If you want you can also keep the previous value in a separate property and use that as a step in between.
I hope that this is kinda what you are looking for.
EDIT 1:
I do have to mention I commented out the keydown event from the currency validator to show it to you.
demo
You can select the input by simply using the select method on your element during the focus event in the CurrencyInputDirective.
#HostListener("focus", ["$event.target.value"])
onFocus(value) {
// on focus remove currency formatting
this.el.value = value.replace(/[^0-9.]+/g, '')
this.el.select();
}
Now you will be able to select the whole option on clicking Shift+Tab. As for undoing all the changes using Ctrl+z, you can listen to the keydown event and remove the input accordingly. In your CurrencyInputDirective. Add a new HostListener to listen to the keydown.control.z event.
#HostListener("keydown.control.z", ["$event.target.value"])
onUndo(value) {
this.el.value = '';
}
StackBlitz Demo

How to set a input text (with no ID or name) value with a subsequent submit of that input text?

I have been trying already all kind of code snippets in Chrome Dev tools on this website:
http://kiwisdr.sk3w.se:8073/?#
This is a software defined radio running on a webserver.
I would like to use Javascript to set the frequency (and submit) so that I can change the frequency the receiver is currently tuned to.
Manually on the GUI the user can just type a frequency (with or without enter) and the new frequeny inside the input box will be tuned.
This is the HTLM part of the website containing the input (no ID or name, so I am not sure how to properly adress this):
<form id="id-freq-form" name="form_freq" action="#" onsubmit="freqset_complete(0); return false;">
<input class="id-freq-input w3-input w3-border w3-hover-shadow" style="padding:0 4px;max-width:74px" size="8" onkeydown="freq_keydown(event)" onkeyup="freqset_keyup(this, event)" type="text" value="" onchange="w3_input_change('undefined', 'undefined')">
</form>
I managed to set the frequency, but I am stuck on how to make it submit.
This is the code I used to set the frequency input box to a certain value (1234.50):
targetForm = document.forms['form_freq'];
targetForm.elements[0].value = '1234.50';
I already tried to trigger the keydown, keyup or change events using some snippets I found, but I am not sure I adress the right elements in the form with it.
All I want to do is to mimic a user entry by code :-)
Could someone point me into the right direction by having a look on the way how the input works on this website and how I can make the website update the currently received frequency with javascript?
Thanks.
Short answer:
freqset_keyup(document.forms[1][0], null)
Nicer answer:
function change_freq(new_freq) {
var form = document.forms['form_freq'];
var freq_input = form.elements[0];
freq_input.value = new_freq;
freqset_keyup(freq_input, null);
}
change_freq(1234.50)

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.

How to set cursor to input box in Javascript?

document.getElementById(frmObj.id).value="";
document.getElementById(frmObj.id).autofocus;
document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
In the above code the value of the form object is perfectly setting to "" but there is no cursor in the text box. I want a cursor to be there. focus() only focuses that input box but does not actually set the cursor.
In JavaScript first focus on the control and then select the control to display the cursor on texbox...
document.getElementById(frmObj.id).focus();
document.getElementById(frmObj.id).select();
or by using jQuery
$("#textboxID").focus();
I realize that this is quite and old question, but I have a 'stupid' solution to a similar problem which maybe could help someone.
I experienced the same problem with a text box which shown as selected (by the Focus method in JQuery), but did not take the cursor in.
The fact is that I had the Debugger window open to see what is happening and THAT window was stealing the focus. The solution is banally simple: just close the Debugger and everything is fine...1 hour spent in testing!
Sometimes you do get focus but no cursor in a text field. In this case you would do this:
document.getElementById(frmObj.id).select();
One of the things that can bite you is if you are using .onmousedown as your user interaction; when you do that, and then an attempt is immediately made to select a field, it won't happen, because the mouse is being held down on something else. So change to .onmouseup and viola, now focus() works, because the mouse is in an un-clicked state when the attempt to change focus is made.
This way sets the focus and cursor to the end of your input:
div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");
Inside the input tag you can add autoFocus={true} for anyone using jsx/react.
<input
type="email"
name="email"
onChange={e => setEmail(e.target.value)}
value={email}
placeholder={"Email..."}
autoFocus={true}
/>
You have not provided enough code to help
You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.
Here is the canonical plain javascript method of validating a form
It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point:
function validate(formObj) {
document.getElementById("errorMsg").innerHTML = "";
var quantity = formObj.quantity;
if (isNaN(quantity)) {
quantity.value = "";
quantity.focus();
document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
return false;
}
return true; // allow submit
}
#errorMsg { color:red }
<form onsubmit="return validate(this)">
<input type="text" name="quantity" value="" />
<input type="submit" />
</form>
<span id="errorMsg"></span>
In my experience
document.getElementById(frmObj.id).focus();
is good on a browser running on a PC.
But on mobile if you want the keyboard to show up so the user can input directly then you also need:
document.getElementById(frmObj.id).select();

Categories

Resources