I am getting values from a model, but while checking the values it always goes in to the else part of the conditions. I am alerting the values I am getting and they are correct, but in the if condition it doesn't get satisfied. I even tried with ===.
$(document).ready(function() {
var mark = new Boolean(#Model.isMarketing);
var revenue = new Boolean(#Model.isRevenue);
var staff = new Boolean(#Model.isStaff);
if (revenue == true) {
$("input[name=isRevenue][value='isRevenue']").prop("checked", true);
} else if (staff == true) {
$("input[name=isRevenue][value='isStaff']").prop("checked", true);
} else if (mark === true) {
$("input[name=isRevenue][value='isMarketing']").prop("checked", true);
} else {
$("input[name=isRevenue][value='None']").prop("checked", true);
}
});
I assume that you're getting not true or "true" from #Model.isMarketing, #Model.isRevenue etc.
And never use the === in condition when you using new Boolean(true) it won't equal true with using ===.
I wanna suggest you several approaches:
1. Use !! instead of new Boolean(#Model.isMarketing);
e.g.
var mark = !!#Model.isMarketing;
2. Just remove new Boolean() and use if like:
var mark = #Model.isMarketing;
if(mark) {
//do smth.
}
else {
//do smth else
};
Also I wanna suggest how to improve your code.
$(document).ready(function () {
var trueMark = 'True';
var mark = trueMark === #Model.isMarketing;
var revenue = trueMark === #Model.isRevenue;
var staff = trueMark === #Model.isStaff;
var value = 'None';
if (revenue) {
value = 'isRevenue';
}
else if (staff) {
value = 'isStaff';
}
else if (mark) {
value = 'isMarketing';
}
$("input[name=isRevenue][value="+ value + "]").prop("checked", true);
});
Please, make sure that you're getting right values from #Model
Related
function myFunction() {
var showpass = document.getElementsByClassName('lpass');
if (showpass.type === "password") {
showpass.type = "text";
} else {
showpass.type = "password";
}
}
This script is not working. In console.log('') it is skipping to else condition directly.
Your var showpass = document.getElementsByClassName('lpass'); returns an array so use the 0 index to get the first match.
var showpass = document.getElementsByClassName('lpass')[0];
You can see more about the function here, https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
I'm getting an array of Strings, and if the array has items I want to do one thing and if not I want to do the other. I'm not sure how to check if the array is empty of not. Also when stepping through my code in chrome debugger even if the array has items in it the length is still 0 so I can't use formErrors.length > 0.
Here's my code for getting the errors. This works fine and returns an array of error strings or an empty array:
var formErrors = validateFormData(formData);
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
Then I want to do one thing if there's no errors and another if there is. But this is the bit that won't work for me.
if (formErrors !== {}) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
}
I've tried multiple ways and nothing has worked so far. Any help is appreciated, thank you!
EDIT
I can't use the .length on the array cause the length is 0 even when it has data.
Screenshot of chrome debugger
I'm slightly confused about what people are asking sorry, i'm not an expert here is my full code to get a better understanding of what i'm trying to do.
$(document).ready(function () {
$('#submit').on("click", onSubmitForm);
function onSubmitForm(event) {
clearErrorMessages();
var formData = getFormData();
var formErrors = validateFormData(formData);
if (formErrors) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
// Do other stuff
}
}
function clearForm() {
$('#title').val("");
$('#client').val("");
$('#date').val("");
$('#status').val("planning");
$('#description').val("");
$('.type').prop('checked', false);
$('.extra').prop('checked', false);
$('#title').focus();
}
function clearErrorMessages() {
$(".uk-text-danger").html("");
}
function getFormData () {
var data = [];
data["title"] = $('#title').val();
data["client"] = $('#client').val();
data["date"] = $('#date').val();
data["status"] = $('select#status option:selected').val();
data["description"] = $('#description').val();
if ($("input[name='type']:checked").length > 0) {
data["type"] = $("input[name='type']:checked").val();
}
else {
data["type"] = "";
}
data["extras"] = [];
$.each($("input[name='extras[]']:checked"), function(index, radio) {
data["extras"].push(radio.value);
});
return data;
}
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
function displayFormErrors(errors) {
for (var field in errors) {
var errorElementId = field + "Error";
$('#' + errorElementId).html(errors[field]);
}
} });
Sorry if this is too much i'm not sure what else to do.
An empty array, string or object is "falsy" in JavaScript.
That is, you can pass the array, string or object directly into the if conditional and it will run depending on if something is in there or not.
if ([]) {
// this will never run
}
if ('') {
// this won't run either
}
if ({}) {
// nor will this
}
var errors = {}; inside the validateFormData function.
And then compare the the object like this.
if (JSON.stringify( formErrors ) !== '{}') { //do something}else { //do something}
Where are you verifying if the formErrors is empty? This verification (the if-else) should be inside the function which submits the form.
Also try using:
if (formErrors.length > 0)
instead of:
if (formErrors !== {})
Here's the code:
eventOverlap: function(stillEvent, movingEvent) {
console.log("I am overlapping something");
if (stillEvent.tags == ""|| movingEvent.tags == "") {
console.log("One of the events have no tag");
return true;
} else {
console.log("SE = " + stillEvent.tags + " ME = " + movingEvent.tags);
$.each( stillEvent.tags.split(','), function( key, value ) {
var index = $.inArray( value, movingEvent.tags.split(',') );
var result = "";
if( index == -1 ) {
console.log("Found no similar tags");
result =true;
} else {
console.log("Similar tags at index:"+index);
result =false;
}
return result;
});
}
}
What I'm trying to do, is when I drag an event above another day that contains an event as well, this function will compare the tags string they have (by splitting them) and looking at each individually.
If one or both of the events have no tags, it is allowed into the day.
Else, each of these are supposed to be compared per element
say X=["1","2","3"] and Y=["3","4","5"] both of these has 3, therefore it should return false. But if it finds no similar elements, like X = ["1"] and Y = ["2"] it should return true. False will disable eventOverlap, and true otherwise.
So I checked with the console. What's happening here is that even if it knows that there are no similar tags, eventOverlap is still not enabled. Only when the other event has no tag.
Might it be a flaw on my logic? Thanks!
What about something like this?
...
eventOverlap: function(stillEvent, movingEvent) {
if (stillEvent.tags == ""|| movingEvent.tags == "") {
console.log("One of the events have no tag");
return true;
} else {
for (i = 0; i<stillEvents.tags.length; i++){
for(j = 0;j<movingEvent.tags.length,j++) {
if (movingEvent.tags[j] == stillEvents.tags[i]){
return false;
}
}
}
return true;
}
}
...
I have a simple form which users can enter a "tweet". I ahve some javascript behind the scenes to control what happens when a url is entered.
If a url is entered such as test.com then a new input field will appear.
If a url that is stored in an array is entered, it will and the new input field along with a select option.
here is my javascript:
var test = ["test1.com", "test2.com", "test3.com"];
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keydown(function () {
var val = this.value;
if (/\.[a-zA-Z]{2,3}/ig.test(val)) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
if ($.inArray(val, test) !== -1) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
});
It works fine if just a url is entered. But as soon as you add more text, it disregards if the url is in the array, and removes the select option. I'm not quite sure on how to explain this any better, so i have setup a fiddle to show what i mean.
I hope someone understands and can point me in the right direction
Fiddle
That's because you are checking if a whole input is in the array: if ($.inArray(val, test) !== -1). You need to retrieve URL from the input using a regex and check that.
Write a regex that retrieves any URL, get that URL and check if it's one of your lucky ones:
var urlsInInput = /[a-z0-9]+\.[a-zA-Z]{2,3}/ig.exec(val);
if (urlsInInput.length == 1 && $.inArray(urlsInInput[0], test) !== -1) {
instead of
if ($.inArray(val, test) !== -1) {
Fiddle
Here is my version handling the first url
Live Demo
$('#tweet_text').keydown(function () {
var val = this.value;
var urls = val.match(/[a-z0-9]+\.[a-zA-Z]{2,}/ig);
var alias = (urls && urls.length>0)
$('#custom_alias').toggle(alias);
var tweet = urls && urls.length>0 && $.inArray(urls[0], test) !== -1;
$('#tweet_campaign').toggle(tweet);
});
What #siledh said. Here is how you could use your current test array
var reg = new RexExp(test.join('|').replace(/\./ig, "\\."), 'ig')
if( reg.test(val) ) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
The reason the campaign field begins to disappear again is that you compare the whole value of the input with the array. If you just find all domain matches and then compare them to your array it should work.
Like so:
var test = ["test1.com", "test2.com", "test3.com"];
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keyup(function () {
var alias = false;
var campaign = false;
var domain = /([a-z0-9]+(:?[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})/ig;
var val = this.value;
var match = val.match(domain);
if (match) {
alias = true;
match.forEach(function(e) {
campaign = campaign || ($.inArray(e, test) !== -1);
});
}
if (alias === true) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
if (campaign === true) {
$('#tweet_campaign').show();
} else {
$('#tweet_campaign').hide();
}
});
Something wrong with your $.isArray(val, test), the value you use is the whole value.
And not sure your purpose, so write a code like this. hope it would help.
http://jsfiddle.net/sheldon_w/KLuK8/
var test = ["test1.com", "test2.com", "test3.com"];
var urlReg = /[^\s]+\.[a-zA-Z]{2,3}/ig;
$('#tweet_text_ga').hide();
$('#custom_alias').hide();
$('#tweet_campaign').hide();
$('#tweet_text').keydown(function () {
var val = this.value;
var matchedUrls = [];
val.replace(urlReg, function (matched) {
matchedUrls.push(matched);
});
if (matchedUrls.length > 0) {
$('#custom_alias').show();
} else {
$('#custom_alias').hide();
}
$(matchedUrls).each(function (idx, url) {
if ($.inArray(url, test) !== -1) {
$('#tweet_campaign').show();
return false;
} else {
$('#tweet_campaign').hide();
}
});
});
I am using this to detect errors on my form...
var error = false;
if (val === '') {
error = true;
}
if (error = true) {
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
Simple really but not working, am I missing something stupid? variable error is default false.
If an error is found it is true.
If error is found to be true it prevents the form being submitted?
var error = false;
if (val === '') { // <<< This checks type first, then value
// An empty '' variable is not type-equivalent
// to a (boolean) false value
error = true;
}
if (error = true) { // <<< You're setting a variable here, which means
// means that you're testing if the variable
// assignment itself is successful, you'll get
// a true result in most cases, and except with
// things like while loops, you shouldn't use this
// form.
// Maybe you want == (falsy)? Or === (type-checked)?
$('#joinForm .submit').click(function(event) {
event.preventDefault();
});
}
You should do the checking in the submit event handler:
$('#joinForm').submit(function(event) {
var error = false;
if (val === '') {
error = true;
}
if (error) {
event.preventDefault();
}
});