Javascript syntax and behaviour in MS Dynamics - javascript

I have a form which I want to build some simple validation for, but I cannot seem to get it working correctly. The option set has about 10 choices, but I only want to create some validation for some of them. For example, if you are a certain race, a "specify" textbox will appear on the dynamics form to allow you to enter data, but the box will no appear if you make certain selections from the optionset. I hope I've explained that clearly.
Currently, the below code works as follows:
The other box is not visible on form load, when you make a selection from the optionset dropdown, it appears on the form and allows you to enter data. However, it should only appear if a certain choice is selected. When an incorrect choice is made, it should clear and become invisible again. At the moment, it stays visible and text the stays in the field. By default, the optionset has no assigned value on formload.
Code below, I think it must be my if statement is incorrect somehow.
function Example_Other() {
Xrm.Page.getAttribute("new_choiceoptionset").getValue();
if (Xrm.Page.getAttribute("new_choiceoptionset").getValue() == "White, Other
(specify)" || "Asian, Other (specify)" ||
"African, Other (specify)" || "Mixed, any other (specify)" || "Other ethnic group (specify)") {
Xrm.Page.ui.controls.get("new_othertextbox").setVisible(true);
} else {
Xrm.Page.ui.controls.get("new_othertextbox").setVisible(false);
Xrm.Page.getAttribute("new_othertextbox").setValue(null);
}
}

if statement works in a different way. You have to provide a boolean expression, so if you want to perform a check like this you have to do something like:
var myValue = Xrm.Page.getAttribute("new_choiceoptionset").getValue()
if (myValue == "White, Other (specify)"
|| myValue == "Asian, Other (specify)"
|| myValue == "African, Other (specify)"
|| myValue == "Mixed, any other (specify)"
|| myValue == "Other ethnic group (specify)")
{
//Your code here
} else {
//Other code here
}

I solved this issue by using the number value of the options, NOT the string assigned value... It's not ideal (as values could need changing over time) But it gives the desired functionality.
Example:
var myValue = Xrm.Page.getAttribute("new_choiceexample").getValue();
if (myValue == 778300002 ||
myValue == 778300006 ||
myValue == 778300009 ||
myValue == 778300014 ||
myValue == 778300015)
{

Related

Conditionally Disable/Enable submit button based on different field types in form

I have a form with numeric fields, text fields and drop down lists. I have implemented functionality were if a field is changed from original value then button is enabled for submit. If field is changed back to it original value button should(is) disabled.
PROBLEM: Current issue at the moment is
- if I change two different fields, then button is enabled as expected. But then if I revert only one of these edited fields back to its original value, submit button is disabled. Expected behavior is "as long as there's a changed field that is valid, then button should remain enabled for submit".
Conditions for button state
for all fields - if original value is changed and is not empty - enable button
for numeric fields - if entered/changed value is a valid number - enable button
*so if any of these conditions are not met, then button should stay disabled
Current Code
Current implementation and why it was implemented this way
$("input[name='q_description'],[name='q_sellprice'],[name='profit'],[name='grossProfit'],[name='markUp']").change(function () {
var originalValue = ($(this)[0].defaultValue);
var currentValue = $(this).val();
var changed = false;
var button = $('#submit-data');
//numeric fields
var sellprice = parseFloat($('#q_sellprice').val());
var profit = parseFloat($('#profit').val()); var grossProfit = parseFloat($('#grossProfit').val());
var markUp = parseFloat($('#markUp').val());
//text fields
var description = document.getElementById("q_description").value;
//alert("Numeric values:" + getFieldValues );
//$('input, select').bind('keyup change blur', function () {
if (description == "" || isNaN(sellprice) || isNaN(profit) || isNaN(grossProfit) || isNaN(markUp))
{
/*change background color to red for invalid or empty field*/
$(this).css("background", "#fd6363");
document.getElementById("submit-data").disabled = true;
}
else if ((originalValue != currentValue) ) {
/*change background color to yellow if value changed*/
$(this).css("background", "#FFE075");
document.getElementById("submit-data").disabled = false;
}
else if (originalValue == currentValue) {
/*original and current values match, reset background of that field to white*/
$(this).css("background", "#FFFFFF")
document.getElementById("submit-data").disabled = true;
}
else {
//to do
}
//});
});
On the first line, I dont have it this way
$("input[type=text]").change(function () {
because there is some fields on the form/page that I wanted to ignore for affecting the state of the submit button. That is why I have specified those particular fields on the .change
Also to check isNaN for the numeric fields. I probably can identify id the required fields by class names and add them to an array and just check that instead of the numerous declarations
var numericFields = document.getElementsByClassName("numeric_fields");
var getFieldValues = new Array();
for (i in numericFields) {
var singleValue = numericFields[i].value;
if (singleValue !== "" && singleValue !== undefined ) {
getFieldValues.push(singleValue);
}
}
but I had an issue, where the invalid check if statement part of the code wasn't getting hit with that implementation.
Anyways the main issue that I would like to solve at the moment, is to stop the button getting disabled when I revert one field back to its original value when multiple fields have been changed/edited to (from original) other valid states.
UPDATE
Further checks to clarify issue. I added an alert message message to see/check which if/else statement is getting hit each time any field is changed
if (description == "" || isNaN(sellprice) || isNaN(profit) || isNaN(grossProfit) || isNaN(markUp))
{
/*change background color to red for invalid or empty field*/
alert("1") //disable button
}
else if ((originalValue != currentValue) ) {
/*change background color to yellow if value changed*/
alert("2") //enable button
}
else (originalValue == currentValue) {
/*original and current values match, reset background of that field to white*/
alert("3") //default -> disable button
}
Now if a previously edited field is reverted back to its original value, while another has been changed, its hitting the last else statement alert("3), meaning the check is done per individual field that is currently being edited and not all the specified fields that I have specified from the form.

enable button when certain text fields have values

I have a form with several text fields and I would like the add button to be enabled when the required fields are filled in. The button is disabled by default in the HTML. In Firebug it appears the blur function fires but the that the if statement isn't reached.
$(".cd-form :input").blur(function(){
var ok=true;
$("#signup-firstnmame,#signup-surname","#signup-Address1","#signup-City","#signup-Postcode","#signup-Email","#signup-Mobile").each(function(){
/* if ($(this).val()==="")*/
if ($('#signup-firstnmame').val() !== "" && $('#signup-surname').val() !== "" && $('#signup-Address1').val() !== "" && $('#signup-City').val() !== "" && $('#signup-Postcode').val() !== "" && $('#signup-Email').val() !== "" && $('#signup-Mobile').val() !== "")
$("#AddData").prop("disabled",false);
else
$("#AddData").prop("disabled",true);
});
});
The commas are supposed to be a part of the selector, not separate parameters.
$('#signup-firstname, #signup-surname, #signup-Address1, ...
Also, if you're checking all of the fields, as in your if statement, you don't need to do that once for each field, it'll suffice to do it once.
If you would consider adding a class to the relevant fields, your function would be much more readable, i.e:
$('#AddData').prop('disabled', $('.required-field[val=""]').length > 0);
To Start, I think it would be smart to add a unique class to the inputs that you care about. this way you can do something along the lines of:
$('.yourClass').on('input', function() {
var x = true;
$('.yourClass').each(function() {
this = $(this); //cast it to jQuery obj (ez ref)
if (this.val() == "")
x = false;
} );
} );
Basically, every time someone enters something into the fields, jQuery will iterate through your inputs checking the values and adding 1 to x. If x is equal to the number of elements you are checking then it will enable the button.
This is not the most elegant solution but how I got around the same issue you were having when I was rushed into finishing a project.
Modified my answer with what #JaredT mentioned about the boolean, far more elegant. I am sure this could be improved further though, hope this gets the ball rolling.

How to filter div's based on text input and select inputs together

I have html page containing 70 or so divs, all with the same name, but each has different content within it. I am trying to make them searchable by filtering the content using jquery. I have it working already somewhat, you can see the page here:
http://smokefreehousingak.org/find-housing.html
The trouble I'm having is combining both the input from text, and the selects you see underneath the search bar. Right now the divs are filtered, but only per item, that is you cannot put a string in the text input, then change the value of the selects, and have it filter the divs based on all 3 or 4 pieces of data. It will only filter based on whichever input or select was last acted upon.
The jquery/javascript for the input filtering is thus:
function searchPage(searchQuery) {
$('.secondary-container').hide();
var searchQuery = $('#search-criteria').val();
console.log("search query is");
console.log(searchQuery);
$('.secondary-container').each(function(){
if($(this).text().toUpperCase().indexOf(searchQuery.toUpperCase()) != -1){
$(this).fadeIn(450);
}
});
console.log("page searched");
}
$('#search').click(function(){
searchPage();
});
$("#searchbox").submit(function() {
searchPage();
return false;
});
The HTML for each item being filtered is like so (just with different info in each one):
<div class="main-container secondary-container">
<aside id="filler-aside">
</aside>
<div class="main-content full listing">
<div class="main-content listing-picture" style="background: url('img/maps/image70.jpg') no-repeat center center;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cover;"></div>
<div class="main-content listing-data">
<h3>"Retirement Community of Fairbanks Inc."</h3>
<h3>Raven Landing</h3>
<p><span>Address:</span> 1222 Cowles St.<br>
<span>City:</span> Fairbanks<br>
<span>Zip:</span> 99701<br>
<span>Type of Housing:</span> Senior <br>
<span>Classification:</span> * Smoking is not allowed anywhere inside a building or complex</p>
</div>
</div>
</div>
The jquery/javascript for filtering divs based on one a select is like so (this is the code for the city select):
function citySelect() {
$('.secondary-container').hide();
$("#city-select").bind("change", function() {
console.log("city changed to");
city = $("#city-select option:selected").text();
console.log(city);
// searchPage(city);
$('.secondary-container').each(function(){
if($(this).text().toUpperCase().indexOf(city.toUpperCase()) != -1){
$(this).fadeIn(450);
console.log("text");
}
});
});
Right now I have each select with its own function thats called after its acted on, that then filters the divs based on the data selected. I think what I need is just one function that gets called anytime a select or input is acted upon, that will filter the divs based on all inputs or selects instead of statically choosing just one piece of data to work with.
Currently, the input search filter works by seeing if any div contains the text inputed into the field:
$('.secondary-container').each(function(){
if($(this).text().toUpperCase().indexOf(searchQuery.toUpperCase()) != -1){
$(this).fadeIn(450);
}
});
I need to somehow say if it includes searchQuery AND input data, etc... same thing when the inputs, I need basically this whole search function to act on all the data input not just one piece. Any suggestions?
You can do something like this:
function searchPage() {
var search = $('#search-criteria').val().toUpperCase();
var city = $("#city-select option:selected").text().toUpperCase();
$('.secondary-container').each(function(){
var text = $(this).text().toUpperCase();
$(this).hide();
if((!search || text.indexOf(search) !== -1) && (!city || text.indexOf(city) !== -1)) {
$(this).fadeIn(450);
}
});
};
I also added !searchand !city to make sure the result is shown if the string is empty.
Since the above ignores the selects if they are empty, but initially they have a default value of "Filter By...", I made a function that checks if the value of the select is "Filter By..." and if so, it sets the city variable to being empty, so that it will get ignored (via !search and !city), and if the value has been changed, then it executes how it normally would.
var search = $('#search-criteria').val().toUpperCase();
var city = $("#city-select option:selected").text().toUpperCase();
var cityStart = "Filter By City";
if(city.indexOf(cityStart.toUpperCase()) != -1){
console.log("city untouched");
console.log(cityStart);
var city = "";
console.log(city);
} else {
console.log("city not default");
}
$('.secondary-container').each(function(){
var text = $(this).text().toUpperCase();
$(this).hide();
if((!search || text.indexOf(search) !== -1) && (!city || text.indexOf(city) !== -1)) {
$(this).fadeIn(450);
}
});

JavaScript: changing input value using JavaScript?

I'm trying to do a very simple task but for some reason I can't do it.
basically I am using the if statement to change the value of an input field using javascript but it doesn't work!
this is my code:
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}
if (document.getElementById("colour").value == "db0000"){
document.getElementById("colour").value = "171515";
}
and the HTML looks like this:
<input type="text" id="colour" name="colour" class="colour" value="171515"/>
so what i need to do is this:
I launch a page and the input field is on my page with the value of value="171515", and then I press a button and that should change the value of the input field to value="db0000", and then I press the button again, and it should change the value of the input button to value="171515" and I need to do the same steps as many times as I want.
currently, it seems like it gets into a loop action and thats why it doesn't change the value of input field! (correct me if i'm wrong).
any help would be appreciated.
Thanks
EDIT:
The javascript code above is executed like so:
$(params.addPplTrigger).bind('click', function(e){
e.preventDefault();
///////// THE CODE ABOBE WILL GO HERE///////////
}
You're just missing an else:
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}
else if (document.getElementById("colour").value == "db0000"){
document.getElementById("colour").value = "171515";
}
What happens in your original code
Case 171515:
first if condition evaluates to true, because the value is 171515
value gets changed to db0000
second if condition evalutes to true again, because the value is db0000 now
value gets changed back to 171515
Case db0000:
first if condition gets evaluates to false, because the value is not 171515
the value remains the same
second if condition gets evaluates to true, because the value is db0000
value gets changed to 171515
So, in both cases you'd end up with 171515.
since you are doing :
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}
and then reverse
if (document.getElementById("colour").value == "db0000"){
document.getElementById("colour").value = "171515";
}
so you are not able to see the change .use else instead of second if.
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}else{
document.getElementById("colour").value = "171515";
}

Help me improve this Javascript codes limitations?

This Javascript which uses functions from jQuery is quite handy but getting feedback on it there is some limitations which I was hoping you guys could help me overcome.
The function basically creates a textbox with a formatted time (HH:MM:SS) so that it is easy for users to enter in times rather than have to use a date time picker which involves lots of clicks.
Code:
//global variable for keeping count on how many times the function is called
var i = 0;
//for adding formatted time fields
function timemaker()
{
//creates an input field of text type formatted with a value of "00:00:00"
var input = $("<input>",
{
name: 'time'+i, // e.g. time0, time1, time2, time3
value: '00:00:00',
maxlength: '8',
size: '6'
});
//this function which uses jquery plugin causes the cursor in the field to goto position zero
//when selected making it easier for the user to enter times and not need to select the correct position
input.click(function()
{
$(this).prop({
selectionStart: 0,
selectionEnd: 0
});
//this child function moves the cursor along the text field
//when it reaches the first ":" it jumps to the next "00"
}).keydown(function() {
if (event.keyCode == 9)
{
return;
}
else
{
var sel = $(this).prop('selectionStart'),
val = $(this).val(),
newsel = sel === 2 ? 3: sel;
newsel = sel === 5 ? 6: newsel;
$(this).val(val.substring(0, newsel) + val.substring(newsel + 1))
.prop({
selectionStart: newsel,
selectionEnd: newsel
});
}
});
//this appends the text field to a divved area of the page
input.appendTo("#events");
i++;
return;
}
00:00:00
Limitations I need help with
Say for example you wanted to enter a time of 12:45:00 , you
obviously don't need to enter the seconds part (last "00") as they
are already there. So you then decide to tab out of that text field
but the javascript interprets your "Tab" keypress as an entry and
deletes a zero from the field causing the value to be like 12:45:0
Does not validate inputs for 24 hour format- do you think it will be
possible to do that? e.g. first number you enter is "2" therefore the
only options you have are "0,1,2,3"
If you make a mistake in the 4th digit and reselect the text field
you have to enter everything again.
I think the main thing you're missing that would allow you to implement all those requirements is the argument that jQuery passes to you in your keydown event handler. So, change that line to this:
.keydown(function(event){
if (event.keyCode == 9) { return; }
... the rest of your code ...
and then you can use event.keyCode to identify what was pressed and take actions accordingly. So for example, if event.keyCode == 9 then the user pressed TAB.
This is a slightly out-of-the-box solution, but you might consider it if things don't work out with your filtered textbox:
http://jsfiddle.net/YLcYS/4/

Categories

Resources