how is my values not passing for ajax using trim and val. The issue is that when I check it using trim and val the values get check if there was anything typed if there is nothing then it sends to validation false if there is something it will hide the validate. All works bu the values do not make it and I get a new row without values. What am I missing from my function to pass my values. Here is the code:
var validation = "";
var values = {};
if ($.trim($("#name").val()) === "") {
$("#validateName").show();
validation = "false";
} else {
$("#validateName").hide();
}
if ($.trim($("#news").val()) === "") {
$("#validateNews").show();
validation = "false";
} else {
$("#validateNews").hide();
}
if(validation == "false"){
return false;
}
values['addnews'] = '';
$.ajax({
// Rest of the code //
This is how it was previously passed. Here is the code:
$.each($('#add-news-form').serializeArray(), function(i, field) {
if((field.value == 0)){
validation = "false";
}
values[field.name] = field.value;
});
What am I missing from my ajax function to pass the values?
If you want to assign the name input text to the values object, you can do it like so:
values['name'] = $.trim($("#name").val());
Ideally you shouldn't have this trim statement twice, you should store the trimmed value in a variable and use that variable in both your validation and assignment sections.
Then make sure you're passing 'values' in the data param of your ajax call:
$.ajax({
data: values
// rest of your ajax code
});
Related
I am storing form data in json format. To allow changing values from a previously created json file, the (plain old javascript) function below will load the values into a form from a file. This method will restore the value of drop down lists but not with a checkbox.
I have tried storing the value of the checkbox ('on' or 'off') and the checked state ('true' or 'false') but neither works out of the box.
Also, I tried adding an if statement before the return, like so:
if (newArr[dataItem] === "true") {
document.getElementById(newArr[dataItem]).click();
} else {
return (inputItem.id === dataItem) ? (inputItem.value = newArr[dataItem]) : false;
}
Here is a stripped down version of the function that works to restore values:
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
Object.keys(newArr).map(function (dataItem) {
inputs.map(function (inputItem) {
return (inputItem.id === dataItem) ? (inputItem.value = newArr[dataItem]) : false;
});
});
}
The json data would look like this:
{ "foo": "ws", "bar": "ws", "checkbox_value": "on", "other_data": "apple" }
So in short, when loading data from a file and evaluating the json dictionary, the checkbox_value does not seem to select or deselect the checkbox.
You need to update the checked attribute, and it needs to be set to the booleans true and false, not the strings. You should store the checked attribute as a boolean in the JSON. To load the values, consider the following code:
Object.keys(newArr).map(function (dataItem) {
var inputItem = document.getElementById(dataItem);
if (inputItem.type === "checkbox") {
inputItem.checked = newArr[dataItem];
} else {
inputItem.value = newArr[dataItem];
}
});
To check if at least one forem field has been filled out, among other solutions, I am considering the following solution:
var form = Ext.ComponentQuery.query('#myform')[0];
form.getForm().getFields().each(function(field) {
var value = field.getRawValue();
if(value !== ''){
//submit form
}else{
//error message
}
});
Since I have several forms that require filling in at least one field, I wanted to create a method in a Util file class and call this method in the controller; something like:
//Class Util
testFields: function(form){
form.getForm().getFields().each(function(field) {
var value = field.getRawValue();
if(value !== ''){
...
}
});
},
//controller
if(MyApp.util.Util.testFields(form) !== ''){ //does not work
//submit form
}else{
//error message
}
Is a solution like this feasible, or is it preferable to get the value of each field in the controller without iterating and testing if they are empty?
I would say, that your util method should return a boolean like
//Class Util
testFields: function(form){
var result = false;
form.getForm().getFields().each(function(field) {
if(field.getRawValue()){ // at least one field needs to be filled out
result = true;
}
});
return result;
},
Than your controller method should just test form like
//controller
if(MyApp.util.Util.testFields(form)){
form.submit();
}else{
//error message
}
So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});
Hi I'm trying to prevent this AJAX submit form function when a validation fails on one of one of the various inputs.
Edit: What I want to know exactly is what I need to include in //Adult age validation and var handleFormSubmit to stop saveForm($('#quotecriteria_form')); and performAjaxSubmit(formData, url); from occurring.
Submit function:
var handleFormSubmit = function( e ) {
e.preventDefault();
var $submit = $('button[type="submit"]');
$submit.addClass('loading');
// Save the contents of the form to session cookie
saveForm($('#quotecriteria_form'));
var formData = $('#quotecriteria_form').serialize();
var url = $('#quotecriteria_form').attr('action');
performAjaxSubmit(formData, url);
}
validation functions initialized:
IndexPageFunctions = {
init: function() {
//Validate date range
this.validateToDate();
this.validateFromDate();
//Validate adult age
this.validateAdultAge0();
this.validateAdultAge1();
this.validateAdultAge2();
this.validateAdultAge3();
//Validate child age
this.validateChildAge0();
this.validateChildAge1();
this.validateChildAge2();
this.validateChildAge3();
this.validateChildAge4();
this.validateChildAge5();
this.validateChildAge6();
this.validateChildAge7();
this.validateChildAge8();
},
One of the many validation functions:
//Adult age validation
validateAdultAge0: function() {
$('button[type="submit"]').on('click', function() {
var inputVal = parseInt( $("input[name='adultAges[0]']").val());
if (inputVal < 18) {
$("input[name='adultAges[0]']").css("border-color","red");
$("div#under18").addClass('show').removeClass('hidden');
}
});
},
Define a boolean array outside the scope of all functions with an index for each input element:
var valid = [false,false,false...];
Set the original value to false if blank input should be considered invalid or true if the field is optional. In each of your validation handlers (like validateAdultAge0) change the corresponding flag accordingly. For example if you decide to map the validity of age0 to the 0th index then:
if (inputVal < 18) {
$("input[name='adultAges[0]']").css("border-color","red");
$("div#under18").addClass('show').removeClass('hidden');
valid[0] = false;
}else{
valid[0] = true;
}
Like someone in the comments pointed out, if the logic is the same for each of these functions you should be using an argument to specify the target input, not creating an entirely new function but I won't get into that here.
In handleFormSubmit you'll just need to check if all the flags in the valid array are set to true, if any one is false you can return:
for(var i=0;i<valid.length;i++){
if(!valid[i]){
return;
}
}
I wrote javascript code and added it as a form on load event of entity(contact). In that Code I want to navigate from the opening form to another form.
For previous developments, I'm trying to get the id of the opening form which I need in order to navigate.
Code as shown below.
var id = Xrm.Page.ui.formSelector.getCurrentItem().getId();
if (itemid != null)
Xrm.Page.ui.formSelector.items.get(id).navigate();
Xrm.Page.ui.formSelector.getCurrentItem() function returns a null value. It doesn't get the item so I can't get the value. What's wrong with that code, what am I missing?
Thanks for replies in advance.
You are assigning the value to id variable but checking itemid in your IF condition.
In if condition just replace the if (itemid != null) with if (id != null)
To test your JavaScript. You can run following function:
var formItem = Xrm.Page.ui.formSelector.getCurrentItem();
if (formItem != null)
{
var itemId = formItem.getId();
var itemLabel = formItem.getLabel();
alert(itemId + " | " itemLabel);
}
else
{
alert("Unable to get current form");
}
Finally, to switch between form, following is very useful function which takes the form name as parameter. you can make changes to use form Id if you like.
function redirectToForm(formName) {
var currentForm = Xrm.Page.ui.formSelector.getCurrentItem();
if (currentForm != null) {
if (currentForm.getLabel().toLowerCase() != formName.toLowerCase()) { //make sure it's not already this form
var availableForms = Xrm.Page.ui.formSelector.items.get();
for (var i in availableForms) {
var form = availableForms[i];
if (form.getLabel().toLowerCase() == formName.toLowerCase()) {
form.navigate();
}
}
}
}
}
In My case, i prefer send the form name as parameter of a kind function such as constructor via load form function.
in the javascript code:
var Formname = "Default";
function Initialize(formname)
{
Formname = formname;
}
In customization of Form, in the onload function, you set this variable and this way remove the dependece from for selector component.
I hope that this solution can help many.
I took it up a notch and wrote the following post. You might find it interesting.
http://totbcrm.blogspot.co.il/2014/08/working-with-multiple-forms.html