Check if a Radio Button Selection has changed - javascript

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

Related

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

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'} />
}

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

Javascript suddenly can not read value

I'm in the process of writing a client side app that given the ingredients will give you cocktail recipe. When inputted, you click on a button will search the ingredients. If "all" is entered you will be redirected to page with all the recipes.
I had just started this so note the all feature is the only part I've done.
It was working fine. For practice I had it when you entered "all" it would redirect to facebook's url. Out of nowhere(with no new changes) it started throwing me an error, it wasn't reading the input, it was reading it as null.
The relevant HTML:
<input type="text" id="alcohol">
<h4 class="btn" type="submit" onclick="whole()"> Search</h4>
The JS:
var input = document.getElementById('alcohol').value;
function whole() {
if (input == "all") {
window.location = "http://www.facebook.com";
};
};
What's happening here? Why did it stop working?
We need to see a greater context to know for sure, but it appears that you are probably getting the alcohol value too soon before it contains the latest value.
You can change to this to make the whole() function work with the current value of the alcohol field:
function whole(){
var input = document.getElementById('alcohol').value;
if (input =="all"){
window.location="http://www.facebook.com";
};
};
Remember that this:
var input = document.getElementById('alcohol').value;
gets the current value at the time that line of code is run. Any future changes to that field will not affect the input variable. That variable contains the value from a specific point in time only. The easiest way to avoid issues like this is to just get the value right when you need it, not some time earlier.

Meteor: How to set a number based on the number of checked boxes within a section

I currently have a multi-section form, with a number of checkboxes. What Im trying to do, is show the number of checked boxes, next to the total. I have total showing up just fine, but I cant for the life of me figure out a way to loop over the inputs, successfully find the :checked, and print that number out.
I think the main thing causing me issues, is that it needs to update every time a new box is checked. Heres some of the code.
Event Handler
'click input[type=checkbox]': function(){
Session.set('selectedPlayerCount', n);
Session.get('selectedPlayerCount');
}
The goal here is to set the number of selected players, and pass it to the template/helper.
Helper
countSelected: function(){
n = 0;
n++;
var selectedPlayerCount = Session.get('selectedPlayer');
return selectedPlayerCount;
}
Within the helper I'm attempting to iterate every time the event is triggered, and as a result increase the value by one. I'm aware that resetting n back to 0 is going to cause some issues, and I know that needs to be changed one the rest is figured out. I just cant figure out where the variable needs to be set in order to provide a default value.
Template
<header>
<p>{{ countSelected }}</p>
</header>
All I'm trying to do here for now is to print out the value rendered by the helper. I don't believe this is causing any issues.
TL;DR - How to count number of checked inputs within a section of a form, and for each one, increment a value, and then return it every time its changed.
I'm new to this but maybe this will serve: define your account to zero in a session variable, each time you select a checkbox you increase the value of your session variable
Session.set("countPlayersChecked", 0);
Template.proof.helpers({
countSelected: function () {
return Session.get("countPlayersChecked");
}
});
Template.proof.events({
'click input[type=checkbox]': function (event) {
if($(event.target).is(':checked'))
Session.set("countPlayersChecked", Session.get("countPlayersChecked")+1);
else
Session.set("countPlayersChecked", Session.get("countPlayersChecked")-1);
}
});
Hope it serves.

Categories

Resources