How to call a method in angular when an inputfield is empty? - javascript

I am now calling controller methods when this inputfield is changing :
<input type="text" ng-model="query" ng-model-options='{ debounce: 500 }' ng-change="searchOnTags(query)"/>
How can I call a different method when the input field is empty again?

You can just use if statement inside your searchOnTags function like this:
$scope.searchOnTags = function(query) {
console.log(query);
if (!query) {
console.log('input is empty');
}
};

Inside your searchOnTags function check whether the form is $pristine, which means the input field is back to its initial state.
When you edit a field it become dirty(ng-dirty), when you clear the input you can set the form to pristine state(ng-pristine).

Related

Input validation does not trigger till I click something on page. How to avoid this?

I have inputs that I check for empty, null etc. I do this by storing a state boolean and updating it with onChange events for each input. Each input is stored in a session variable using React.useState. The validation work does work, but if I type something in then hit backspace till the input box is empty you can click submit button and send an empty piece of data and I do not know how to prevent this because I'm checking every onChange event for every input box.
Here is one of my inputs
<input id="editCourse_placeHolder_courseName" type="text" placeholder={edit_Course?.name} onChange={new_category_name}/>
Here is where I validate form input for my state variable
const formValidation = ():void => {
if(state_category_name && state_category_name.trim()){
state_form_Validation = false;
} else {
state_form_Validation = true;
}
setState_form_validation(state_form_Validation);
};
here is my state variable that holds the value of the input box which then gets sent to server.
let [state_category_name, setState_New_Category_Name] = React.useState<string | undefined>("");
State boolean to enable this button if all input is good
let [state_form_Validation, setState_form_validation] = React.useState<boolean>(true);
<input name="view" disabled={state_form_Validation} type="submit" onClick={() => {submitEdit();history.push("/");}} value="Edit"/>
And my on change event
const new_category_name = (e:any):void => {
setState_New_Category_Name(e.target.value);
formValidation();
};
Any help would be great, thanks!
There's a few things wrong here.
First, don't set state variables explicitly, e.g., myVariable = 'new value'. Only update them with the setter, e.g., setMyVariable('new value'). The setter you get back from the useState hook is what ties you into the component lifecycle and will re-render it based on changes.
onChange should be a function not a value, e.g.,
const handleChange = e => /* set state here */
<input id="editCourse_placeHolder_courseName" type="text"
placeholder={edit_Course?.name} onChange={handleChange}
/>
When you implement the onChange handler, each keystroke will update state. Then, I would validate in the body of the component, e.g.,
const isValid = validateForm()
You don't need to maintain the valid status in state. You care if it's valid each render so you can allow a form submit, so just do it in the body of the component. Set the result of the validation to the disabled prop on your button.
<input name="view" disabled={!isValid} type="submit"
onClick={() => {submitEdit();history.push("/");}} value="Edit"
/>

Set HTML Form Input To JS Variable

I want to read user input into a form back to them, sort of a confirmation before they send it in. I have some text elements on the page with their corresponding IDs. I would think that I just need to set the variables equal to the values of the input field, but when the function runs it just returns blank.
I have a function that sets the variables to the .value of that form input, but where I might be getting hung up is that there is no default value on the input field, I would think that the value is set after the user inputs something.
Example user inputs "John Doe" into field shouldn't that change the value of that field to "John Doe"?
var Phone;
document.getElementById('confirm-details').onclick = ConfirmDetails()
function ConfirmDetails() {
// Set variable to form input
Phone = document.getElementById("InputPhone").value;
// Change text element to variable
document.getElementById("BookingPhone").innerHTML = Phone;
};
Maybe I'm just confused about the .value attribute but I thought that the value on an input field should be what the user inputted.
This row
document.getElementById('confirm-details').onclick = ConfirmDetails()
should be
document.getElementById('confirm-details').onclick = ConfirmDetails
You don't want that document.getElementById('confirm-details').onclick references the result of the function ConfirmDetails (here void) but the function itself.
Instead of using .value, you need to be using .innerText
Phone = document.getElementById("InputPhone").innerText;
object.oninput = function(){
ConfirmDetails();
};
or, shorthand:
object.oninput = function(){ConfirmDetails()};
You should also use document.getElementById().innerHTML() to get the text
This worked just fine for me. I appreciate all the answers!
<script>
document.getElementById("confirm-details").addEventListener("click", function(){
document.getElementById("BookingName").innerHTML = document.getElementById("InputName").value;
document.getElementById("BookingEmail").innerHTML = document.getElementById("InputEmail").value;
document.getElementById("BookingPhone").innerHTML = document.getElementById("InputPhone").value;
document.getElementById("InputDay").innerHTML = document.getElementById("BookingDay").value;
document.getElementById("InputTime").innerHTML = document.getElementById("BookingTime").value;
document.getElementById("InputService").innerHTML = document.getElementById("BookingService").value;
document.getElementById("InputExtra").innerHTML = document.getElementById("BookingExtra").value;
});
</script>
Here is what I believe you are trying to accomplish:
function confirmDetails() {
// Set variable to form input
var phone = document.getElementById("inputPhone").value;
var confirmMsg = 'is ' + phone + ' correct?' + '<br> <input type="button" value="Yes" onclick="confirmed()"> ';
// Change text element to variable
document.getElementById("bookingPhone").innerHTML = confirmMsg;
};
function confirmed(){
alert('confirmed');
}
<input id="inputPhone" type="text" placeholder="input here">
<input type="button" onclick="confirmDetails()" value="Submit">
<br>
<span id="bookingPhone"></span>
When the button is clicked, it runs the function confirmDetails and sets the variable phone to the user's input. I set variable confirmMsg to the confirm message which reads back the user's input. I used a span with a unique ID and sent the variable confirmMsg to it.
I put the confirm message into a variable to make it more versatile, should you need it elsewhere.

Angular UI-Bootstrap Typeahead: Accept top item as selected on ENTER

Simple question, but is there a way to have the first item in the dropdown results be the selected item when ENTER is pressed?
An example of this is the user types in "PC0" and sees "PC001" listed as the first option, can we have it use "PC001" on the typeahead-on-select option when ENTER is hit?
I am currently using typeahead-on-select to run a function that calls the input via id and grabs the Value for use in the function. It seems to use what was entered into the textbox instead of the selected value, either on ENTER or Click.
HTML:
<input id="applicationComboBox"
type="text"
ng-model="applicationComboBox"
uib-typeahead="a as a.Value for a in applicationList | filter:$viewValue"
typeahead-on-select="getApplication()"
class="form-control">
JS for the getApplicationValue() looks like this:
$scope.getApplication = function () {
$scope.ApplicationValue = applicationComboBox.value;
}
The issue is the applicationComboBox.value is what text the user has typed into the input at the time of the click/enter instead of the clicked/highlighted value respectively. So in previous example "PC0" would be the value instead of "PC001".
When the user selects/press enter the ng-model applicationCombox is is updated automatically. If you want another value $scope.ApplicationValue to be updated after the selection, do the following
$scope.applicationCombox = ""; //your existing model.
$scope.getApplication = function () {
$scope.ApplicationValue = $scope.applicationCombox;
}
Let us know.
I was able to get a solution that worked for me.
HTML:
<input id="applicationComboBox"
type="text"
ng-model="applicationComboBox"
uib-typeahead="a as a.Value for a in applicationList | filter:$viewValue"
typeahead-on-select="onApplicationSelect($item, $model, $label, a)"
class="form-control">
JS:
$scope.onApplicationSelect = function (item, model, label, application) {
applicationComboBox.value= item.Value;
}

Angular form with dynamic input values

I am having issues with angular not picking up the dynamic values from my inputs.
This is what I'm trying to do. When a user clicks on map, the angular populates the hidden form fields with lat/lon, and the user then submits the form, which ends up missing data on the controller.
Here is the relevant controller code :
$scope.formData = {};
$scope.submit = function(addressform) {
addressService.createAdddress($scope.formData).then(function(result) {
$scope.addressResponse = result;
}, function(err) {
alert(err);
});
}
$scope.userSelectedPoint = function () {
$scope.lat = map.getLat();
$scope.lon = map.getLon();
$scope.address = map.getAddress();
}
This is the relevant HTML :
<form id="address_form" name="addressform" ng-submit="submit(addressform)">
<input "lattitude" name="lattitude" type="hidden" ng-model="formData.lattitude" value="{{lat}}">
<input id="longitude" name="longitude"type="hidden" ng-model="formData.longitude" value="{{lon}}">
<p>Selected Address: {{address}}</p>
</form>
Everything looks ok in the chrome inspector(random point on a map) :
However when I submit this form and print out a $scope.formData I get an empty object:
$scope.formData
Object {}
What am I doing wrong here? Why is the formData in my controller empty, when obviously the value is set in the HTML as it can be seen from the screenshot I pasted?
you need to assign the values to ng-model variable, not to the value
as
<input "lattitude" name="lattitude" type="hidden" ng-model="formData.lattitude" />
<input id="longitude" name="longitude"type="hidden" ng-model="formData.longitude" />
assign the value to formData.lattitude.
$scope.formData = {};
$scope.userSelectedPoint = function () {
$scope.formData.lattitude = map.getLat();
$scope.formData.longitude = map.getLon();
$scope.formData.address = map.getAddress();
}
in angular if you provide a value to a variable and u assign that variable to input using ng-model then the input is getting the value of variable, anf if we change input value variable value gets change.
so your assign the lattitude property of formData object to a input. that means if you change the $scope.formData.lattitude input value gets change.
In angular you can't use the value property. You have to initialize the formData object with longitude/lattitude. And therefore you also need any fake hidden field. You don't need this pattern in Angular.

remove hidden field based on hidden field value using jquery

i would like to remove a hidden field from the form using jquery based on hidden field value.
please look the below html:
<input type="hidden" name="myvalue[]" value="value1"/>
<input type="hidden" name="myvalue[]" value="value2"/>
<input type="hidden" name="myvalue[]" value="value3"/>
i have jquery function which returns me the above value example:
$('#getValue').click(function(){
.... processing code here.....
return valueOfHiddenField;
});
now i would like to remove the hidden field from the form based on the value return by the getValue
so if the method returns me value1 then any input hidden field in the form with value as value1 should be removed. in this case the first input field of my html above.
any help or suggestion would be a great help ... thanks in advance
$('input[type="hidden"][value="+YOUR_VALUEVAR+"]').remove();
fiddle: http://jsfiddle.net/9tsgy/
You can iterate over input:hidden elements to check values and remove() based on value,
$("input:hidden").each(function () {
if (this.value == "value1") { // your condition here
$(this).remove()
}
}
$('#getValue').click(function () {
$(document).find("input[type=hidden]").each(function () {
if ($(this).value == 'Your Value') {
$(this).remove();
}
});
return valueOfHiddenField;
});
You can also do like this:
let hiddenValue = $(this).val();
$('input[type="hidden"][value="'+hiddenValue+'"]').remove();
Get the value of a hidden field and then use it dynamically and remove specific <input type="hidden">

Categories