Using jQuery Validator for Empty Fields - javascript

I'm using the jQuery Validation Plugin to validate some forms, and I'm not able to quite get what I want when using with some inline table editing I'm coding. So I'm hoping someone here can shed some light.
I'm currently trying to validate for an empty or null input field. I can get it to work with the built-in rules such as "required: true" and stuff. But I can't seem to get it to validate the field if there's no data in it.
You can check out this Fiddle to see what I mean
(my last attempt was with the 'noempty' validator.addMethod)
What am I missing or overlooking?
Thanks!

Maybe try it with a function like this one to check if number of characters is less than one:
function notempty(id){
var value = $("#"+id).val();
var len = value.length;
if (len < 1){
return false;
}else{
return true;
}
}

I ended up retooling things quite a bit (other things outside my custom rules weren't working 100%), and I think I've now got it working now (I've updated my Fiddle in case it helps anyone else).

Related

Javascript checks if any text was entered on form submit is just not working

I know this is a very basic JS question and I apologize. I am very new to this. I must be making a mistake somewhere. Here is what I am working with:
HTML Form
<div class='nameinput'>Please enter your name:</div>
<input id='name1' placeholder='Name...' type='text'>
<input type='submit' value='Connect' class="submitForm">
</div>
Javascript Code
function store() {
name = $("input#name1").val();
}
function init() {
$('.submitForm').on('click', function(){
if (name === '') {
alert("Please Enter Name");
}
else
store();
$(".login_page").animate({
'opacity': '0' });
I am not sure what I am missing here. The name = $("input#name1").val(); works fine but I can't seem to get the if to work right. Could someone kindly explain my issue here?
The variable name is undefined in the scope. You need to get it when the button is clicked. Change your code to something like this:
function init() {
$('.submitForm').on('click', function() {
var name = $("#name1").val();
if (name === '') {
alert("Please Enter Name");
}
// rest of the code
}
Also, you don't need the function store if you're using it only to initialize the variable name. Additionally, the selector input#name1 can be simplified to #name1 as all elements in the page should have unique IDs.
I am still new and learning JavaScript in many ways, so don't worry.
First, you should always try to debug the problem as much as possible. One easy way to do that is simply putting in test console.log() statements printing out relevant values so you 1) know what is firing and when, and 2) what values they are working with. That'll get you out of a lot of problems like this.
Second, your if statement (if (name === '') {) I believe is the problem. You should look at this and ask yourself why isn't it working? Is your logical comparison written wrong? are you comparing the right things? What values are you comparing?
Your problem is: where is name defined? You use it in store(), but it pops up for the first time in init in that if statement. It's not defined prior to that.
So the first time it fires, that can't be true, and it goes to the else clause and then store() fires.
In this case, you've lost track of scope; where your variables are being defined.
The easiest solution is to add another statement to extract the value of the input you are trying to check and making sure it's not null/empty. For that matter, I don't think you need store() at all, unless you had some specific purpose for it.

Adobe Acrobat - Error Iterating Over All Fields in a PDF with JavaScript

I'm having trouble iterating over all of the fields in my document to remove the tooltip. Here's my code:
var index=0;
while(index<this.numFields)
{
var nom=this.getNthFieldName(index);
var fieldName=this.getField(nom);
fieldName.userName = "";
index=index+1;
}
I'm getting an error saying fieldName is null and my script won't run. I've seen this answer already:
Iterating over all fields in a PDF form with JavaScript
I get the same error with that code too. If I manually assign a field name to fieldName using var fieldName=this.getField("field1");, it works fine.
Does anyone have any idea why this would error on me?
Edit:
I can iterate over the list and output nom to the console so I know it's grabbing the names of the fields properly. It seems to have trouble dropping that name into the this.getField(nom) statement. No idea why...
Why use while… for this?
Doing exactly the same (setting the mousetip text to a blank string) is simpler using
for (var i = 0 ; i < this.numFields ; i++) {
this.getField(this.getNthFieldName(i)).userName = "" ;
}
and that should do it.
However, unless you have a very good reason, setting the userName to the blank string is not recommended; it is needed if your form is used with assistive devices, and it is also the very nearest and simplest help item.
I figured out my issue.
When I created the form, I used the automatic field detection to create my fields for me in order to save time (there are like 250 fields on this form). The reason I needed the script in the first place was to remove the crummy tooltip names that the feature generates.
Apparently, in its infinite wisdom, the field detection feature named a handful of fields with a leading space ( something like " OF INFORMATIONrow1"). Since getNthFieldName(index) returns the fields in alphabetical order, it was returning one of these broken fields and erroring immediately because getField() doesn't like the leading space in the name.
I renamed the handful of fields and the script works like a charm.

SSI Web javascript not working

I am currently having a problem with SSI's Custom Java Script Verification feature. I cannot make the program give me an error when a condition is not satisfied. I checked if javascript is enabled in my browser and it was. Also, I am sure to have it enabled in the survey. My code looks something like this:
var strErrorMessage= "";
var r1value = SSI_GetValue("q1_r1_c1");
var r2value = SSI_GetValue("q1_r2_c1");
if (r2value) < (r1value)
{strErrorMessage="error";}
However, when I put a smaller number in r2, it does not give an error and it continues on to the next question.
Any help is appreciated. Thanks in advance.
I think the last part should be
if(r2value < r1value)
Right now you have mismatched parentheses.

Hidden input field not being updated properly

I am trying to get the referrer and update the referrer so that my users can go back to the page they came back from. I have a hidden input field which holds the value of the redirect. I have a static value in there just in case the referrer is empty. If the referrer is not empty, I want to update the value of it. Here is the code I have written, I even tested it and it said it was updated, however, I am not being redirected properly, so it is not working.
JavaScript and HTML I have written (keep in mind, I have correctly linked the file and such):
$(document).ready(function(){
if (document.referrer != "") {
document.getElementsByName("redirect").value = document.referrer;
var test = "false";
if (document.getElementsByName("redirect").value == document.referrer){
test = "true";
}
alert(test);
}
});
<script src="js/referrer.js"></script>
<input type="hidden" name="redirect" value="https://www.google.com" />
I feel like this is a minor error or there might be some sort of standard I am not following.
Thanks for the help! I appreciate any insight!
I can't see what the problem is off hand by what you've given me. But what I can say is that if you are going to use JQuery in one place (document ready function) then you should also use it to grab the value of your input field.
It would also help if you put an Id on the input field instead of doing it by name. Ids are the best way to get a specific element. That could be your problem too.
Then call it using:
$("#ID").val()
so your code would become:
if($("#ID").val() === document.referrer)
I would also suggest using triple equals as well. But that is completely up to you.
I've never done anything with document.referrer, but there might be a better way of doing that as well.
One odd thing is that you are setting these 2 things equal to each other
document.getElementsByName("redirect").value = document.referrer;
and then immediately testing if they're equal to each other.
if (document.getElementsByName("redirect").value == document.referrer)
I can't say that this is your issue, but it's bad coding and should be fixed.
I think a single letter is tripping you up here.
if (document.getElement**s**ByName("redirect").value == document.referrer){
There's no singular equivalent for 'byName', so you do end up with an array (or at least, an array-like object). Unlike IDs, it is allowable for multiple inputs to have the same name. The easiest solution is this:
if (document.getElementsByName("redirect")[0].value == document.referrer){
Doing document.getElementsByName will return an object array that DOES NOT include the value. There is no way to change the value (That I know of and have tried) when using the getElementsByName. I have solved this issue by using getElementById, it actually works properly for me.

Breezejs Double trouble in angularjs

I am trying to change a value in a angular view from a integer to a float/double value that is bind to ngmodel. The input don’t except anything other than a integer.
My guess is that breeze does something in the background to validate the value or something on the "defined properties". But my knowledge of JavaScript prototyping is very limiting aka I need to learn it..
This is really hard to explain so I created a plunk that can hopefully help: http://plnkr.co/edit/Gcj0VvBE3f8DRbIjMtqt?p=preview
In the plunk I also added a normal object to test the same values and it is working as expected when changing the numbers to floats/doubles.
So the question is why won’t the value changed when binding to a float/double value from breeze?
I've checked a preliminary fix into GitHub for this. Please check it out and let me know if it works ( or not). We are still testing it.
This issue is caused by Angular's (new) behavior where if the angular digest cycle does not see a change to a model property then it seems to reset the UI to what it was on the previous digest cycle. So.. the idea behind this fix is to convince angular that the model value has changed even when it hasn’t.
and.. nice catch ( this was not obvious and your plunkr helped) :)
Ward adds: You must love the breeze team responsiveness :-) Jay jumped right on this and came up with an interesting solution. But please note the word "preliminary" in Jay's answer. We are discussing this "fix" internally and it may be withdrawn. Consider the zEquivalent directive in this new plunker or just wait until the dust settles.
Update 12 March
I found what I believe is a better solution for your use case because it does not involve "debouncing" nor any change to Breeze. See the zEquivalent directive in this new plunker
Reminder: the "best" resolution of the problem you discovered is still up in the air within the Breeze core team. You should not lock into a particular outcome until we can make a more definitive recommendation.
p.s.: I should have mentioned that Jay and I are on the Breeze core team. We are doing our best to get you out of a jam but sometimes we move a wee too quickly. Bear with us please.
This answer deprecated as of 12 March
Leaving it here for "historical" purposes.
I think you should try the zEquivalent directive first.
It is important to know that the Angular team is working on a robust extension to data binding that includes "debounce" which is still a good idea for many scenarios. See this (long) pull request thread on the Angular GitHub site.
Original Answer
Consider the zDebounce directive currently located in this plunker which is based on #qorsmond's second attempt.
I'd like to know your thoughts. I'm inclined to call this "the solution" and to add it to Breeze Labs. I'll update this answer when/if I do add it to the labs.
you can use input type="number" step="any" and hide the arrows using css
I tracked down the behaviour in the breeze code, when the value change it is intercepted and parsed:
var coerceToFloat = function (source, sourceTypeName) {
if (sourceTypeName === "string") {
var src = source.trim();
if (src === "") return null;
var val = parseFloat(src);
return isNaN(val) ? source : val;
}
return source;
};
So when the value change this function is called that parse the string to a float, the problem is as soon as the value entered is some number and a point like 5. it parse it to the number 5 witch is obviously correct. So you will never be able to get past the point.
When changing the input to a number type it works because its sourceTypeName is not a string.
Update
I ended up changing the breeze code to enable the decimal to be entered, I’m still not sure if I missed something but this works for me.
var coerceToFloat = function (source, sourceTypeName) {
if (sourceTypeName === "string") {
var src = source.trim();
if (src === "") return null;
var val;
if (src.indexOf('.', src.length - 1) !== -1) {
val = src;
}
else {
val = parseFloat(src);
}
return isNaN(val) ? source : val;
}
return source;
};
This doesn't work for large or small numbers that might be entered using an exponent form. If I want to enter 2.55e35 (a large salary ;)) the current implementation stops at the 'e'. Is there an easy way to fix this?

Categories

Resources