I have a form master detail for tabular input and with enabledAjaxValidation=true
So far so good, the form validates all the rules and shows the error messages when submitting or changing any value of any control (onchange event). The problem comes when I add controls to the form using ajax, the latter do not behave like the original ones, they do not show the error messages.
The same when do submit with button
I think that
You need to add the newly created/added field to the validation manually for any dynamically created inputs using the yiiActiveForm.add() function.
You havent added the code you are currently using when you click on the button and add a new input to the form via ajax. So what you need to do is when you receive the response and append the input to the form just add the new input using the following code.
Note: Change the form and field attributes accordingly
$('#form-id').yiiActiveForm('add', {
id: 'input-id',
name: 'input-name',
container: '.field-input',
input: '#input-id',
error: '.help-block',
validate: function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {message: "Validation Message Here"});
}
});
Read more about the activeform valiadation js
Update
If you dont wish to add the validation function manually for every input and you have tabular inputs you can access any of the already created similar field and bind the validation function from it.
For instance in the above example if the the name field is tabular and belongs to the model Contact and you already have a name field populated in the form #contact-0-name you can use the yiActiveForm.find() function to access the attributes of that field and assign the existing validation. see an example below
var fieldAttributes = $("#form-id").yiiActiveForm("find", 'contact-0-name');
$('#form-id').yiiActiveForm('add', {
id: 'contact-1-name',
name: '[1][name]',
container: '.field-name',
input: '#contact-1-name',
error: '.help-block',
validate: fieldAttributes.validate
});
use somthing like below code
error: function(jqXHR,textStatus,errorThrown) {
stopLoader('.modal-content');
$('.csv_errors').show();
if(jqXHR.status==422){
var responseText = $.parseJSON(jqXHR.responseText);
$.each(responseText.errors,function(key,value){
$('.csv_error ul').append('<li>'+value+'</li>');
});
}else{
var responseText = $.parseJSON(jqXHR.responseText);
$('.csv_error ul').append('<li>'+responseText.message+'</li>');
}
}
Related
I need to pass in form variables via AJAX every time a select box value is changed, and get a returned string from the AJAX call to display on the page. Here's the situation:
I built a form which is dynamically built by the user for a set of compliance rules. This allows the user to have multiple select boxes to generate a logic statement such as the following:
(
( 6779 AND 10852 AND 10845 )
AND
(
( 8260 AND 8258 )
)
)
OR
( 6780 OR 10845 OR 8258 OR 12893 )
I've written a function that returns this logic statement as a string after submission of the form, but would like to dynamically populate a div (#logicblock) on the form page BEFORE submitting, so that the user can verify the logic before submission of the information into our database.
I tried to use the following:
('##logicblock').load("#getmodel('model.compliance').BuildLogic(rc)#", function(response){
$('##logicblock').html(response);
})
... but this does not properly pass in the RC scope into my model. I've searched and can't find a way that makes sense to me to send the entire form scope into a method that returns a value for display on the page.
I got it figured out. Because the form fields are dynamically generated, I found that I couldn't use a $('select').change() event to call the method, so I wrote a handler method to generate the data and serialized the form to pass in to the handler. I was able to use the following to get the desired response:
function updateLogicBlock(){
var serialform = $('form').serialize();
$.get("#event.buildLink('handler.buildComplianceLogic')#?" + serialform,
function(data) {
$('##logicblock').html(data);
});
};
Then I simply added onChange="updateLogicBlock();" to every select box on the form.
I have a function which does some custom work on form submit, send some data via Ajax, append the returned data in a new FormData object, now I need to submit the form conventionally (not via Ajax) with this FormData. I understand that it can be achieved with hidden fields, but what if I don't want the returned data to be visible to someone who knows a little bit of coding ?
So is it possible to submit a form with a custom FormData in jQuery without the hidden fields and Ajax ?
You could add your object into the form before submitting it and the remove it directly afterwards.
$('#yourForm').submit(function() {
$(this).append(yourCustomObject)
$(this).submit();
$(yourCustomObject).remove();
});
At the moment, as you cannot call the submit event from a FormData object is to:
intercept the original submit event preventing the default submit behaviour
copy the original form to a new FormData instance (everything will
be copied)
use jquery ajax or native XHR in order to call the server
action
Please note that the ajax call effect has the same of an ajax/xhr call, using the correct configuration.
I found the answer sort of from this answer. If you don't already have a form you can create one as in the other post. In my case I had an existing form so I handled it in the submit event.
$('form').on('submit',e => {
formData['caption'] = $('#caption').val()
formData['action'] = 'create'
$.each(formData,(key,value) => {
let field = $('<input></input>')
field.attr("type", "hidden")
field.attr("name", key)
field.attr("value", value)
$('form').append(field)
})
})
Just for reference I mutated the formData from another event in the document.
Keep in mind that the form will be submitted immediately after these fields are created as opposed to fetching that data and adding in as hidden fields on the form, so the data will not be part of the form for long before it is submitted.
I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
I've got this working successfully for my first input field - I would now like to extend this to a 2nd, 3rd etc input fields but want to try and avoid having multiple scripts that perform very similar functions. I'm new to jQuery and AJAX so learning the syntax as I go.
Here's my input fields:
Manager
Phone
Here's my Javascript that is working on the storeManager input field:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
I essentially need to branch and pass an additional POST parameter to the editProject.php script so it knows which database field to update, and then conditionally add a class to the appropriate row.
Everything I've tried breaks the script when I try and get it to branch or pass a parameter based on the input field that is being edited. I haven't been able to find any examples that show the correct syntax to have the one script that is called by different input fields - I'm presuming this is possible instead of having multiple versions of the same script acting on different fields.
This works for multiple fields. Just call the same function from different input fields. I just broke your code into two parts.
1. onChange function of each individual field, and
2. function call by passing the field parameters.
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){ yourFunction(this) }):
$("#worker").change(function(){ yourFunction(this) }):
$("#someX").change(function(){ yourFunction(this) }):
yourFunction(field)
{
var value = $(field).val();
var inputId=field.id;
$.post('editProject.php', { inputValue: value, id: inputId }, function(data) {
$('#'+inputId+'Row').addClass("success"); // (this looks like: *#storeManagerRow* ) you can change your Row id's accordingly to make your work easier. Eg: for **#storeManager** make this id as **storeManagerRow**
}).fail(function () {
// no data available in this context
$('#'+inputId+'Row').addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
</script>
You just try to post a value. for example type. Which should contain some value for identify the ajax call.
If it is for login, then add type = 'login'. Then check the value of $_POST['type'] and write php according to it
sample.php
if(isset($_POST['type']))
{
if($_POST['type'] == 'login')
{
//your code goes here
}
}
you can use this kind of code :
$("#storeManager, #Manager, #Phone").change(function(){
You could do something like this using :input or a class that they all have
$(":input").on("change", function(){
var text = $(this).val();
var idOfInput = $(this).attr("id");
//your post to php function using the above variables
});
From this you could post the id of the input to your php script using the idOfInput variable which you could then on the php side use a case switch to do a different query depending on which id is sent to the php
Here is a jsfiddle showing how it works
I have a dynamic form that is bound with knockout.js and validated by bootstrapValidator.
There is one input field that needs to be 'required-validated' dependent on the state of another control.
The input field:
<textarea id="inputReason" name="inputReason" rows="3"
class="form-control col-lg-8"
data-bind="value: Reason" />
The relevant javascript part of the knockout-viewmodel:
self.SelectAbsenceType = function (absenceType) {
self.SelectedID(absenceType.ID);
if (self.SelectedAbsenceType().ReasonRequired) {
$('#formCreate').bootstrapValidator('addField', 'inputReason', {
validators: {
notEmpty: {
message: 'Please enter a reason'
}
}
});
} else {
$('#formCreate').bootstrapValidator('removeField', 'inputReason');
}
}
The problem I'm facing is that a call to removeField of the bootstrapValidator instance doesnt seem to completely remove all registration infos since there is a javascript exception in the updateStatus method of the bootstrapValidator class that in fact should not be called at all since I have the removed the field before:
var that = this,
type = fields.attr('type'),
group = this.options.fields[field].group || this.options.group,
total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
The exception: Unable to get value of the property 'group': object is null or undefined
The variable field contains the value 'inputReason'.
So my Question is this (because the documentation of bootstrapValidators removeField is not entirely clear on this: How do I remove the dynamically added validation of the field inputReason completey?
(side note: can someone add the tag boostrapvalidator?)
Ok, after some digging it seems that the bootstrapValidator Plugin simply doesnt yet support the removal of validators that are attached to an input field that is NOT to be removed in the same process. Thus the events that are attached to the input field that trigger the validation are not unregistered.
A temporary workaround is to destroy the bootstrapValidator instance, set the data-* attribute of the form to null and reinitialize the plugin. This code replaces the bootstrapValidator.removeField() call:
bootstrapValidator.destroy();
$('#formCreate').data('bootstrapValidator', null);
$('#formCreate').bootstrapValidator();
update
Another even better way to get this done is to use the enable/disable feature of bootstrapValidator:
bootstrapValidator
.enableFieldValidators
(
'inputReason',
self.SelectedAbsenceType().ReasonRequired
);
(thanks to #nghuuphuoc for pointing this out)
I am having an aspx form and in that i need to do validations using jquery or javascript.
I just want to give a message near to the textbox if a user enter a value which is not valid in that textbox.Inorder to display the message in a popup [not alert('message')]
How can I find the position of the textbox in which user enters the invalid data or how can i display a message near the textbox using javascript or jquery ?
I need the validation occur in blur.So it is easy for user to know whether he entered a valid data immediately after giving the input.
Thanks in advance.I am not interested to use asp.net ajax validation and its callout extender.
I just want to implement a functionality which is similar to validation callout extender does.
When you bind the blur event to the textbox, you know which textbox it is. Just use your callback javascript to insert the error near by.
If you're doing jquery, it might look something like:
$('.my_textboxes').blur(function() {
var textbox = $(this);
//ajax validation call
$.post('/whereever', {}, function(response) {
//ajax callback
if (response == 'error') {
textbox.next().html(error); //something like this to insert the error into the next element after the texrbox, eg, a span to hold the error
}
});`
You can use the jQuery (ASP.NET) Validator Callout Plugin
You can use the jQuery validation plugin
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
Which has options to specify the message beside the control or to specify all the message at one place.
The demos are available at
http://docs.jquery.com/Plugins/validation
Exactly how you do this depends on the layout of your form, but in general you probably would do something like this: if the validation returns an error for a text field, check to see if an "error box" already exists for that field. If so, then just update its contents with the new error message; if not, then add the error element.
One way to do that would be to use a <span> tag with a particular class (for layout purposes), and an "id" value made from the input field's "name" or "id":
$.fn.setValidationResult = function(errorMessage) {
return this.each(function() {
var errId = 'errMsg_' + this.name, errMsg = $('#' + errId);
if (!errMsg.length) {
$(this).after($('<span></span>', { class: 'validation-error', id: errId }));
errMsg = $('#' + errId);
}
if (errorMessage)
errMsg.html(errorMessage).show();
else
errMsg.html('').hide();
});
});
Then you can just use $(yourInput).setValidationResult(whatever); with "whatever" being empty when validation passes.