How to dynamically check if input is empty without using onChange? - javascript

I want to get one-time information from the input control when value is empty and when value is not empty
Right now I'm using onChange like below:
<Input onChange={onChangeValue()} />
But this onChangeValue method is running every time when I type into the input, but I want two times information, first when value from input is empty and second when value from input is not empty.
Can someoone tell me what can I do this?

You can put some logic before your onChangeValue() function that checks the input value's length and then calls onChangeValue():
beforeOnChangeValue = function() {
if(arguments[0].target.value.length <= 1) return onChangeValue(arguments)
}
<Input onChange={beforeOnChangeValue} />
This way the onChangeValue() function will only be called when the input is either emptied or when the first character is put in

it seems like you're using controlled components (changing the value of the control on every key typing). I think based on your strategy that you could use a flag in the onChange handler like this
function onChange (evt) {
setIsEmpty(!!evt.target.value);
// Your code ...
}
Then you'll always know if the input is empty or not.
function Form () {
const [isEmpty, setIsEmpty] = React.useState(false);
// onChange here
return <Input className={isEmpty ? 'empty-class' : 'non-empty-class'} />
}

Related

Validate HTML input in JS prior to change

It looks like when an input element is initially loaded, its validity is not evaluated right away. For example, if my HTML looks like this...
<input type="text" value="ABC" minlength="5">
In JavaScript it appears that the input is valid and not too short, despite the value attribute being set to a length less than 5. For example:
const input = document.querySelector("input");
console.log(input.validity.valid); // true
console.log(input.validity.tooShort); // false
Only when the user makes a change in the input can we get a true reckoning of the input's validity.
Is there any way to force the input to evaluate its actual validity on load, even if the user has not yet touched the input?
See example: https://jsfiddle.net/t5afujkn/3/
I guess the reason is your default value is not checked from <input> directly at load as it probably does not trigger a check for the default values.
You can add another check condition in your js as below:
{
const displayObj = {
valid: input.validity.valid,
tooShort: input.validity.tooShort
};
if (input.value.length < 5) {
displayObj.valid = false;
displayObj.tooShort = true;
document.querySelector("p").textContent = JSON.stringify(displayObj);
}
}
or maybe you can also try to put the if condition somewhere outside the button call.
Also I did an update in JSFiddle; not sure if you can see it: https://jsfiddle.net/2Lhp96ct/6/

React Js - Unable to enter value in Input Field

I appreciate all of your idea in advance. My problem here is the input field of the email is not updating. Can anyone give me a solution?
<input
type="text"
placeholder="Enter Email "
onChange={this.emailHandle}
value={this.state.email}
/>
Event handler for the above input field is here:
emailHandle = (e) => {
if (e.target.value !== "undefined") {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (pattern.test(e.target.value)) {
console.log(e.target.value);
this.setState({ email: e.target.value })
}
}
}
The onChange event will never be validate by the regex cause it is called on each key typed. So you start typing andy#gmail.com, with the a but a does not pass the regex... so the state is not updated... so it's like you didn't type a.
What's the initial value of your component state? For one, if you're not initializing the email property on state to be an empty string, and it's undefined, you're blocking that state from ever updating with your undefined check. But you have a bigger problem than that. You're testing to see if the value of the input matches your email regex pattern. That won't ever work if you use that check to block setting state. onChange is going to fire every time the input value changes, and that means it's going to change one character at a time. So what's happening is the user types a character, the onChange fires, but it doesn't match your pattern, and you don't update state.
What you want to do is always update state and then handle this as validation to block submitting the form. Or you could show an error of some kind, but you need to always call setState with the new value on e.target.value.

Check if a Radio Button Selection has changed

I am trying to learn basics of Angular and stuck with a particular doubt. I have a set of dynamically generated radio button and one of them will be selected by default.
I want to check and detect the change of selection of radio button. This might not be particularly related to angular or maybe logic based question. Below is what I have attempted.
$scope.selectedReason= function(radio1)
{
$scope.radio7=radio1.id; // now radio7 has the value of radio7 e.g "12345"
$scope.bankAccount=radio1;
}
// another function where I am checking if the selected value is not same as new value
$scope.selectedAmount= function(radioSelect)
{
console.log($scope.radio7); // old value 12345
$scope.preselectedAccount = $scope.radio7; // hoping to store old value
$scope.selectedValue = $scope.preselectedAccount;
if ($scope.selectedValue == $scope.radio7){
console.log("Success");
}
}
Baiscally I am trying to store old value to a variable and check but its obvious that every time a new value comes the variable takes that value so there is not point in doing this. Any way I could pertain my old value check with new values.
Edit:
Input
<input type="radio" id="child_{{$index}}" name="radio2" ng-model="selectedBankAccount" ng-value="bankAccount" ng-click="selectedReason(bankAccount)">
You can use the change event for it
// you can pass anything in the function
<input type="radio" (change)="handleChange(child_{{$index}})" />
and in your TS file implement the handleChange function and do what you want.
handleChange(id) {
console.log(id);
}

How do I detect whether or not an input with type=time has any values entered

I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.
However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.
In the below example, timeSelector is the input with type="time".
if (timeSelector.value == "") {
timeSelector.classList.add("empty");
} else {
timeSelector.classList.remove("empty");
}
Is there any way to detect this type of thing?
To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.
var checkInput = function() {
var value = this.value
var isValid = this.checkValidity()
if (!this.value.length && isValid) {
console.log('empty');
} else if (!this.value.length && !isValid) {
console.log('invalid time entered')
} else {
console.log('valid time entered')
}
}
var input = document.querySelector("input")
input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)
<input type="time" />
Per the specification on Input Elements with type time ( HTML Spec ) :
The value attribute, if specified and not empty, must have a value that is a valid time string.
If the value of the element is not a valid time string, then set it to the empty string instead.
This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.
You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.
The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.
By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">
The only way to possibly get around the lack of a changing value is to set a default value as below:
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("change");
<input type="time" value="00:00">
However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.
You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.
Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.

How to capture previous value of optionset field onchange?

I have an optionset field in an entity, I want to fire a JavaScript method on this field change. I want to capture the old value of the field on the change. I've got a solution which gets the old value on form load, but this doesn't work on multiple changes.
This has to be solved by our own code implementation. Store the attribute value on form load in a variable, keep the new value in that variable on every change, so you can use that in onChange handler. At the end of business validation inside handler put that new value in variable if success or revert to old value if failed.
var previousValue;
function onFormLoad(){
previousValue = formContext.getAttribute("fieldname").getValue();
}
function onFieldChange(){
if(myBusinessValidationSucceeds){
previousValue = formContext.getAttribute("fieldname").getValue();
}
}
Idea 1 and Idea 2

Categories

Resources