jQuery unobtrusive custom adapter and method in jsFiddle - asp.net-mvc

I cannot make this jsFiddle work but it works in the browser: http://jsfiddle.net/vtortola/jYq2X/
I am trying to add a new custom rule to compare two fields. The custom adapter works, it is being called and setting the options. But the custom method is never called.
I am executing this JS on DOM ready:
$.validator.addMethod("customequal-method", function (val, el, p) {
var $other = $(el).closest('form').find('input[name=' + p.other + ']');
return $other.length && $other.val() == val;
});
$.validator.unobtrusive.adapters.add("customequal", ["other"],
function (options) {
options.rules["customequal-method"] = options.params;
options.messages["customequal-method"] = options.message;
});
$(function(){
$.validator.unobtrusive.parse($('#myform'));
$('[type=button]').click(function(e){e.preventDefault(); $('form').valid();});
$('input[type=text]').blur();
})
These are the fields in HTML:
<input type="text" name="StartDate2" id="StartDate2" value="2"
data-val="true" data-val-customequal="xx xxx" data-val-customequal-other="EndDate2"/>
<input type="text" name="EndDate2" id="EndDate2" value="3"
data-val="true" data-val-customequal="xx xx" data-val-customequal-other="StartDate2"/>
I have been trying different things but nothing seems to work.
Any idea?

Your fiddle is not working because:
all your code runs in the DOM ready so you are adding your custom unobtrusive.adapters.add after the unobtrusive.validator plugin called unobtrusive.parse(document) which registers all the inputs without your custom validator
if you call .validate() multiple times it only registers the rules for the first time and does not override them on subsequent calls. So although you've called unobtrusive.parse again in the DOM loaded this time with the custom adapter added it still won't have any effect.
So you have two ways to fix it:
Register your custom adapters before the DOM loaded event, you can do this with changing your fiddle to use
"No wrap - in <head>"
Demo JSFiddle.
Or
Remove the already added validator object with using $('#myform').data('validator', null) before calling unobtrusive.parse manually:
$(function () {
$('#myform').data('validator', null);
$.validator.unobtrusive.parse($('#myform'));
$('[type=button]').click(function (e) {
e.preventDefault();
$('form').valid();
});
$('input[type=text]').blur();
})
Demo JSFiddle.

Related

Materializecss tooltip not showing up

I am trying to use materialize tool tip for the first time using the example shown on its website. However, the tool tip is not showing up. What am I missing? Here is the link to the fiddle : https://jsfiddle.net/L013uvms/5/
<textarea id="causative_micro_organisms" class="materialize-textarea tooltipped" data-position="top" data-tooltip="I am a tooltip" required="" aria-required="true"></textarea>
<label for="causative_micro_organisms">What are the LIKELY causative Micro-organisms?</label>
I have also initialized the tool-tip
$(document).ready(function() {
$('select').formSelect();
$('.tooltipped').tooltip();
})
as docs of materialize website add these before document ready
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.tooltipped');
var instances = M.Tooltip.init(elems, options);
});
related link https://materializecss.com/tooltips.html

Disable entire jqGrid

I have been looking for methods on how to disable a jqGrid and I found some:
Using BlockUI plugin: http://jquery.malsup.com/block/
Using jqGrid options: loadui and set it to 'block'
First option is a great solution (I have not tried yet) and it is clearer maybe but I want to avoid using plugins if I can whenever I can do it by setting object properties so I am trying the second option but it is not working for me, jqGrid continues enabled.
My jqgrid in my asp.net mvc 4 view:
<div id="jqGrid">
#Html.Partial("../Grids/_PartialGrid")
</div>
and _PartialGrid:
<table id="_compGrid" cellpadding="0" cellspacing="0">
</table>
<div id="_compPager" style="text-align: center;">
</div>
so in the view, in script section I perform below on document ready and depending on the status of a property in my model (I disable it if id>0, otherwise I enable it on page reload):
#section scripts
{
#Content.Script("/Grids/CompGrid.js", Url) // Content is a helper javascript loader (see end of this post)
}
<script type="text/javascript">
$(document).ready(function () {
showGrid();
var disableCompGrid = #Html.Raw(Json.Encode(Model.ItemCompViewModel));
setStatusCompGrid(disableCompGrid.id > 0);
}
</script>
CompGrid.js is:
function showGrid() {
$('#_compGrid').jqGrid({
caption: paramFromView.Caption,
colNames: ....
}
function setStatusCompGrid(disabled) {
$('#_compGrid').jqGrid({
loadui: 'block',
loadtext: 'Processing...'
});
}
In the code above, also I have tried to pass as parameter disabled to showGrid function and depending on if it is true or false to set a variable to 'block' or 'enable' respectively and then setting loadui property with this variable but it is not working.
Content.cshtml:
#using System.Web.Mvc;
#helper Script(string scriptName, UrlHelper url)
{
<script src="#url.Content(string.Format("~/Scripts/{0}", scriptName))" type="text/javascript"></script>
}
Any ideas?
It's important to understand that the call $('#_compGrid').jqGrid({...}); converts initial empty <table id="_compGrid"></table> element to relatively complex structure of dives and tables. So you can do such call only once. Such call creates and initialize the grid. In other words the function showGrid has bad name. The function can be called only once. The second call of it will test that the grid already exist and it will do nothing. If you need to change some parameters of existing grid you can use setGridParam method.
In the case you can use absolutely another solution to block the grid. After the call $('#_compGrid').jqGrid({...}); the DOM element of the initial table get some expandos - new property or method. For example $('#_compGrid')[0] will contains grid property which contains beginReq and endReq methods. So you can first create the grid (in the showGrid function) and include options loadui: 'block' and loadtext: 'Processing...' in the list of options which you use. Then if you need to block the grid later you can use
$('#_compGrid')[0].grid.beginReq();
and the code
$('#_compGrid')[0].grid.endReq();
to remove blocking. See the demo which demonstrates this. Alternatively you can show overlays created by jqGrid manually like I described in the answer. The code will be simple enough:
var gridId = "_compGrid"; // id of the grid
...
$("#lui_" + gridId).show();
$("#load_" + gridId).text("Processing...").show();
to show the overlay and
$("#lui_" + gridId).hide();
$("#load_" + gridId).hide();
to hide the overlay. See another demo which works exactly like the first one.
you don't need any plugin. Just add/remove css:
.disabled {
pointer-events: none;
//optional
opacity: 0.4;
}
DEMO

jquerymobile datebox - How to call a function when date selected

I have inherited some code using the jquerymobile datebox. The code so far concentrates on making the application look correct. I need to make it work so that when a date is selected, the server is called with the date and a new page loaded. Most examples just change the date in the page.
The code so far is :-
$('#daycal').live('click', function() {
$('#catchdate').datebox('open');
});
$( "#catchdate" ).bind( "change", function(event, ui) {
$("#test1").val("xyz");
});
And
<div data-role="fieldcontain">
<label for="catchdate">Some Date</label>
<input name="catchdate" type="date" data-role="datebox" id="catchdate" data-options='{"mode":"calbox", "useNewStyle":true, "theme":true, "themeHeader":"f", "themeDateHigh":"f", "themeDatePick":"e", "themeDate":"f", "centerHoriz":true}' />
<input id="test1" type="text"/> <!-- Later changed to a function call -->
</div>
In my simple test I expected the text in the input to change when a date was selected.
I have seen an example using the bind to change event, but I cannot get it to work. In the example I was just changing the value in an input element, later this will be changed to a function call.
I also saw somewhere in my search for an answer, a comment that 'live' was deprecated.
Finally, I thought I could use closeCallback ('Callbacks ('openCallback' and 'closeCallback') are simple to work with...') but could not find any examples of how it should be used.
What changes do I need to make to obtain the functionality I need?
You could try using the close function of the date box, so that when user changes the date selection he makes and closes the date box you can call the server method with the selected date:
$('#DateSelectorId').bind('datebox', function (e, passed) {
if ( passed.method === 'close' ) {
// selected date
var date = $('#DateSelectorId').val();
// make your service method and change page to another page
}
});
think this can fix it
$('#catchdate').on('datebox', function(e, p) {
if ( p.method === 'close' ) {
alert('DO SOMETHING');
}
});
u can go and test it on Fiddle
**i think u need some validation check for input box empty or not

rails jquery change event not working

I am building a rails app where I want to simply fire code when a user selects an option on a element (unobtrusively). I have read that the most supported way of doing this is by attaching the element directly to the change event:
$('#country_selection').change(function() { alert('it works'); });
However, for me, this is not working. If I put it in the console, it works just fine. However, putting it in the js file of my view, it does not work. I know my js file is being loaded because inserting a simple alert('in the js file'); returns just fine. The other strange part is that using the live method works:
$('#country_selection').live('change', function() { alert('hello'); });
However, I do not want to do this b/c it is not as supported. The other option I tried which does not work is the 'delegate' method:
$('#country_selection').delegate('change', function() { alert('hello'); });
Why isn't my change function working?
If you have a select element like
<select id="my-select-box">
<option value="1">First Value</option>
<option value="2">Second Value</option>
</select>
Then the following Jquery code should work
$('#my-select-box').change(function() {
alert("hey, i got changed");
});
It is imperative that the DOM is loaded before JQuery binds your code to the selector. To do this, ensure that you have your code within an anonymous function as such:
jQuery(function(){
$('#my-select-box').change(function() {
alert("hey, i got changed");
});
});
This ensures that the DOM is loaded before the JQuery executes and tries to bind. Otherwise the JavaScript will execute before the element is loaded, and it will not execute correctly.

livequery not always live when used with jquery.validate

I use jquerylive plugin to add additional css classes to .field-validation-error class like this:
$(".field-validation-error").livequery(function () {
$(this).addClass('ui-state-error ui-corner-all');
});
when I get some spans with this class generated by jquery.validate the above code works, but at 2nd validation it doesn't.
here is the live link: http://mrgsp.md:8080/awesome/person
click on create after click save to get validation messages and click again on save
Why not hook your function into the same event that triggers validate()?
Update
I read the other comments and saw you were using xVal, read up a bit on jQuery.Validate as well. jQuery.Validate ties in with many events and registering on the event handlers would be messy. The reason that livequery works first time is that the labels are generated if they don't previously exist so that creation event makes the function run, everytime after this the label is just hidden/shown so it doesn't get triggered again but jQuery.validate's showLabel function resets the classes.
The ideal place is in xVal by making one small change in the xVal.jquery.validate.js file. In the _ensureFormIsMarkedForValidation method are the lines:
ensureFormIsMarkedForValidation: function(formElement, options) {
if (!formElement.data("isMarkedForValidation")) {
formElement.data("isMarkedForValidation", true);
var validationOptions = {
errorClass: "field-validation-error",
All you should need to do is change errorClass to:
errorClass: "field-validation-error ui-state-error ui-corner-all",
This is because xVal is doing the setting up of the validate plugin.
Can you not just the the errorClass option?
$(".selector").validate({
errorClass: "field-validation-error ui-state-error ui-corner-all"
})
Or maybe:
$.validator.setDefaults({
errorClass: "field-validation-error ui-state-error ui-corner-all"
});

Resources