Live data not submitting using MVC 4.5 unobtrusive validation - javascript

We have a form where a user can move items from one multi-select box to another. We are using MVC 4.5 and jquery validate with Microsoft's unobtrusive javascript.
The problem is, when submitting the form, the values within the select boxes don't get submitted because the user doesn't know after moving items that they have to also select all those items for submission.
So the solution sounds easy: use jquery to select all items upon submit.
After doing some research (thanks stackoverflow community), we were able to discover the necessary jquery code to intercept the submit process. However, the problem arises in that when the code selects the items, only pre-existing items in a select box are selected. Live (dynamic) items that have been moved do not get selected.
Here is the code that we first used:
$('#UserProfileForm').bind('invalid-form.validate',function(){
$(this).find('.selectbox option').each(function (i) {
$(this).attr("selected", "selected");
});
});
We discovered that using bind doesn't work but live should:
$('#UserProfileForm').live('invalid-form.validate',function(){
$(this).find('.selectbox option').each(function (i) {
$(this).attr("selected", "selected");
});
});
However, we are using jquery 1.9 and the live function has been removed. It has been replaced with this:
$(document).on('invalid-form.validate', 'form', function () {
$(this).find('.selectbox option').each(function (i) {
$(this).attr("selected", "selected");
});
});
However, this still doesn't work. So I replaced the selection function with an alert to see if it works at all:
$(document).on('invalid-form.validate', 'form', function () {
alert('test');
});
An alert does not pop up. Any ideas?
ADDITIONAL INFO
For those wondering why I'm referencing invalid-form.validate is because I am testing with invalid form data. The same scenario would apply if it was valid form data. I just haven't gotten to the point on how to bind live data to the valid form submission process either.

After inspecting the elements, I noticed that the jquery was adding the selected attribute to the options. However, the options weren't highlighted. This had me thinking that maybe the jquery call to add the selected attribute was wrong.
After some experimentation, I discovered that it was wrong. It appears that if you use the attr function of jquery, it doesn't actually set the option to selected in the DOM. Using the prop function does.
Here is the code:
$(document).on('submit', 'form', function (e) {
$(this).find('.selectbox option').each(function (i) {
$(this).prop("selected", true);
});
});
This allows the form to select all options as selected upon form submission whether the submit handler is valid or not. If you just want to select based on invalid info, use this:
$('form').bind('invalid-form.validate', function () {
$(this).find('.selectbox option').each(function (i) {
$(this).prop("selected", true);
});
});
Enjoy!

Related

Select the changes of a textbox that was disabled from code behind in jQuery

I have a page with a asp:textBox.
In my code behind (VB.net) in the Page Load, depending on such filters, i'm going to enable/disable this asp:textBox in this way:
this.txtB.Enabled = true;
this.txtB.Enabled = false;
In the moment that the user change the context of this asp:Textbox (only if it's enabled) i want to do some stuff, and so i thought to use jQuery in this way:
$('.txtB:enabled').on("propertychange input paste", function () { ... });
The problem is that, in some cases, the textBox that in the beginning was disabled had to become enabled too. And i do that always in jQuery:
$(".txt_PISocAppNom").prop('disabled', false);
But in this case when then the user change the context of the textBox, the previous method didn't catch the changes.
I assume that the problem derive from the fact that in my code behind i'm setting the ENABLE attribute and in jQuery the DISABLE attribut.
I don't know if my supposition is correct and in that case how to change the code to make it work.
Have you tried using 'live' instead of 'on'?
$('.txtB:enabled').live("propertychange input paste", function () { ... });
If your textbox is disabled at the beginning the selector '.txtB:enabled' won't apply to it so the change event will not get attached to it. Using 'live' will make sure that the event also gets attached for the future elements.
'live' has been deprecated in the new versions of jquery. In jquery 1.7+ you can also use $('.parentB').on("propertychange input paste", ".txtB:enabled", function () { ... }); to get the same result as 'live'. I'm using '.parentB' as a selector to get the parent of your textbox.
The problem was that i inserted the
$(".txtB:enabled").on("propertychange input paste", function () { ... });
in the
$(document).ready(function () { ... });
In that case, it was attacked in the early stages only to those items that were enabled. So, if my textbox was at first disabled, and enabled only later it hadn't the .on(...) property.

Select all options in multiple select before submitting form

I've created a widget with two html multiple selects - "available" and "selected". User choose items from "available" and they are displayed in "selected", pretty simple stuff. I'monly interested in "selected" values (the other one simply doesn't have a name attribute) but for it to send all values they have to be selected.
I tried to select them all in jQuery "submit" event but for some reason it doesn't work. I can see they are all visualy selected before the form is sent but the data itself is not sent.
var form = this.$selectedSelect[0].form;
$(form).on('submit', function(e) {
this.$selectedSelect.find("option").prop("selected", true);
}.bind(this));
I'd like to avoid creating hidden fields for each "selected" entry.
You should prevent the original submit process and invoke a new one after selecting all items like this:
var form = this.$selectedSelect[0].form;
$(form).submit(function(e) {
e.preventDefault();
this.$selectedSelect.find("option").prop("selected", true);
this.submit();
});
UPDATE:
You don't even need to prevent the default vehaviour, the following sinmple solution is already sufficient:
var form = this.$selectedSelect[0].form;
$(form).submit(function(e) {
this.$selectedSelect.find("option").prop("selected", true);
});
you need something like this
<script>
$(document).ready(function() {
$("form").on("submit",function(eve){
eve.preventDefault();
$("select#someSelectId").find("option").prop("selected", true);
$(this).submit();
})
})
</script>

Disable Submit button if none of selector options is selected

I would like to disable the Submit button on a search form that only contains select dropdowns. There are several similar questions here but I most of them deal with fields. The closest thing to my case is Disable submit button if all three of three specific dropdown fields are empty. I modified the solution supplied in JSFiddle to feature an empty option, and did get it working -- but only in JSFiddle, not on my page.
I use the same code from the proposed answer (only changed IDs):
$('#submit').attr('disabled','disabled');
$('select').change(function(){
if ( $(this).hasClass('require_one') ){
$('#submit').removeAttr('disabled');
}
});
$('#submit').click(function() {
$('#searchform').submit();
});
I add the above code right after I include the jquery.js (v. 1.9.1).
I generate the form dynamically, but in JSFiddle I use exactly what is seen in the page source: http://jsfiddle.net/cheeseus/d5xz6aw8/8/
I have no idea why I can't get it to work on the actual page, hope those more knowledgeable can help sort it out.
And, if possible, I would also like the Submit button to be disabled again if all three selects are set to blank values again.
I usually don't like using the ID(3) for CSS selector since you can have only one ID selector with that name on the document and there might be another element already with the same ID. How about using the class hierarchy instead to pinpoint the button element?
In any case you need to re-check the count everytime what you select on what is empty:
var $submitButton=$('.selector .btn');
var $selectors=$('.selector select.require_one');
$submitButton.attr('disabled','disabled');
$('.selector select.require_one').change(function(){
var $empty=$selectors.filter(function() { return this.value == ""; });
if ( $selectors.filter(function() { return this.value == ""; }).length == $selectors.length ){
$submitButton.attr('disabled','disabled');
} else
{
$submitButton.removeAttr('disabled');
}
});
$submitButton.click(function() {
$('#searchform').submit();
});
JSFiddle code here
You can just use a simple count to see if you should display the button or not. Here is jQuery code.
var count = 0;
$('.require_one').change(function() {
count++;
if (count >= 3) {
$('#submit').removeAttr('disabled');
}
});
$('#submit').attr('disabled','disabled');
I think this is because you didn't check is your document ready.
I added few improvements:
caching jquery object in variables, makes your code a bit faster (you don't look for it everytime select is beeing changes).
used recommended way of binding events - 'on' function
'disabled' is property not an attribute, jQuery has dedicated method to use
on select change - check all selects if there is any not selected, it there is - set prop disabled to true, otherwise set false.
instead of disabling submit at initialization, trigger same action you do when selected is beeing changed (if you start with option selected in all select initial state won't be disabled).
$(document).ready(function () {
var $submit = $('#submit');
var $selects = $('select.require_one');
$submit.on("click", function() {
$('#searchform').submit();
});
$selects
.on("change", function(){
var $not_selected = $selects.filter(function() {
return !$(this).val();
});
$submit.prop('disabled', $not_selected.length ? true : false);
})
.first()
.triggerHandler('change');
});

.focus() doesn't work on cloned object?

Hope you are all doing well!
So I have a form that contains list of input text in a row. the form can contains as many rows as possible as there is an 'add row' button that allows user to add dynamically
I use clone() to this 'add row' function and it's working perfectly
Next,each input in a row can only be edited if the corresponding checkbox is checked
I have put the code to the fiddle: FIDDLE DEMO
Now, when the checkbox is checked, we directly put the focus to the first input (which I defined the input class ='first'), once this input is filled, it directly focuses to the next input. and it's working fine, EXCEPT: if I add new row, the focus function doesn't work anymore.
My focus function is:
$("input").keyup(function (event) {
if ($(this).val() != "") {
$(this).next('input').focus();
if ($(this).next('input[type="text"]').val() == "X") {
$(this).closest('.me').find('input').focus();
}
}
});
Is that supposed to be that way? Or is there anything I need to add to the script?
Thanks!!
Use clone(true) instead of clone()
Code
var new_line = $('#content div.2dtme:last').clone(true).append();
DEMO
OR
You need to use Event Delegation. You have to use .on() using delegated-events approach.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
i.e.
$(document).on('event','selector',callback_function)
Example
$('form').on('keyup', 'input', function (event) {
//Your code
});
instead of
$("input").keyup(function (event) {
//Your code
});
DEMO

jquery click vs button executed function to find length of checkboxes

I am currently working with a JQuery function that determines if there are any checkboxes checked in my form. I'm using JQuery v1.10.2
This code works fine whenever I execute it with a button, but when I try to use a checkbox within the form to execute it, it does nothing. I've tested with a JFiddle, and that worked, but in my form, the alert does not fire. I've checked for redundant names, and my form id is unique. Could it be the div/table structures within the form causing some sort of conflict? The form is wrapped inside of a hidden div. Thanks for any help.
Below is the code:
<script>
$(document).ready(function(){
//$(".ksa_button_check").click(function(){
$(".ksa_check_k, .ksa_check_s").click(function(){
if ($("#ksaChecks input:checkbox:checked").length > 0) {
alert('is checked');
}
});
});
</script>
You could use something like this.
var checkboxes = $("input[type='checkbox']");
checkboxes.click(function() {
alert("Checkbox Is Checked");
});
http://jsfiddle.net/bowenac/aTDj6/1/
Not sure which language you are using. If you are using PHP you could check if $_POST has a value etc. If a checkbox is checked it would have $_POST data if not it would not.
Something like this.
if(isset($_POST['submit'])) {
$checkboxes = isset($_POST['checkbox']) ? $_POST['checkbox'] : array();
foreach($checkboxes as $value) {
Do something
);
};
};
Other than that I am wondering if your checkboxes are losing its state on your form submit. So yea as others said would help to see the code.

Categories

Resources