Disable the input value - javascript

I have an input field. In which I want to fix a value. I am able to fix the value by putting readonly but it's not passing the value which I have put as fixed.
what I am doing is:-
<input name="txt_zip_code" class="z-con-input adj-z-con-input" style="background:#eee" type="text" maxlength="13" field="txt_zip_code" value="98052" readonly="readonly" />
I want to make the value same for every user.
Can I get any help in this.

You have not included what back end system you are using, which is relevant information. However, with PHP and ASP.NET MVC I've discovered a similar behavior. I believe you are describing disabled/readonly inputs sending null values to the back end controller. In the past, I've found that I had to re-enable inputs with Javascript before submitting them to the controller. The jquery to do this is:
$("input[type='submit']").click(function(e){
e.preventDefault();
$("input").removeProp('readonly');
$("form").submit();
});
However, if the field is always static, you may just want to hard code it on the back end.
I'd also recommend you check out the w3 specification on disabled elements to make sure the readonly attribute is the correct attribute for you. You are currently using the readonly attribute incorrectly, as it is a boolean attribute.
<input readonly="readonly">
should be:
<input readonly>

Related

How to Completely Prevent Web Form Input Text Item change

I have this simple web-form
<form id="MyFormDiv" method="post">
<input type="number" name="cmp_no" id="id_cmp_no">
<input type="text" name="cmp_lname" maxlength="40 id="id_cmp_lname">
<input type="submit" name="submit" value="Save" id="submit-id-submit">
</form>
and this form will be used for both add and update.
When insert I have no problem, but when update I don't want to allow user to update or change the value of item which its id= "id_cmp_no"
I used javascript code to set its readonly property to true but that was not the 100% solution, because user can use browser inspect tool and see page source and change it's value before submitting the form, and therefore the readonly property is not useful.
Can I override it's onchange event to prevent change of it's value even if the value changed from page source using inspect tool.
Any one can help, thank you in advance
There is nothing that stops a user from changing values in browser, u can try solutions given in the above answers but be cautious user can dig out number of ways to do so like by using firebug/inspect element/ what ever..
What we can do is checking our values on server side and prompting user if they mismatch.
Shouting again ..
Never trust/depend on client....
If a user is skilled enough to open dev tools and change values from there, chances are they can also alter any JS code that prevents editing the readonly value.
So, there is no substitute to proper server-side validation.
You could check that the value is not being altered from the form's onsubmit event handler (see below), but keeping in mind what I and many commenters stated above.
$("form").on("submit", function(e) {
//check value of the input
if(this.someInput.value != 1) {
//do something here
//return false; if you want to block submit
}
return true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="number" name="someInput" readonly value="1"/>
<button type="submit">Submit</button>
</form>

How to override Parsley JS focus behavior

When a new user comes to the page and types in an email that already exists in the system, I would like to do the following:
Show the error message.
Show the arrow.
Then move the focus(cursor)
to the Password field.
Using jQuery I'm able to move the focus to the password field, but after a few milliseconds, the focus is pulled back to the email field with the Parsley error message.
I have tried using data-parsley-focus="..." and data-parsley-no-focus, but that didn't do anything for me. I've also looked at the source code and I see that validate.focusedField.focus() is what's forcing the focus back to the field with the error, but can't quite figure out how to stop that.
So, is there a way to override this behavior?
The following code works as expected, although you might need to tweak some aspects based on your code.
What I did:
Whenever a field has an error, check if it's a specific field (field1 in my case) and, if so, do something (in this case, focus on field2 input).
Add data-parsley-focus="none" to the form to avoid auto focus on the first input with errors (behaviour by default).
$(document).ready(function() {
$.listen('parsley:field:error', function(parsleyField) {
if (parsleyField.$element.attr('name') === 'field1') {
$("input[name=field2]").focus();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.0.7/parsley.min.js"></script>
<form id="myForm" data-parsley-validate data-parsley-focus="none">
<input type="text" name="field1" required data-parsley-minlength="50" data-parsley-trigger="focusout" />
<input type="text" name="field2" required />
<input type="submit" />
</form>
If you run into some trouble, please provide a fiddle and add the relevant code to your question.

Form validation clears JavaScript field

I am using a SEAM based JSF web application. I have a simple form that includes a lookup (pop up window) that retrieves a Category name and ID (both are retrieved with no issues and are stored in myView). When the look up returns, the Category name is used to populate "selectedCategoryName" (using Jquery).
The issue comes when you try to submit the form, and another field fails validation (simple required field missing). All of my other fields remain unchanged, but selectedCategoryName is cleared (even though the bean still has it's value, so fixing the validation error and resubmitting resolves to a proper submit). So my question is, how can I maintain showing the value that's in "selectedCategoryName" when the form validation fails?
Thanks in advance!
<s:decorate id="selectedCategoryField" template="/layout/edit.xhtml">
<span>
<h:panelGroup rendered="#{! myView.persisted}">
<img class="lookup" src="${request.contextPath}/images/lookup.gif" width="15" height="14" alt=""
title="Category Lookup"
onclick="return openNewWindow('${CategoryLookupUrl}?#{myView.lookupParameters}', 'id');"/>
</h:panelGroup>
<h:inputText id="selectedCategoryName" required="true"
value="#{myView.selectedCategoryName}"
size="50"
readonly="true">
<a:support event="onchanged" reRender="selectedCategoryField" ajaxSingle="true"/>
<a:support event="oninputchange" reRender="selectedCategoryField" ajaxSingle="true"/>
</h:inputText>
</span>
The problem is, that actually the bean does not hold the selected value because of readonly="true". When you apply that property to an UIInput the UIInput will not be processed on a submit.
To fix this you can do the following:
If you use JSF2 you can use readonly="#{facesContext.renderResponse}" instead.
If not, define a method isReadonly on your backing bean and use readonly="#{myView.isReadonly}".
public boolean isReadonly() {
return FacesContext.getCurrentInstance().getRenderResponse();
}
Have a look at the following similiar question and especially the answer for more details on why this works:
Data in <h:inputText readonly="true"> disappears when command button is clicked

Angularjs Form/Field validation using JavaScript function without directives

Is there a way to validate a field in angular without using a directive?
For example: I want to make following validation on an input field.
If field is empty we should show "Field must contain a value" message.
if field contains alpha Numeric characters we should show "Field can contain only digits".
An EVEN number - message to the user "Value must be an even number".
I want to make following validation in a call to JavaScript function.
I googled around and saw that there is a way to use ng-valid and $error , however I was not managed to make it work.
Code below is according to one of the answers I got:
<div ng-app>
<form name='theForm' novalidate>
<input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/>
<span ng-show='theForm.theText.$error.pattern'>Field can contain only digits</span>
<span ng-show='theText.length<1'>Field must contain a value</span>
<span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>Value must be an even number</span>
<br/><input type='submit' value='Submit' />
</form>
I want to take what inside the last [span] and put inside a JavaScript function in order to make it more generic and eventually change only JS and not the HTML when conditions are changing
Can someone please advise? a working example would be great.
I'm surprised no one has mentioned ui-validate
$scope.isOdd = function($value){
return $value % 2;
}
...
<form name="myform">
<input ng-model="myVal" name="value" required
ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
<pre>{{myform.value.$error|json}}</pre>
</form>
Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)
Here's a working demo
Take a look at the angularjs form documentation - http://docs.angularjs.org/guide/forms . In general, it is based on the HTML5 attributes like required, min, max, etc.
To get, for example, your first requirement done - "an empty field should show "Field must contain a value" message, yo uwould do something like that:
<input type="text" ng-model="user.name" name="uName" required /><br />
<div ng-show="form.uName.$invalid">
<span ng-show="form.uName.$error.required">Field must contain a value.</span>
</div>
For digits only field you can use the pattern attribute with a matching regular expression (example: http://www.wufoo.com/html5/attributes/10-pattern.html).
For even number validation, I'm not sure - I think you'd have to go with custom validation for that (meaning you'd have to create a directive) or use the pattern attribute somehow.
Last but not least - remember to add novalidate to the <form> tag. Otherwise the browser will try to validate your fields as well and you don't want that:
<form ... novalidate>
...
</form>
I know the question is old and I know you didn't want a directive but you may consider using a directive if it's "Angular" way... Well here is my Angular-Validation. I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... It is so crazy simple, you need 2 lines 1 line of code, 1 line for the input, 1 line for error display, that's it... never more and never less!!! Enough said, let's give some examples:
<!-- example 1 -->
<label for="input1">Email</label>
<input type="text" validation="email|min_len:3|max_len:25|required" ng-model="form1.input1" name="input1" />
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
So I can define whatever amount of validation rules (already 25+ type of validators) which I want in a simple directive validation="min_len:2|max_len:10|required|integer" and the error message will always display in the next <span> Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur and onkeyup. Oh and I also support multiple localization languages via JSON external files. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that a little extreme) when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
UPDATE
Another candy bonus! To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000" to make a 5 sec. timeout. Full example:
<input type="text" ng-model="form1.input1" typing-limit="5000" validation="integer|required" name="input1" />
<span class="validation text-danger"></span>
UPDATE #2
Also added input match confirmation validation (ex.: password confirmation), here is a sample code
<!-- input match confirmation, as for example: password confirmation -->
<label for="input4">Password</label>
<input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required" />
<label for="input4c">Password Confirmation</label>
<input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required" />
UPDATE #3
Refactored the directive so that the requirement of having a <span> to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.
DEMO
Added a live demo on Plunker
Well you can try to create a func
<span ng-show='isEven(theText)'>Value must be an even number</span>
$scope.isEven=function(data) {
if(data) {
return data%2===0
}
return true;
}
The method can either be defined on the current controller scope or on $rootScope.
Not a very angular way, as directives would be better but i think it would work.

Long form validation in JavaScript / jQuery

I have a long long long form. It has about 200 fields. Now, about 50 fields need to be validated through JavaScript / jQuery. How can I easily validate them without a huge amount of code. I want to avoid doing this:
field1 = document.getElementById("field1").value;
if (field1 == '') {
alert ("Please enter a value for Field1");
return false
}
Is there an easier way? Thanks a lot.
Use the jquery Form validation plugin and assign the correct classes to the fields.
It's as simple as class="required" in most cases!
If you just want to check if the field is empty or not you could do something like this using jQuery:
HTML:
<form>
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
</form>
SCRIPT:
$('.validate').each(function() { //this will get every input marked with class "validate"
if ($(this).val() == '')
return false;
});
Using JQuery validate plugin can be much help. You can control the way plugin works from your HTML code and even not write any javascript! If you need more complex validatio, you can extend it by adding specific validation functions. It allows you to localize the application as well.
This page gives a good example on how to use the plugin: http://jquery.bassistance.de/validate/demo/milk/ (click the "Show script used on this page" link).
Here is a rudimentary fiddle, that you can use to validate your form, Just add a span after each of the fields that you need to validate.
http://jsfiddle.net/refhat/h2S6G/35/
I thought about this too, but the plugin can be a bit difficult to
use. Do you know if it allows to display an alert box when an error is
found, instead of the actual displaying on the page? That's a bit too
much for this form. Thanks a lot
Here's a validator I wrote that uses a pop-up style alert box for error messages. Is that the sort of thing you are after?
http://validator.codeplex.com/
Do you want default error messages like for required validator? Regarding jquery validate plugin was it the syntax it offers to place validation information in the method call you found difficult since for a large form having validation information located separately from the text boxes makes it harder to go through and verify all fields have the right validators and messages?

Categories