.validate() not working in jQuery Mobile - jquery-mobile

It is my first time using the plugin and .validate() method. Now I have a form and every time I click the submit button it runs with out doing the form validation. Here is my code:
<form class="form d" method="post" action="">
<input type="text" name="searchtitle" id="searchtitle" placeholder="Enter the textbook's title">
<input type="text" name="searchauthor" id="searchauthor" placeholder="Enter the textbook's author">
<input type="text" name="searchpublisher" id="searchpublisher" placeholder="Enter the textbook's Publisher">
<input type="text" name="searchedition" id="searchedition" placeholder="Enter the textbook's edition">
<select name="searchuniversity" id="searchuniversity"></select>
<select name="searchuniversitycampus" id="searchuniversitycampus" ></select>
<input type="submit" id ="searchsubmit" name="searchsubmit" value="Search">
</form>
I then have the following Javascript:
$(document).on('pageinit',"#searchpage",
//this funciton will carry out the things we need to do to carry out our search
function(e)
{
e.preventDefault();
$(".form.d").validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
comments: {
required: true,
minlength: 5,
nourl: true
}
},
messages: {
name: "Required Field",
email: "Valid Email Required",
comments: "Required Field + No URL's"
}
});
$("#searchsubmit").click(
function(e)
{
//Do a lot of processing here
});
});
Like I said I'm very new to doing the forma validation and using the function.
Here is a jsFiddle of the problem. When you click on submit in the fiddle it alerts "hello" and then it does the validation. How to stop this from happening. i.e validate first 1st and then run the function?

Your whole problem is your click handler. The plugin already has callback functions built in that will capture the click event of the submit button. Use the submitHandler to fire a function when the form is valid. Use the invalidHandler to fire a function when the form is invalid.
You already have the submitHandler callback in your jsFiddle so I refactored your jsFiddle code as follows:
$(document).on('pageinit', function(){
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true
},
field2: {
required: true
}
},
submitHandler: function (form) {
alert("hello"); // stuff to do when form is valid
alert('valid form submitted'); // for demo
return false;
},
invalidHandler: function () {
// stuff to do when form is invalid
alert("invalid form"); // for demo
}
});
// remove click handler
// use the plugin's built-in callback functions instead
//$("#test").click(function(){alert("hello")});
});
DEMO: http://jsfiddle.net/BTwaP/1/
See documentation for all callback functions
EDIT:
As of jQuery Mobile version 1.4, the pageinit event has been deprecated and replaced with pagecreate.
Good Reference: https://stackoverflow.com/a/14469041/594235

Related

why won't my jquery dialog fully fadeOut()?

When I call fadeOut on my dialog it only does a partial fade and leaves the grey header area where the dialog title is. I've tried removing the title as well as the various attributes that disable the exit button in the upper right corner of the dialog, but that didn't work. As you'll see in my script below, I want the dialog to close after the form submission has been validated.
//HTML
<div id="dialog">
<form id="form">
<p id="thanks">Please provide a contact number. It will only be shared with the
host</p><input id="number" name="number" type="text"/>
<button id="submit" type="submit">Submit</button>
</form>
</div>
//JS
if(myConditional){
//FORM IS HIDDEN ON PAGE LOAD AND SHOWN ON CLICK
$('form').show();
$('#dialog').dialog({
//These parameters are meant to disable the dialog close button
closeOnEscape: false,
beforeclose: function (event, ui) { return false; },
dialogClass: "noclose",
title: "Thanks For Volunteeering",
minWidth: 500
});
$('button').button();
}else{
//other code
}
//Validate the phone number before saving it to local storage
$("#form").validate({
rules: {
number : {
required: true
customvalidation: true
}
},
messages: {
number : {
required: "enter a phone number"
}
},
submitHandler: function(form) {
var number = $('#number').val();
localStorage.setItem('number', JSON.stringify(number));
//THIS FADE OUT ISN'T FULLY FADING THE DIALOG
$('#dialog').fadeOut();
} //closes submit handler
});//close validate
Ok I figured it out.
I got rid of the beforeClose parameter in the dialog init code, and in the form validation submit handler I added this:
$('#dialog').fadeOut('slow', function(){
$( this ).dialog( "close" );
});
//The fadeOut method has a call back function you can use with it to do something after the fade is completed.

Transfer Ajax data to hidden textbox in mvc

I have the folloing textboxes located in a form:
<input type="text" id="duration" name="duration" readonly="readonly" style="width:0px"/>
<input type="text" id="renew" name="renew" readonly="readonly" style="width:0px"/>
<input type="text" id="accountAfter" name="accountAfter" readonly="readonly" style="width:0px"/>
On form post these text boxes will pass the data to the controller retrieved from the following dialog:
$('#fixed').dialog({
autoOpen: false,
width:600,
resizable: false,
title: 'Fixed Account Details',
modal: true,
buttons: {
"Close": function () {
$(this).dialog("close");
},
"OK": function () {
$('#duration').val($('#duration').val());
$('#renew').val($('#renew').is(':checked'));
$('#accountAfter').val($('#accountAfter').val());
$(this).dialog("close");
}
}
});
Is it possible hide these textboxes from the user whilst still passing data?
Change them to hidden input elements. For example:
<input type="hidden" id="duration" name="duration" />
I think the rest of your code can stay the same, although I'm not really sure what you're trying to accomplish here; you're just updating the the values to themselves.
$('#duration').val($('#duration').val());
$('#renew').val($('#renew').is(':checked'));
$('#accountAfter').val($('#accountAfter').val());

Multiple Autocomplete box using same Ajax

I want to have two different Autocomplete boxes but both using the same AJAX method in the background.
Here is my script
$(document).ready(function () {
$("#SearchProject")
.each(function () {
var urlloc = "/Project/FindProjects";
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: urlloc, type: "POST", dataType: "json",
data: { searchString: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.name, value: item.name, id: item.id }
}))
}
})
},
select: function (event, ui) {
$("[id$='ProjectID']").val(ui.item.id);
// alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
// : "Nothing selected, input was " + this.value);
}
});
});
});
I want my input fields on the form as below.
<input id="SearchProject" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID" value="" />
<input id="SearchProject2" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID2" value="" />
When autocomplete select is complete I want the corresponding hidden field to be updated.
How do i achieve this?
Two possibilities:
First (the one I prefer): extract your auto-complete setup into a method:
function configureAutocomplete(autoField, updatedField)
You call this method for as many auto-complete fields as you want, passing it two JQuery selectors: the selector for the auto-complete field, and the hidden update field.
The other way is to base the ID of the hidden field on that of the auto-complete field. This will let you use an each to attach behavior to the fields, but I think it' more trouble than it's worth.

Custom validation handling with jQuery Datepicker

We have an instance of the jQuery UI DatePicker. When the built in validation fires--such as for an invalid date as shown below--the plug in inserts the message between the input and the calendar button.
<div><label for="optContractFinite">Contract Starts on</label></div>
<input type="radio" id="optContractFinite" value="OE" name="optContractDuration" />
<input type="text" class="isdatepicker" id="diContractStart" />
<div">Contract Expires on</div>
<input type="text" class="isdatepicker" style="margin-left: 20px" id="diContractExpires" />
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(".isdatepicker").datepicker({
showOn: "button",
buttonImage: rootPath + "/images/CalendarIcon.gif",
buttonImageOnly: true
});
});
</script>
Is there a way to call a custom function to handle displaying the message?
So what was causing that was not the datepicker rather the jQuery validator and it's default placement handler.
form_validator = $('form').validate({
errorClass: 'validationError',
ignore: '.optional',
onkeyup: false,
rules: {
diContractStart: {
required: '#optContractOpenEnded:unchecked',
date: true
},
diContractExpires: {
required: '#optContractOpenEnded:unchecked',
date: true
}
},
errorPlacement: function (er, el) {
if (el && el.length > 0) {
// er.insertAfter(el); <- The culprit
createErrorBubble(el, er.text());
}
}
});

JqueryUI Dialog. Unable to trigger from html form

Works fine with a text link to fire dialog - but lasts for about .5 second if triggered from an html form submit button. Sounds crazy! Yep, just cannot get it to work. Help!
$(document).ready(function() {
$('#rating-0').click(function() { $('#dialog').dialog('open'); }); $('#dialog').dialog({ autoOpen: false, height: 280, modal: true, resizable: false, buttons: { Continue: function() {
$(this).dialog('close'); // Submit Rating
}, 'Change Rating': function() {
$(this).dialog('close'); // Update Rating
} }
});
});
<form action="https://www.etc" id="rating-0">
<input type="hidden" name="cmd" value="_s-xclick" />
<input name="submit" type="image" src="https://www.paypal.com/en_GB/i/btn/btn_cart_LG.gif" />
</form>
<div id="dialog" title="Are you sure?">
<p>You've assigned the current celebrity a rating of 0…</p> <p>Perhaps you are just judging them on the terrible last movie…</p>
</div>
Add return false; to your submit or click handler to prevent the browser from submitting the form and reloading the page.
EDIT:
$(document).ready(function() {
$('#rating-0').submit(function() {
$('#dialog').dialog('open');
return false;
});
...
});

Resources