setting value of a text field using jquery still fetches validation errors from rails
I have a checkbox on my form. When clicked, it simply copies values from another textbox and puts the same value in another textbox. I use the following code to do this:
$('#box1').val($('#box2').val());
this works fine as on the form visually I see the data from box2
开发者_C百科 being populated in box1
. However, my rails validation still kicks in and says that box1 can't be empty. But visually I can see that it is not empty, because of the above code.
Is there something else that I should be doing?
Here is the detailed code:
$('#same_above_relation').change(function () {
if ($(this).attr("checked")) {
$('#box1').val($('#box2').val());
$('#box1').attr('disabled', 'disabled');
return;
}
//unchecked
$('#box1').removeAttr("disabled");
$('#box1').val("");
});
I think your problem is right here:
$('#box1').attr('disabled', 'disabled');
Disabled form elements are not sent to the server with the rest of the form:
Therefore, it cannot receive user input nor will its value be submitted with the form.
And so the value you set for #box1
never even gets to the model on your server. Perhaps you should try using the readonly
attribute instead of disabled
.
You could also use a before_validation
callback in your model to manually copy the box2 value to box1 before the validations are run. However, if you do this then it will always be copied even when your checkbox isn't set so you'd have to add in more logic to check the checkbox value inside your model.
精彩评论