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

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

Related

HTML input - Replace selected value by typing

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>

Angular 6 Reactive Form Input Value to UpperCase

I am using Reactive form in Angular 6. For input type text I want it to be uppercase. I tried the solution
(input)="form.patchValue({name: $event.target.value.toUpperCase()})"
The solution works fine, but the only problem when I move cursor to middle and type a character, the cursor moves at the end.
Is there any other approach or any better solution?
why don't you just use CSS to do the job?
.uppercase{
text-transform: uppercase;
}
<input class="uppercase" type="text" placeholder="type here">
You can try this:
const yourControl = this.form.get('yourControlName');
yourControl.valueChanges.subscribe(() => {
yourControl.patchValue(yourControl.value.toUpperCase(), {emitEvent: false});
});
I know this is reeeeally late, but...
You could hook on to the (change) event instead of the (input) event. Your case changes won't execute until after the user leaves the field, but it will prevent the cursor from jumping.
You case changes will still execute if the user submits the form by pressing Enter while in the field.

"Bubble" validation message on non-form element

I have some elements on a page and I want to make use of the nice bubble style messages such as described here HTML5 form validation. It seems that to use them it is required they are within a form element and they only can be used on validation once the form is attempted to be submitted.
Taking from the linked example, I want to know how to get the following to work as described (i.e for this example pop a bubble message if the user sets a time before now)
Fiddle for this: My attempt without form
<body>
<label>
Arrival Date:
<input id="arrivalDate" type="date" onchange="dateChanged()" />
</label>
<input type="button" value="Test Reservation"></input>
<script type="text/javascript">
function dateChanged(e){
var arrivalDate = document.getElementById("arrivalDate");
var value = new Date(arrivalDate.value);
if (value < new Date()) {
arrivalDate.setCustomValidity("Arrival date must be after now!");
} else {
arrivalDate.setCustomValidity("");
}
arrivalDate.checkValidity();
}
</script>
</body>
Specifically in my case I have 2 KendoUI DateTimePickers being used to select the time range which is used to display information dynamically on the page. I'd like if I could use these bubble messages if the user tries to make the start time after the end time.
There's no way to manually trigger the validation. Using .checkValidity() will only return true/false if the context of what your checking is valid or not, i.e. if you did form.checkValidity() it will check if all form elements are valid, or input.checkValidity() only check the validity of that single element.
The only way to trigger the validation is on submit. You can simulate this by having a submit button and calling the click function.
if (!arrivalDate.checkValidity())
{
document.getElementById('submit_reservation').click();
}
Fiddle: http://jsfiddle.net/QGpQj/3/
Note: I've added window.dateChanged = .... because of your inline event listener. You really should be using .addEventListener or, ideally, jQuery for this to add backwards compatability support for those non-supported browsers.

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();

Type into a field, and use jQuery/JS to display this value lower on the page

I have a simple task which I'm failing at.
I want to take this field:
<input id="amount" name="amount" value="{$formRefill.amount}" class="textInput auto required validateNumber" type="text">
And once the user has typed a value in there (i.e. 950.50), and they click outside of text field (focus somewhere else), jQuery takes this field and displays it somewhere else on the page.
I was trying to do this inside of a DIV lower down the page.
Thanks.
You need to use change event of the input field:
$('#amount').change(function() {
$('#mydivid').text($(this).val());
});
Code: http://jsfiddle.net/yg9gF/2/
you should use keyup which will update the div on every char entered.
$('#amount').on('keyup',function() {
$('#mydiv').text($(this).val());
});
fiddle : http://jsfiddle.net/yg9gF/11/
you can use the blur() or the change() event. Use change if you want the value to copy only when it has been changed, or blur if you want it to copy regardless.
$('#myText').blur(function () {
$('#myDiv').text($(this).val());
});
http://jsfiddle.net/AAyyq/

Categories

Resources