I am working on an assignment for university. I need to make a simple form validation system with javascript. The problem is I can't get it right. The first if else statement works perfectly fine, however the second if statement does not work. However, if I copy and paste the second if statement in the console in the browser, it does work. If I try to copy and paste the whole if-else statements it once again does not work.
I have already tried looking at code in other examples but I can't seem to find the solution.
let nameForm = $('#name').val();
let age = $("#age").val();
let email = $('#email').val();
let city = $('#city').val();
if(nameForm != ""){
$("#name").attr("class", function(i, origValue){
return origValue + " is-valid";
});
}
else{
$("#name").attr("class", function(i, origValue){
return origValue + " is-invalid";
});
}
if(isNaN(age)) {
$("#age").attr("class", function (i, origValue) {
return origValue + " is-valid";
});
}
I have tried to remove all attr() and replace it with addClass(). This is the code I have now but still the class is-valid is not added with input age.
if(nameForm != ""){
$("#name").removeClass("is-invalid");
$("#name").addClass("is-valid");
}
else if(nameForm === "") {
$("#name").removeClass("is-valid");
$("#name").addClass("is-invalid");
}
if(isNaN(age)){
alert('test2');
$("#age").removeClass("is-invalid");
$("#age").addClass("is-valid");
}
The only error I got is this:
Failed to load resource: the server responded with a status of 404 (Not Found) But this is for the styles.css file and that file is empty.
Related
I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.
I am using the chatbot from liouh (https://github.com/liouh/chat-bot). When I attempt to return a URL, it gives me unrendered/raw HTML instead of a link. How can I return a rendered link given the Google scenario below? Thank you
function chatBot() {
// current user input
this.input;
this.respondTo = function(input) {
this.input = input.toLowerCase();
if(this.match('link to google'))
return "<a href='http://google.com'>Google.com</a>";
if(this.input == 'noop')
return;
return "I dont know the answer to '" + input + "'. You can teach me that via the link at the top of this page.";
}
this.match = function(regex) {
return new RegExp(regex).test(this.input);
}
}
It looks like in line 54 of index.js you need to change the code from
line.find('.text').text(text);
to
line.find('.text').html(text);
this will append the incoming reply as HTML instead of plain text.
Here is the Code that Manipulates the Birthdate and Age, If age is blank I get an error with the field's customized event. I can't seem to figure out why this JavaScript is throwing the "Cannot assign to a function result" error on a Event: onchange, when this error is appearing on form load. Is there a way to Allow the code to have no action if the Birthdate field is blank?
function birthdate_onchange()
{
var age = Xrm.Page.getAttribute("new_age");
var bDay = Xrm.Page.getAttribute("birthdate");
if (bDay.getValue() != null)
{
var now = new Date();
var thisYear = now.getFullYear();
var birthYear = bDay.getValue().getFullYear();
if((bDay.getValue().getMonth()-now.getMonth())>=0)
{
if((bDay.getValue().getMonth()-now.getMonth())==0 && (bDay.getValue().getDate()-now.getDate())<=0)
{
age.setValue(thisYear-birthYear);
}
else
{
age.setValue(thisYear-birthYear-1);
}
}
else
{
age.setValue(thisYear-birthYear);
}
}
else
{
age.getValue()=null;
}
}
I would love some feed back on this as I am new to JavaScript, but want to learn this language very much. Can provide more code or elaboration as needed, as this is just a segment of our Script for Contacts.
Thanks,
PGM
Edit 1 (5/20/2014):
Now that the Age/birthdate field changes are resolved, I am getting a 'fireonchange' object doesn't support property or method 'fireonchange'.
I have a feeling it is coming from this segment of code:
//TODO: could use to be upgraded to 2011 syntax
if (Xrm.Page.getAttribute("srobo_birthdatepre1900").getValue() != null) {
crmForm.all.srobo_birthdatepre1900.style.display = 'inline';
crmForm.all.srobo_birthdatepre1900_c.style.display = 'inline';
crmForm.all.birthdate.style.display = 'none';
crmForm.all.birthdate_c.style.display = 'none';
}
else {
crmForm.all.birthdate.style.display = 'inline';
}
try {
//Sets Age
//TODO: test if this works
Xrm.Page.getAttribute("birthdate").fireOnChange();
}
catch (err1) {
alert("Contact onLoad Error 1" + err1 + " " + err1.description);
}
try {
}
catch (err2) {
alert("Contact onLoad Error 2 " + entity + ": " + err2 + " " + err2.description);
}
} //end on load
I have been trying to switch the CRM 4.0 JavaScript Versioning to the 2011 friendly syntax, but I am still getting the error in my CRM. Could anyone show me where my problem areas are in terms of Syntax?
I have already switched this line:
Xrm.Page.getAttribute("birthdate").fireOnChange();
but still don't see why it would be throwing that fireonchange error?
Thank you so much for all the help so far! I really appreciate it!
Try to change line
age.getValue()=null;
to
age.setValue(null);
So I have a list of users registered on my site in 1 column, in the 2nd is their email address with a checkbox next to it. On this page a user can check the box (or multiples) and click a submit button. Once they do that it will generate a list of the emails semicolon separated.
My issue is after they hit submit the lists generates, but the first email address has "undefined" written right next to it.. so instead of saying "domain1#test.com; domain2#test.com" it reads "undefindeddomain1#test.com; domain2#test.com".
Here is my jQuery:
jQuery(document).ready(function() {
jQuery('#memberSubmit').click(function() {
var emailList;
jQuery('.email-members input:checked').each(function() {
var $this = jQuery(this);
emailList += $this.next('a').html() + "; ";
});
jQuery('.email-message').hide();
jQuery('.email-members').hide();
jQuery('.email-checks').hide();
jQuery('#memberSubmit').hide();
jQuery('.email-results a').attr('href', "mailto: " + emailList).fadeIn(2000);
jQuery('.email-results .email-list p').html(emailList).fadeIn(2000);
jQuery('.email-results h2').fadeIn(2000);
jQuery('.email-results p').fadeIn(2000);
jQuery('.email-list h2').fadeIn(2000);
//console.info('Emails: ' + emailList);
});
});
I think my error is on the line: emailList += $this.next('a').html() + "; ";
But I am not sure... any ideas?
Thanks!
Initialize the emailList the variable first, that means it doesn't start at undefined when you perform your first go around. Coincidently, when you're calling += for the first time, it's actually converting undefined to a string, thus meaning your string always starting with that.
var emailList = "";
Try replacing emailList's declaration with this code:
var emailList = "";
That's because emailList starts out as undefined if you don't initialize it. Therefore undefined + "this is a test" would turn out as undefinedthis is a test.
I have a Toogle function that uses to show/hide a div bloack to end users. However, some users said the IE generate an error when they clicks on this link. I am wondering whether I can use try catch statement in JavaScript to catach the error the users got and send to Googel Analytics.
If Yes, How I can do that. I have google analytcis set up in our site.
For instance, I have a div section call dynamic phone number.
<div id = "cs_DynamicForm">
"Phone number..."
<div>
When users click on Phone us link, i am able to track it in google.
<a onclick="javascript: pageTracker._trackPageview('/Contact/UK/phone');" id="phoneNumberToggle" class="more-info-link" href=" javascript:void(0);">Phone us</a>
In the back end, my toggle function works, like that
_dynamicPhoneNumber: function(type, arg)
{
var phoneNumber = document.getElementById("cs_DynamicForm");
var vis =phoneNumber.style;
//alert(vis);
if(vis.display==''&&phoneNumber.offsetWidth!=undefined&&phoneNumber.offsetHeight!=undefined)
vis.display = (phoneNumber.offsetWidth!=0&&phoneNumber.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
If i have to rewrite this function, i think it will look likes that:
try{
var phoneNumber = document.getElementById("cs_DynamicForm");
var vis =phoneNumber.style;
//alert(vis);
if(vis.display==''&&phoneNumber.offsetWidth!=undefined&&phoneNumber.offsetHeight!=undefined)
vis.display = (phoneNumber.offsetWidth!=0&&phoneNumber.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
catch (e)
{
var errorMsg=e.message;
if (typeof (e.number) != "undefined") {
document.write ("<br />");
document.write ("The error code: <b>" + e.number + "</b>");
}
if (typeof (e.lineNumber) != "undefined") {
document.write ("<br />");
document.write ("The error occurred at line: <b>" + e.lineNumber + "</b>");
}
//And send the errorMsg to google analytics. how I should do that
}
Any helps,
Cheers,
Qing
first catch the error simply like:
try {
tes.ting = 123;
}
catch(e) {
errors.push(e);
}
then push it to Google
_gaq.push(['_trackEvent', 'Testing', 'Error', errors.toString()]);
You can use the trackEvent as has been pointed here - but I believe the easiest way is to use trackPage, as you did for the other pages.
I use something like this:
try {
...
} catch (e)
{
pageTracker._trackPageview('/errors/'+e.toString());
}
You can replace 'errors/' with whatever makes sense to you ('virtual-errors-list/' for example).
In addition, consider adding the error tracking to window.onerror handler:
window.onerror = function(errorMsg, url, lineNumber){
pageTracker._trackPageview('/errors/'+errorMsg);
}