Validate a couple of dependent select lists with plugin jquery validate - jquery-validate

As the title said, I need to validate 2 dependent select lists with the jQuery Validator Plugin, to force website users to choose an option from all 2 fields (they have to become required fields).
If you see the html you can read a "disabled" tag on the second list, which will removed when user select one of the list1 option.
Here's the simplyfied code of the form
<form action="/index.php" method="post" id="XTspSearchForm132" >
<select class='sid_list1' name='to_sid_list_1321' id='extparent_1321' style='margin-top:4px;'><option style="" value="" selected="selected">- Seleziona categoria -</option><option style="" value="spc55" class="spc63" >Africa del Sud</option><option style="" value="spc56" class="spc63" >Nord America e Caraibi</option><option style="" value="spc57" class="spc63" >America Centrale</option><option style="" value="spc58" class="spc63" >Sud America</option><option style="" value="spc59" class="spc63" >Isole del Pacifico</option><option style="" value="spc60" class="spc63" >Oceano Indiano</option><option style="" value="spc61" class="spc63" >Penisola Arabica</option></select>
<select class='sid_list2' name='to_sid_list_1322' id='extparent_1322' style='margin-top:4px;'><option style="" value="" selected="selected" disabled="disabled">- Seleziona categoria -</option><option style="" value="spc62" class="spc55" >Botswana</option><option style="" value="spc64" class="spc55" >Mauritius e Seychelles</option><option style="" value="spc65" class="spc55" >Mozambico</option><option style="" value="spc66" class="spc55" >Namibia</option><option style="" value="spc67" class="spc55" >Zimbabwe e Zambia</option><option style="" value="spc68" class="spc55" >Sudafrica</option><option style="" value="spc69" class="spc56" >Anguilla</option><option style="" value="spc70" class="spc56" >Antigua e Barbados</option><option style="" value="spc71" class="spc56" >Aruba</option><option style="" value="spc72" class="spc56" >Bahamas</option><option style="" value="spc73" class="spc56" >Bermuda</option><option style="" value="spc74" class="spc56" >Giamaica</option><option style="" value="spc75" class="spc56" >Repubblica Dominicana</option><option style="" value="spc76" class="spc56" >St Lucia</option><option style="" value="spc77" class="spc56" >St Martin</option><option style="" value="spc78" class="spc56" >Turks and Caicos</option><option style="" value="spc79" class="spc56" >US & British Virgin Islands</option><option style="" value="spc80" class="spc56" >Canada</option><option style="" value="spc81" class="spc56" >Canouan Island</option><option style="" value="spc82" class="spc56" >Stati Uniti</option><option style="" value="spc83" class="spc57" >Belize</option><option style="" value="spc84" class="spc57" >Costa Rica</option><option style="" value="spc85" class="spc57" >Guatemala</option><option style="" value="spc86" class="spc57" >Messico</option><option style="" value="spc87" class="spc57" >Panama</option><option style="" value="spc88" class="spc58" >Equador</option><option style="" value="spc89" class="spc58" >PerĂ¹</option><option style="" value="spc90" class="spc59" >Hawaii</option><option style="" value="spc91" class="spc59" >Polinesia Francese</option><option style="" value="spc92" class="spc60" >Seishelles</option><option style="" value="spc93" class="spc60" >Mauritius</option><option style="" value="spc94" class="spc61" >Dubai</option><option style="" value="spc95" class="spc61" >Oman</option></select>
<input type="submit" id="XTtop_button" name="search" value="Search" class="buttonhome" onclick="this.form.sp_search_for.focus();extSearchHelper132.extractFormValues();"/>
</form>
Removing of "disable" tag probably depends to this script, loaded by the form: http://www.provafabio.netsons.org/modules/mod_sobiextsearch/js/jquery.chained.min.js
Now I'm using this script, which works for the first, but not for the second...
<script text= type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function () {
$j("#XTspSearchForm132").validate({
// other rules and options,
});
$j('.sid_list1').each(function () {
$j(this).rules('add', {
required: true,
messages: {
required: "your custom message"
}
});
});
$j('.sid_list2').each(function () {
$j(this).rules('add', {
required: true,
messages: {
required: "your custom message"
}
});
});
});
</script>
I need to find the syntax of action which activate the second list, to realize a script which works like this one jsfiddle.net/km6XE/ (sorry, can't post more of one link)
Here's the form in action: provafabio.netsons.org

I think the problem is in your "other rules and options" part of your example that you haven't included, as there is nothing wrong with your form or your JavaScript code
The error you describe is often encountered when you have specified a rule for a method that doesn't exist - have a look at this fiddle for an example
eg. this will give you the error you are seeing
$('#myform').validate({
rules: {
field1: {
non_existent_method: true
}
}
});

You do not use rules('add') within DOM ready if the input element does not yet exist.
This answer shows that when the user clicks a button one time, a new field called newfield is added to the form and then the rules are added dynamically to this new input field.
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
minlength: 5
},
field2: {
required: true,
minlength: 5
}
}
});
$('button#add').one('click', function () {
var field = '<input type="text" name="newfield" /><br />';
$('#myform').prepend(field);
$('[name="newfield"]').rules("add", {
required: true,
messages: {
required: "this new field is now required"
}
});
});
});
Demo: http://jsfiddle.net/km6XE/
You'll need to make sure your code creates a unique name for each new input or you'll break the Validate plugin.

Quote OP: "I need to understand: 1) how can i add rules to the first class
without using 'add' function 2) how can i add rules to a select list
which does not exist in DOM"
See the following:
"1) how can i add rules to the first class without using 'add' function"
If you want to assign those rules to many elements at a time by using their class, using rules('add') is acceptable. If you add rules by name, there are other ways. Again, since you are targeting by class, using rules('add') is acceptable here.
"2) how can i add rules to a select list which does not exist in DOM"
You can not add rules to something that does not exist yet in the DOM.
Inside whatever function is used to create the element is where you'd place your rules('add').
THIS IS JUST AN EXAMPLE:
IF you use a button to add an input element, you'd put rules('add') inside the click handler function. The same idea applies no matter how you add the new input. Since we can't see that part of your code, I'm sticking with my generic example below:
$('button#add').one('click', function () { // <-- WHATEVER FUNCTION YOU USE to add the new input
// THIS is just SAMPLE code that adds a new input element
var field = '<input type="text" name="newfield" /><br />';
$('#myform').prepend(field);
// NOW HERE, AFTER the new input is created, is where to add the rules.
$('[name="newfield"]').rules("add", {
required: true,
messages: {
required: "this new field is now required"
}
});
}); // <- end button#add click handler
Working Demo: http://jsfiddle.net/km6XE/
Essentially this is the same as my first answer.

Related

Select2 clone is working only twice

I'm trying to clone a select2 list and 2 text areas, but it's working only for the first clone, and I don't understand why..any new eye will certainly help !
(the cloning is OK, but the select2 is not applied to the 3rd clone)
HTML part
<fieldset>
<div id="test">
<div>
<label>Tool Name : </label>
<select class="toollist" name="FSR_tool_id[]" style="width: 350px" />
<option></option>
<option value="1" >bla 1</option>
</select>
<input type="Button" value="ADD ANOTHER TOOL" class="AddTool">
<label>Service Scope</label>
<textarea rows="5" style="width:99%" name="FSR_servicescope[]" class="validate[required]" />
</textarea>
</br>
<label>Service Description</label>
<textarea rows="10" style="width:99%" name="FSR_servicedesc[]" class="validate[required]" />
</textarea><hr>
</div>
</div>
<input type="hidden" value="0" id="countertool">
</fieldset>
JS part (I call jquery and select 2 before, of course)
$('#test .toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
$("input[type='button'].AddTool").live('click',
function() {
var index = $(this).closest('div').index();
if (index > 0) {
$(this).closest('div').remove();
} else {
$('#test .toollist').select2('destroy');
//we have to destroy the select2 before cloning
var $div = $(this).closest('div').clone(true);
$div.find('input.AddTool').val("DELETE THIS TOOL");
//to replace the button "add" by another "delete"
var $input = $div.find('input.exp');
var index = $('input#countertool').val();
var id = 'exp' + index;
index++;
$('input#countertool').val(index);
$input.attr('id', id).data('index', index);
$(this).closest('#test').append($div);
//then, we re-apply select2 to the lists
$('#test .toollist').select2({
placeholder: "Search your tool !",
allowClear: true
});
};
});
Any idea of my mistake ?
Thanks a lot in advance !
See this fiddle: http://jsfiddle.net/omugbdm1/3/ it's a bit of a mashup of code but should do the trick.
<div id="test">
<div id="tooltest0" class="tooltest0">
<label>Tool Name :</label>
<select class="toollist" name="FSR_tool_id[]" id="FSR_tool_id0" style="width: 350px" />
<option></option>
<option value="1">bla 1</option>
</select>
</div>
<div id="tool-placeholder"></div>
<div>
<input type="button" value="Add another" />
</div>
</div>
and
$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
$('input[type=button]').click(function () {
$('.toollist').select2("destroy");
var noOfDivs = $('.tooltest0').length;
var clonedDiv = $('.tooltest0').first().clone(true);
clonedDiv.insertBefore("#tool-placeholder");
clonedDiv.attr('id', 'tooltest' + noOfDivs);
$('.toollist').select2({ //apply select2 to my element
placeholder: "Search your Tool",
allowClear: true
});
});

how to validate a form without displaying any error messages

I do not understand how I can validate a form with jquery validate to display the Submit button or not.
My javascript is as follows:
ko.bindingHandlers.jqValidate = {
init: function (element, valueAccessor, option) {
var element = element;
var validateOptions = {
ignore: [":hidden:not(required)"],
focusCleanup: true,
onsubmit: true
};
function displaySubmitButton() { // Remove/Add class to submit button
if ($('form').valid()) $('.toSave').show();
else $('.toSave').hide();
}
$('form').bind('onchange keyup onpaste', function (event, element) {
if ($('form').valid() === true && $(element).not('.resetForm')) $('.toSave').show();
else if ($(element).not('.resetForm')) $('.toSave').hide();
});
}
};
My form :
<ol class="MutColor13 mouseOver" data-bind="jqValidate: {}">
<li class="rightCol">
<strong>
<label for="iEmailReply"><asp:Literal runat="server" ID="lEmailReply" /></label>
</strong>
<input id="iEmailReply" name="EmailReply" type="text" tabindex="2"
class="MutColor13 email"
data-bind="value: communication.Message.ReplyEmail, valueUpdate: 'afterkeydown'"
required="required" />
</li>
<li class="leftCol">
<strong>
<label for="iEmailFrom"><asp:Literal runat="server" ID="lEmailFrom" /></label>
</strong>
<input id="iEmailFrom" name="EmailFrom" type="text" tabindex="1"
class="MutColor13 email"
data-bind="value: communication.Message.SenderEmail, valueUpdate: 'afterkeydown'"
required="required" />
</li>
<!-- and more form input -->
</ol>
My submit button :
<div class="buttonBlock rightButton" data-bind="fadeVisible: validateMessage()">
<a class="MutButton3 toSave" data-bind="click: saveMessage"><span class="MutButton3">submit</span></a>
</div>
when I type "$ ('form'). valid ()" in the firebug console, all error messages appear. I do not think the submit button is the problem because I have not clicked at this point
How do I enable the display of the error message from the input short change while allowing the display of the submit button if fields (and any other form fields in the page) if all fields are valid?
I was inspired by this question: jquery validate: IF form valid then show submit button
a working demo : http://jquery.bassistance.de/validate/demo/
but the button is displayed continuously
ok I think this could work:
http://jsfiddle.net/Ay972/10/
what I did :
$('form').bind('change oninput', function (event, element) {
console.log('formLive :: ', $(event));
if ($('form').valid() === true && $(element).not('.resetForm')) $('.toSave').show();
else if ($(element).not('.resetForm')) $('.toSave').hide();
});
the 'change oninput' seems to work.

Bootstrap dropdown item binding with Ajax source

I have Bootstrap dropdown button, I want get data when user click this dropdown button instead of I need load country list at page loading time, here is my code;
<div class="btn-group">
<input class="text-box single-line" data-val="true" data-val-required="The Country field is required." id="Country" name="Country" type="text" value="US" />
<a class="btn dropdown-toggle country" id="country" data-toggle="dropdown">
<span class="caret"></span>
</a>
<ul class="dropdown-menu countrys" role="menu" aria-labelledby="dropdownMenu">
//store country list
</ul>
</div>
I click dropdown button, it can't trigger jquery work, it seems Bootstrap don't allow custom dropdown function.
$(document).ready(function () {
$('#country').click(function () {
// Only call notifications when opening the dropdown
if (!$(this).hasClass('open')) {
$.ajax({
type: "GET",
url: "/getCountries",
async: false,
dataType: "script"
});
}
});
});
You can try to add the ajax request inside the dropdown-open event. something like this:
$('#myDropdown').on('show.bs.dropdown', function () {
// do something…
})
show.bs.dropdow-- This event fires immediately when the show instance method is called. The toggling anchor element is available as the relatedTarget property of the event.

Kendo mobile template styling/formatting not working

I am trying to use a template as shown below, the outcome is a view with all elements from the template on one line, even though i am using to separate the elements. Why does this not display properly? It seems that no matter what styling i do it still ends up a single line view.
UPDATE
The culprit is the kendo style sheet - kendo.mobile.all.min.css -
So the new question for a kendo expert is why does kendo handle input fields differently when they appear in a listview via a template than when they appear outside of a template?
An input field outside of a listview template gets this class
.km-ios .km-list input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="image"]):not([type="checkbox"]):not([type="radio"]):not(.k-input):not(.k-button), .km-ios .km-list select:not([multiple]), .km-ios .km-list .k-dropdown-wrap, .km-ios .km-list textarea
Which results in no odd styling rules :) Normal text field view
An input field inside of the template gets this class
.km-root input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="image"]):not([type="checkbox"]):not([type="radio"]):not(.k-input):not(.k-button), .km-root select:not([multiple]), .km-root .k-dropdown, .km-root textarea
which results in these rules being applied to it (making the field sit in a wierd spot and loose all normal field stlying ie border background etc.) Im not 100% sure which wrapper is causing this
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
font-size: 1.1rem;
color: #385487;
min-width: 6em;
border: 0;
padding: .4em;
outline: 0;
background:
transparent;
My work around is to give any text fields inside listview templates the class="k-input" which obviously excludes them from the above css -
<script src="kendo/js/jquery.min.js"></script>
<script src="kendo/js/kendo.mobile.min.js"></script>
<link href="kendo/styles/kendo.mobile.all.min.css" rel="stylesheet" />
<!-- eventDetail view -------------------------------------------------------------------------------------------------->
<div data-role="view" id="view-eventDetail" data-show="getEventDetailData" data-title="eventDetail">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
<a data-align="right" data-role="button" class="nav-button" href="#view-myEvents">Back</a>
</div>
</header>
<form id="updateEventForm">
<div id="updateEvent">
<div id="eventDetail"></div>
<p>
<input type="button" id="eventUpdateCancelButton" style="width:30%" data-role="button" data-min="true" value="Back" />
<input type="submit" id="eventUpdateSaveButton" style="width:30%" data-role="button" data-min="true" value="Save" />
</p>
<div id="eventResult"></div>
</div>
</form>
</div>
<script id="eventDetail-template" type="text/x-kendo-template">
<p>
<input name="event_type" id="event_type" data-min="true" type="text" value="#= type #" />
</p>
<p>
<input name="event_loc" id="event_loc" data-min="true" type="text" value="#= type #" />
</p>
<p>
<input name="event_date_time" id="event_date_time" data-min="true" type="datetime" value="#= stamp #" />
</p>
<p>
Share this
<input data-role="switch" id="event_share" data-min="true" checked="checked" value="#= share #"/>
</p>
<input name="userID" id="userID" type="hidden" value="#= user_id #" />
<input name="eventID" id="eventID" type="hidden" value="#= event_id #" />
</script>
<script>
function getEventDetailData(e) {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://localhost/mpt/website/api/event_details.php",
dataType: "jsonp",
type: "GET",
data: { userID: e.view.params.user_id, eventID: e.view.params.event_id },
cache: false
},
parameterMap: function(options) {
return {
userID: options.userID,
eventID: options.eventID
};
}
},
schema: { // describe the result format
data: "results" // the data which the data source will be bound to is in the "results" field
}
});
console.log(e);
$("#eventDetail").kendoMobileListView({
dataSource: dataSource,
template: kendo.template($("#eventDetail-template").html())
}).data("kendoMobileListView");
}
//update event
function sendUpdateEvent() {
var siteURI = "http://localhost/mpt/website/api/update_event.php?";
app.showLoading();
var user_id = $('#userID').val();
var event_id = $('#eventID').val();
var event_type = $('#event_type').val();
var event_loc = $('#event_loc').val();
var event_date_time = $('#event_date_time').val();
var event_share = $('#event_share').val();
var formVals = 'eventID=' + event_id + '&userID=' + user_id + '&event_type=' + event_type + '&event_loc=' + event_loc + '&event_date_time=' + event_date_time + '&event_share=' + event_share;
var fullURI = siteURI + formVals;
$.ajax({
url: fullURI, dataType: 'json', success: function (data) {
$('#eventResult').html(data.results);
app.hideLoading();
app.navigate("#view-myEvents");
}
});
}
$('#eventUpdateCancelButton').click(function () {
app.navigate("#view-myEvents");
});
$('#eventUpdateSaveButton').click(function () {
sendUpdateEvent();
});
$('#updateEventForm').submit(function () {
sendUpdateEvent();
return false;
});
</script>
ListView widgets are supposed to be applied to <ul> elements.
Try changing:
<div id="eventDetail"></div>
to:
<ul id="eventDetail"></ul>
Also with this bit of code:
$("#eventDetail").kendoMobileListView({
dataSource: dataSource,
template: kendo.template($("#eventDetail-template").html())
}).data("kendoMobileListView");
The .data() call on the end isn't doing anything here and can be removed, and also you can pass just the text string as the template. You don't need to call kendo.template() yourself. So you can change that to just:
$("#eventDetail").kendoMobileListView({
dataSource: dataSource,
template: $("#eventDetail-template").html()
});

How to implement filter text from list box on char change in text box

How to implement Bing search like in wp7,i have list of data in list box by typing a char in text box i should able to filter the data from list.
Check autocomplete control from Silverlight Toolkit for Windows Phone (it's on codeplex)
In addtion to using AutoCompleteBox as argh mentioned, you should use CollectionViewSource
http://www.windowsphonegeek.com/news/wp7-Collectionviewsource-filtering
//JQuery:
//mobile - netbanking search
$(document).on('keyup', '#filter', function (e) {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val();
//Regex created to find value in list.
var pattern = new RegExp(filter, "i");
// Loop through the comment list
$(".list").each(function () {
// If the list item does not contain the text phrase fade it out
//Trim space from variable value.
var str = $(this).text().trim();
if (str.search(pattern) < 0) {
$(this).fadeOut();
//Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
JQuery Solution:
HTML will be:
<div class="yourlist">
<input name="" id="filter" type="text" placeholder="Search list" onkeyup="this.setAttribute('value', this.value);" value="">
<div class="list" style="display: block;">
Abc
</div>
<div class="list" style="display: block;">
xyz
</div>
<div class="list" style="display: block;">
qwe
</div>
</div>

Resources