How to update `linkRef` in to `touched` state by function? - javascript

In my app, I use the linkRef in form. some reasons I require to update the linkRef to touched state, when i do getting error by function. what is the correct way to do this?
template:
<div *ngIf="linkRef.errors && (linkRef.dirty || linkRef.touched)" class="error" >
method:
addAdnlVasSelection(addVas, linkRef){
console.log('linkRef', linkRef);
if(!addVas.input || !linkRef.errors ){
linkRef.tourched(true); //notworks
linkRef.tourched = true; //notworks
return;
}
}
what is the correct way to do this?

Assuming that linkref has the form instance, try:
this.linkRef.markAsTouched()

Related

Condition is Not checking properly in ng-if with !state.include

<select class="form-control"
ng-if="((!$state.includes('home.allprojects') ||
!$state.includes('home.Sentprojects')) &&
!dynamicFields.isShowVismaButtons)"
ng-model="projects.selectedBokYear" ng-change="onBokYearChange()"
ng-options="font.value for font in projects.bokYears"></select>
Here the code must display if the state is not in the home.allprojects or home.Sentprojects and !dynamicFields.isShowVismaButtons
ng-if="((!$state.includes('home.allprojects') || !$state.includes('home.Sentprojects')) && !dynamicFields.isShowVismaButtons)"
but the Select is visible even in the home.allprojects and home.Sentprojects state
can any one give a solution for it
You cant access $state in html,
Instead write a function which defines your logic and call that function from your HTML, or you can take a variable and use it in html for state
I prefer going with a function which I added in my answer.
HTML:
<select class="form-control"
ng-if="checkState()"
ng-model="projects.selectedBokYear" ng-change="onBokYearChange()"
ng-options="font.value for font in projects.bokYears"></select>
In controller,
$scope.checkState = function(){
return ($state.includes('home.allprojects')) ||
(!$state.includes('home.Sentprojects')) &&
(!$scope.dynamicFields.isShowVismaButtons)
}
I have created a checkState function from HTML and defined your logic there.
Also, to check the state directly if there is no parent-child, you can use $state.current.name
$scope.checkState = function(){
return ($state.current.name != 'home.allprojects') ||
($state.current.name != 'home.Sentprojects') &&
(!$scope.dynamicFields.isShowVismaButtons)
}

Form validation. Optimize Angular ng-required expression

I'm creating a form validation and it becomes too ugly and heavy because of too many fields that need to be validated. I need to optimize it. So, I'm making required any field based on the other fields values using ng-required. When the user insert a value in one of the fields then the rest of them loose the required quality and the form becomes valid. So, for that I created an expression like this:
<input ng-model="field.one" ng-required="
!field.two &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
<input ng-model="field.two" ng-required="
!field.one &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
So, I intend to move the required expression in the controller or where you think it should be moved in order to optimize and organize the code. I was thinking to encapsulate it in a function inside of controller but I didn't succeed. I tried something like this:
VIEW
<input ng-model="field.one" ng-required="myFunc(field.one)"/>
CTRL
$scope.myFunc = function(modelField){
anything I tried in this fn I didn't make it to work syncronized with
the field models, updating their models based on user interaction :)
}
Please, is there someone that has an ideea how should be done? Thanks.
I would prefer one scope variable which is bound to all input field's ng-required attribute. And on change of any of the input field toggle this variable.
http://plnkr.co/edit/PVXVD9RKM8cMwCVjFA7c?p=preview
<input type="text" ng-change="onChange(userName1, 'name1')" name="name1" ng-model="userName1" ng-required="required">
<input type="text" ng-change="onChange(userName2, 'name2')" name="name2" ng-model="userName2" ng-required="required">
$scope.required = true;
$scope.userNames = [];
$scope.onChange = function(val, name) {
if (val) {
if ($scope.userNames.indexOf(name) == -1) {
$scope.userNames.push(name);
}
$scope.required = false;
} else {
if ($scope.userNames.indexOf(name) !== -1) {
$scope.userNames.splice($scope.userNames.indexOf(name), 1);
}
if ($scope.userNames.length === 0) {
$scope.required = true;
}
}
}

Uncaught TypeError: Cannot set property 'display' of undefined

I am in the process of migrating an existing platform to a new server. I am taking the opportunity to upgrade PHP ect and standardise/debug the code as the previous maintainers have had different standards.
I have opted for PHP version 5.4.33 for now, once I have managed to move everything over to mysqli I will look to go to a more recent version. I didnt think anything server side would make a difference to AJAX/JS? As far as I am aware is it not client side?
Since I have moved the code over I am having issues with AJAX/JS. I am not the greatest at AJAX/JS and could use some assistance please. Even though every submit works differently through the entire platform I do not want to remove the AJAX/JS that already exists. I will most likely use it as an opportunity to how to use it as it makes end user experience smoother.
Using Chrome to debug I am receiving the following error on clicking the Save button:
Uncaught TypeError: Cannot set property 'display' of undefined
email_user
onclick
This is the Save button code
<span id="loading" style="color: red; font-size: x-small; display: none; text-decoration: blink;">Loading... Please wait..</span><input type="button" value="Save" class="save" onclick="if(validate()){ email_user(); }" />
This is the function code for validate()
function validate() {
var errorString = "";
if(isBlank(document.getElementById("forename").value)) {
errorString += " - Please input a forename\n";
}
if(isBlank(document.getElementById("surname").value)) {
errorString += " - Please input a surname\n";
}
if(isBlank(document.getElementById("company_name").value)) {
errorString += " - Please select a company\n";
}
if(document.getElementById("username").value != "" || document.getElementById("password").value != "") {
if(isBlank(document.getElementById("username").value)) {
errorString += " - Please input a username\n";
}
if(isBlank(document.getElementById("password").value)) {
errorString += " - Please select a password\n";
}
}
//if not a solicitor then cases mandatory
if(document.getElementById("company_role_type_id").value == 2) {
if(document.getElementById("other_view_if").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(document.getElementById("company_role_type_id").value == 3) {
if(document.getElementById("other_view_ea").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(errorString) {
alert('Please correct the following items:-\n\n'+ errorString);
return false;
}
else {
return true;
}
}
This is the function code for email_user()
function email_user(){
if(skip_email == true){ $('user').submit(); }
var url = 'email_user.php';
var params = '?' + $('user').serialize() + '&from_edit=1';
$('loading').style.display = 'inline';
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: params,
onComplete: show_response
});
function show_response(this_request){
//alert(this_request.responseText);
var reply = this_request.responseText.evalJSON(true);
if(reply['status'] == false){ var blah = ''; }
else{ alert(reply['message']); }
//$('loading').style.display = 'none';
$('user').submit();
}
}
Thinking about it, maybe it is more to do with the Apache version?? Just in case Apache version is 2.2.15.
Any assistance you guys can give me will be greatly appreciated! If you need any more information please let me know.
Kind Regards,
n00bstacker
As previously stated in comments, your code has some issues, your line (the one that is triggering the error, can be optimized in the following way:
$('#loading').css("display","inline"); //Selector is ok now...
In the other hand, I also noticed that you have a second selector $('user') that won´t work. Remember that anything without a dot, or a sharp will be considered as an element selector (loading, and user elements, won´t exist in your document unless you created it.
Remember:
$("#myId") //id selector
$(".myClass") //class selector
If "user" is the form name, the code may work. Remember that you want to catch the form submit event.
Regards,
Guillermo
Try changing $('loading') to $('#loading')?

HTML5 form validation without submit button

i want to validate the form inputs without an type="submit" button.
How can i do this?
I tried this ->
<script type="text/javascript">function validateForm() {
$('#form1')[0].checkValidity()
if( document.form1.vorname.value == "" )
{
return false;
}
if( document.form1.nachname.value == "" )
{
return false;
}
if( document.form1.postleitzahl.value == "" )
{
return false;
}
if( document.form1.email.value == "" )
{
return false;
}
if( document.form1.telefon_optin_Ja.value == "" )
{
return false;
}
if( document.form1.ort.value == "" )
{
return false;
}
if( document.form1.straße.value == "" )
{
return false;
}
if( document.form1.Anrede.value == "" )
{
return false;
}else {
$('#modal_absenden').modal({
backdrop: 'static',
keyboard: 'false',
})
}
}
</script>
My form name is: form1 , button -> `Absenden
The "background" of the question is: I want to validate the form inputs first, then (if all inputs ok) it should opens a modal, where u can select the redirect page (redirect yes, redirect no) then it submit the form via post to mail.php.
I hope u understand my question, if u have questions, pls ask. (My english is not so good..)
Thank you for help.
You have said about HTML5.
Then that means all you have to do is to use checkValidity() along with
<input type="text" name="name" required>
<input type="email" name="email" required placeholder="Enter a valid email address">
Here is the nice article about using HTML5 validation.
I have not used by myself. But I am glad to know a bit from your post.
http://www.the-art-of-web.com/html/html5-form-validation/
If you want to use jQuery one then go for validation.
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You could call your validate function everytime an input changes:
$('#form1 input').change(validateForm);
Using
$("#form1 input").on('change,blur', validateForm);
function validateForm() {
// Caution : this refers to the HTMLElement
}
You shoud consider to use a jQuery form validation like library like http://formvalidator.net/ or http://jqueryvalidation.org/ or create yours.
Cheers
So I guess you want to do frontend validation with Javascript. There are wrapped library to do this. E.g., validate.js, verifyjs, and this one, ...
And you can bind the validation process on the blur event of an input
JQuery validate is a good choice with clear documentation. You just need to download the .js library and place it somewhere under your web folder, and using tag to include it. And call the .validate() function on the form you want to validate. That should be done.
$('input').on('blur', function(){
$("#myForm").validate();
});

Correct syntax for IF statement

Can anyone tell me why this IF statement doesn't work, please? I'm using jQuery and Firebug but the latter is not giving me any useful information.
I'm simply attempting to reveal a "submit" button when all of the fields have been completed and the script runs every couple of seconds to check for input.
My code excerpt goes a little like this:
function checkForm(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
// The following line shows me that the values for the fields are all getting picked up properly
$('#report').html("userName: "+userName+"<br />userContent: "+userContent+"<br />userEmail: "+userEmail);
// But the following line is throwing some kind of error
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideDown();
} else {
$('#update').slideUp();
}
}
$(document).ready(function(){
$('#update').hide();
setInterval('checkForm()' , 2000);
});
And my HTML...
<div id="report"></div>
<form id="submitfact">
<div id="update">Update Database</div>
<label><input id="name" name="name" type="text" value="" /><span>Fact submitter's name</span></label>
<label><input id="email" name="email" type="text" value="" /><span>Fact submitter e-mail address</span></label>
<label class="content"><span>Fact text</span><br /><textarea id="content" name="content"></textarea></label>
</form>
Edit...
I apologise if people think I'm wasting their time by not providing the error message - but Firebug simply isn't giving me anything useful - if it was I'd be posting it here. I am a reasonably experienced php programmer but fairly new to jQuery so I admit I am still getting to grips with both writing the language and debugging it. I'd like to post a screen shot of Firebug's response but, as a new user, I am not allowed... all I am getting is a "red error circle/yellow play triangle" icon in the line numbers column ("script" tab) on the line I've shown above... there is nothing else unless you can tell me where else to look other than the "script" and "console" panels?
Another edit...
Well, I got it fixed by taking a look at Cristoph's suggestion. It's basically the same solution but instead of calling it as a function I put it "inline". I'm not entirely sure what the difference between the two techniques is or whether it's simply a local issue I was having but my new jQuery looks like this:
$(document).ready(function(){
$('#submitfact').keyup(function(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
$('#report').html(userName + "<br />" + userContent + "<br />" + userEmail);
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideUp();
} else {
$('#update').slideDown();
}
});
});
I will have a look through your other comments to see if I can streamline it at all but at least I have a working baseline now! Thanks for your time, everyone :)
First of all, is it really throwing an error, or is it simply not working?
From how i understand your code, your if condition should be:
if (!userName === "" && !userContent === "" && !userEmail === ""){
// show
$('#update').slideDown();
} else {
// hide
$('#update').slideUp();
}
Second: doing this with a timer is a bad idea.
Introducing an eventhandler to check once an inputvalue changed is far better:
$("input").change(function(){
// if all inputs are filled, show Button, else hide it
});
P.S.
advanced insight into Javascript: an empty string is considered "falsy", thus
username === "" could be written as !username. Note however, that undefined, null, false, 0 and NaNare also considered "falsy"! THis means, you can't distinguish them. For this reason i prefer username === "" ( note the === ! )
Try changing your evaluation to this:
if (!userName || !userContent || !userEmail){
$('#update').slideDown();
} else {
$('#update').slideUp();
}

Categories

Resources