JS HTML DOM typeMismatch error - javascript

I am using XHTML, JSF and JavaScript to create a form, validate the information that has been submitted into their respective fields through the use of a onclick() in a h:commandButton.
I have managed to create a JS file that checks for empty fields and alerts the user if true, that works fine. I next wanted to try to make sure that the input matches the type defined in the tag using the typeMismatch property, in a function i've called Validity. Here is my code so far:
function Validity() {
var checkName=document.getElementById("formdiv:cardName");
var checkCard=document.getElementById("formdiv:cardnumber");
var checkExp=document.getElementById("formdiv:expDate");
var error="";
var inputChecks=[checkName, checkCard, checkExp];
for (i=0; i < inputChecks.length; i++){
if(inputChecks[i].value.validity.typeMismatch){
error= "Your fields dont match the required input type. E.g Card Number must be a number"
}
}
document.getElementById("errorMessage").innerHTML=error;
}
My problem lies on line 48 where i get a "Uncaught TypeError: Cannot read property 'typeMismatch' of undefined'. I have only been coding JS for a week so am relative new to it, so I'm sure it's down to how I'm declaring/ referencing something. I've have already checked w3schools and other sources all to no avail. So I'm hoping someone here will be able to help. Any suggestions would be greatly appreciated

The only thing that we can discern from the code you've given and the error is that the 'validity' property hasn't been defined.
It's important to note the difference between null and undefinied in JavaScript.
Effectively the fact that it's undefined suggests that it's never been set. My guess would be that you have some problem where either the code that's setting the validity property isn't being executed, or it's behaving differently than what you'd expect.
If you add more information such as the rest of the code (JavaScript and XHTML) someone might be able to answer more specifically.
Truthy and Falsy values might also be useful to learn about as it's quite common for these sorts of things to unexpectely happen

Related

Accessing datetime-local value does not work. Can't figure out why

EDIT:
So, after more playing the problem is a bit more complex than originally thought, and while I have found a workaround, I'm curious to figure out why this is happening, so here's the update:
I have created the following function to fill in form fields using HTML DOM:
function populateField(fieldname, value) {
document.getElementById(fieldname).value = value;
}
Then in the main part of my php code, I call that function and hand it the ID of the field, and the VALUE I want to set like this:
echo('<script>');
echo('populateField("contact", "'.$fillContact.'");');
echo('</script>');
This works perfectly fine for all my form fields except for the datetime-local field. It simply doesn't work.
So I decided to bypass my function, and just set the field directly in the main part of the code like this:
echo('document.getElementById("arrival").value = "'.$fillArrive.'";');
This works perfectly fine...but ONLY if I execute it before I call my function for the first time. In other words...
THIS works:
echo('<script>');
echo('document.getElementById("arrival").value = "'.$fillArrive.'";');
echo('populateField("contact", "'.$fillContact.'");');
echo('</script>');
but THIS does not work:
echo('<script>');
echo('populateField("contact", "'.$fillContact.'");');
echo('document.getElementById("arrival").value = "'.$fillArrive.'";');
echo('</script>');
For the life of me I can't figure out why it would make any difference at all, but there you have it. If anyone sees something that I'm missing, I would love to know what I'm doing wrong!
Thanks all!
ORIGINAL:
So this is an interesting one. I have an HTML form field with multiple fields, including a datetime-local field. Using Javascript I am able to access and/or change the value property of all of the other input fields using HTML DOM, but for some reason, I am unable to access or set the datetime-local value property. Trying to read the value of the field returns a value of "" and trying to set the value has no effect.
Interestingly, if I include the value="some datetime" into the HTML tag itself, it sets the value property correctly. Thinking the value="" may have been somehow mucking things up, I removed it, but there is no difference.
Here is the field code within the form:
<input type="datetime-local" name="arrival" id="arrival" value="'.date('Y-m-d').'T00:00">
That works correctly and sets the field to the current date with a time of 00:00:00.000.
But if I do something like this afterwords:
x = document.getElementById("arrival").value;
Then x = "";
Likewise, if I attempt to set the field by doing this:
document.getElementById("arrival").value = [some datetime value];
the field remains blank.
Obviously, I'm missing something here, but for the life of me I can't figure out what. I even went to lookup an example. This example works fine, but even copying the lines it still doesn't work in my code:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_datetime-local_value
Ideas?
I'm afraid your value for date is not in correct format. You need to have ISO-8601 formated date as mozilla references it in online docs here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
var dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = '2017-06-01T08:30';
Also, if you not set value and try to console it, it's empty as expected, and after you set it, it yields same date in ISO format.
GL
function myFunction() {
console.log( document.getElementById("myLocalDate").value )
}
Date: <input type="datetime-local" id="myLocalDate" value="">
<button onclick="myFunction()">Console date</button>

Dynamics 365. Field value (javascript)

How can I get field value in Dynamics 365 with JavaScript?
In browser console function Xrm.Page() return undefined.
And when I try get some attribute like a
Xrm.Page.getAttribute("new_city").getValue();
receive error in browser console:
Unable to get property 'getValue' of undefined or null reference
There are two ways you can approach this issue
In the 'target' dropdown in the top right corner of your Developer Tools window, switch to 'Client API Wrapper'. You should then be able to access the form with your javascript code. Your syntax is correct.
Append the beginning of your code with frames at index 0
example:
var city = frames[0].Xrm.Page.getAttribute('bah_city').getValue();
Good luck!
It seems that you havent select the right frame, in the upper left corner of the console you should changed to customScriptsFrame and execute you code
Hope it helps.
Regards
Xrm.Page() probably isnt a method that exists. Try Xrm.Page instead.
For Xrm.Page.getAttribute("new_city"), are you certain:
The field is on the form.
The field name is spelt correctly.
Your code:
Xrm.Page.getAttribute("new_city").getValue(); should work.
Make sure you are using the Name exactly as it is seen in the Field Properties.
Possible reasons are given in other answers.
To avoid errors, always use null check.
if(Xrm.Page.getAttribute("new_city") != null)
var city = Xrm.Page.getAttribute("new_city").getValue();
If you are using this field in header, then use this:
Xrm.Page.getAttribute("header_new_city").getValue();
If you are using this field in Business Process Flow, then use this:
Xrm.Page.getAttribute("header_process_new_city").getValue();

What is a good way to change fields in livecycle-documents without triggering validations?

I got a form with lots of fields and many scripts so I broke it down to my very fundamental problem with this example:
Before printing I check if everything is filled out with:
Seite1.execValidate();
The validate XML source of the field:
<validate nullTest="error" scriptTest="error"/>
When clicking on the top-button I want different things to happen.
For example:
field.rawValue = "";
or (if it's a decimal field)
//isPauschal was set earlier to either true or false
field.value.decimal.leadDigits = (isPauschal)?"4":"2";
But then this happens:
Field goes blue (=it is empty) when setting its value to "" - this I want only to happen when I'm validating with the print-button.
Now I found a workaround:
field.mandatory = "";
field.rawValue = "";
field.mandatory = "error";
But if I were to write this every time I changed something that would trigger this my code would look pretty bad and much more confusing.
Can someone help me?
What could I do to easily validate my fields before printing and still being able to change them around with js at runtime without them making strange colors. ;)
I don't want to validate them individually - I wish to keep something like the execValidate() command so it automatically checks all the fields in a subform.
Let me know if you need any more information!

Can't access object in jquery (prevObject?)

A function in my WP plugin has just randomly (as far as I can tell) stopped working.
Here's the code in question:
window.send_to_editor = function(html) {
var classes = jQuery('img',html).attr('class');
var items = classes.split(" ");
... more stuff here
}
I've confirmed that the html variable is indeed an img html tag. Here's what firebug shows when I do a console.log of the object (console.log(jQuery('img',html));):
Object[]
context -> undefined
jquery -> "1.11.2"
length -> 0
prevObject -> Object[img.alignnone.size-full.wp-image-1234 name.jpg]
And the error it shows is classes is undefined.
I figure there's something wrong with the object I get, but this used to work recently and I'm not aware of any changes in the site that could have caused this.
I'd appreciate any input on this.
EDIT:
More info. This happens with two plugins which are supposed to be unrelated (made by different people). It happens when, after uploading an image to the server (or selecting a previously uploaded picture) you try to insert it into the post.
As I said before this error has appeared out of nowhere, it was working as intended a couple days ago. The only thing I can think of that has changed since then is the domain name, but I can't see how that could be related.
The jQuery selector always returns a jQuery object, but when the length is 0 then no elements were found matching the selector that you provided. In your example you've confirmed that nothing is selected as the length of the jQuery object is 0. Perform a check whether an element was selected like this:
var $els = jQuery('img',html),
classes;
if ($els.length) {
classes = $els.attr("class");
}
Keep in mind that your DOM query is limited by what you pass in as the html parameter. If you simply want to find the images on the page do: var $els = jQuery('img');
I finally managed to fix this; the key was parsing the html string variable into proper HTML, using jQuery.parseHTML(). Thanks to everyone who helped!

Is there anything wrong with this statement? (Javascript)

I would like to know if there is anything wrong with the below statement.
document.getElementById(monthId).options[document.getElementById(monthId).selectedIndex].value
Am asking this because, sometimes it seems to work fine and the rest of the time, it throws up an error - Object doesn't support this property or method.
BTW, monthId is the clientID of the dropdown present in a gridview in an asp.net page.
Thanks!
If no value is selected in the dropdown list, selectedIndex would be -1.
It's hard to evaluate without some more code as context. But without sanity checks around this line of code I would expect it to fail with an index out of bounds type exception when there is no selected index.
I tend to error check when using getElementById. I would expect that that is where your problem is.
Try this, and then test it in a debugger, but I will put an alert in.
var elem = document.getElementById(monthId);
if (elem.options) {
options[document.getElementById(monthId).selectedIndex].value
} else {
alert("elem doesn't have an options property");
}
You may want to not assume that the value property exists either, and do the same basic thing as I did here.
Once you get it working smoothly, where you know what is going to happen, you can start to remove the unneeded variables and go back to your original line, but for debugging, it is simpler to have one operation on each line and use separate variables, so that the debugger can show you what is happening.
You may want to understand the difference between undefined and null, and there are various pages on this topic but this one isn't too bad.
http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-2F00-EcmaScript.aspx
You can debug your problem by adding a breakpoint to your code in IE development tools, Firebug, Opera dragonfly or Chrome development tools and check your values.
Or you could add alert statements to check your values. Personally i think the code goes awry when selectedIndex is -1 (selectedIndex = -1 would occur when nothing is selected).
Check for yourself:
alert(document.getElementById(monthId)); // Returns null if nothing is found
alert(document.getElementById(monthId).selectedIndex); // If the selectedIndex is below 0 it could cause your error
document.getElementById(monthId).options[document.getElementById(monthId).selectedIndex].value

Categories