Angular 6 Reactive Form Input Value to UpperCase - javascript

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.

Related

Prevent letters from input is not working how I want

I have the following code: https://codepen.io/ion-ciorba/pen/MWVWpmR
The problem is on "Suma solicitata" value, there you can click and edit the value, but when trying to replace a number inside the whole one, the newly replaced number will go to the end of it. How can I fix this, I think it's because of that:
var preventOnlyLetters = function (event) {
$(this).val($(this).val().replace(/[^\d]+/, ""));
}
It's happening because you are triggering this function both on keypress and keyup. You should only have it on either keyup or keypress. But I think it would be much better if you just make the input type="number"

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

Onchange event not triggering when using the minus sign

I'm experiencing a weird issue, or maybe it's something that i simply don't know
i am using an input type text to capture and update a value using ajax.
<input type="text" onchange="functionx(this);" style="width:80px; margin-top: 5px;" name="stock" id="stock" />
if i put any alphanumeric value on the field the javascript function get fired correctly, even if i put the plus sign and some numbers (+123456) but if i use the minus sign it doesn't work (-123456) what am i missing or doing wrong?
Thanks in advance.
UPDATE
function functionx(obj){
alert("function is being called");
}
I ran into a similar issue, while working on a project.
My answer does not exactly address the OP, but might help people running into the similar issue, due to a different reason.
I had an input field, which needed only Natural numbers as input. Therefore inside the onChange handler, I would run a validation, as shown in below code snippet.
<input
...
// AREA OF FOCUS
type="number"
// AREA OF FOCUS
onChange={(event) => {
const isValid = validateNumberValue(event.target.value, 'REGEX FOR NATURAL NUMBER');
if (isValid) {
handleFormInputChange();
}
}}
...
/>
It would work perfectly for the most part, however it would also accept input such as --, ++. Upon investigation, I figured it was due to the onChange handler not triggering when + or - was entered as input.
This was because, the type attribute of the input HTML tag was "number". It would only trigger when a numeric value was entered. I changed the type field to text, and everything started working as expected.
<input
...
// AREA OF FOCUS
type="text"
onChange={(event) => { ... }}
...
/>
Hope it helps. Thanks.
Validate in your JS that you are comparing with a NULL or undefined value and not with a value who is bigger than 0, i tested this on jsFiddle and its working fine.
Something in your validation could be causing this issue.
function functionx(obj){
var objval = obj.value;
if(objval != ""){
alert(objval);
}
}
Check this fiddle

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