Having two fields in my form, that compare to each other to see if they are valid:
<input type="text" name="StartDate" id="StartDate" value="2"
data-val="true" data-val-equalto="xx" data-val-equalto-other="EndDate"/>
<input type="text" name="EndDate" id="EndDate" value="3"
data-val="true" data-val-equalto="xx" data-val-equalto-other="StartDate"/>
When I blur on StartDate, EndDate gets validated as well. So jQuery manages to avoid validation loop between one and the other.
Now, I am trying to implement the same mechanism in my custom validation rules. I get the value from the "other" field, and if everything is right, i trigger validation in the "other" as well, but this ends in a validation loop:
$.validator.addMethod("customequal-method", function (val, el, p) {
var $other = $(el).closest('form').find('input[name=' + p.other + ']');
if($other.val() == val){
try{$other.valid();}
finally{return true;}
}
return false;
});
How could I apply the same approach than jQuery? I mean, given these two fields:
<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 want that when modifying EndDate2, after blur, StartDate2 gets validated as well, and both became valid in the same way than in jQuery.
I have been trying to put together an example in jsFiddle, but I cannot make my custom method work: http://jsfiddle.net/vtortola/vu6tm/ ( if you find the problem I would be very grateful ), I started a separate thread about this at jQuery unobtrusive custom adapter and method in jsFiddle
Cheers.
You need a stack to understand you returned back to a previously validates element. A single value is not enough because eache element may be involved in other rules with other elements. You may define the var that contains the stack in closure (isInStack verifies if the element is in the array):
(function () {
var stack = [];
$.validator.addMethod("customequal-method", function (val, el, p) {
var iAmTheRoot = stack.length == 0;
var $other = $(el).closest('form').find('input[name=' + p.other + ']');
if($other.val() == val){
try{
if (!isInStack($other[0]) ) $other.valid();
}
finally{
if (iAmTheRoot) stack = [];
return true;}
}
return false;
});})();
Related
I got knockout to work before in MVC, but unfortunately I lost the code, and need help figuring it out.
I am trying to simply put an html page in the ~/wwwsource/ folder of my MVC project, and in that page I would like to demo a simple knockout example.
(Eventually, I actually want to use knockout inside MVC Views, using knockout right alongside Razor if possible but first I just would at least like to get a simple working example going, and extend from there.
I tried the following, which worked in JSFiddle but not in Visual Studio:
<script src="lib/knockout/dist/knockout.debug.js" type="text/javascript">
// Here's my data model
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.pureComputed(function () {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));
</script>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
You are calling the javascript before the html has been fully rendered. So when ko.applyBindingsis called the html as only partially loaded.
Easiest solution is to wrap the javascript in a document loaded callback using jQuery (which should exist because you're using knockout).
You also have some invalid script tag syntax. Need to close knockout script tag before starting a new one for the page.
<script src="lib/knockout/dist/knockout.debug.js" type="text/javascript">
</script>
<script type="text/javascript">
// Here's my data model
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.pureComputed(function () {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
$(document).ready(function(){
ko.applyBindings(new ViewModel("Planet", "Earth"));
})
</script>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
Im trying to create an app that will have fields a user can enter information into. The problem is I don't know how many fields that will be. For example, lets say you have a recipe app where you enter the ingredients in. Some recipes may have 2 ingredients and some may have more. What I am wanting is the option if there are more fields needed than what is on the screen presently, the user can press a add button and it will create the additional fields as needed instead of having some potentially unused fields. I've been looking around trying to find an example of what I'm looking for and not having any luck. Any help would be much appreciated.
best approach will be a UITableView. There you can add as much cell as you need.
There is a apples example though it not as like as you want but you can get the picture.
Hope this helps.. :)
Try this it will help you..
<pre><div id="divingredient" class="input_wrapar_search">
<span>Ivingredient Type : </span>
<input type="text" maxlength="50" id="txtIngredient0" />
</div> </pre>
<script>
var counter = 0;
$("[id$=btnaddnew]").live("click", function (e) {
counter++;
if (counter > 10) {
alert("Can not add more than 10 price !");
return false;
}
$("#divingredient").append('<input type="text" maxlength="50" id="txtIngredient' + counter + '" />');
e.preventDefault();
});
$("[id$=btnremove]").live("click", function (e) {
if (counter == 0) {
alert("one price is manadatory !");
return false;
}
$("#txtIngredient" + counter).remove();
counter--;
e.preventDefault();
});
</script>
<asp:Button ID="btnaddnew" runat="server" Class="btn" Text="Add New" />
<asp:Button ID="btnremove" runat="server" Class="btn" Text="Remove" /></pre>
Is there a possibility to have a number input with minus-button on the left and plus-button on the right? Or maybe also -- ++ to change value in bigger steps.
I know that I'm not the first one asking this but:
This solution is not displaying correctly in the first turn and jQuery-Mobile-Stepper-Widget from Github (can't post another link because I'm new) does not work with current version of jQuery Mobile.
The result should look like the screenshot in this question: Has anyone implemented jQuery Mobile Add (+/-) Button Number Incrementers? respectively horizontal grouped buttons in jQuery Mobile
Any ideas or new snippets, working with current version of jQuery mobile?
Here is a hint, the rest is purely CSS job and extra JS codes to control the value, e.g. maximum, minimum...etc.
HTML
<div data-role="controlgroup" data-type="horizontal" data-mini="true">
<button id="plus" data-inline="true">+</button>
<input type="text" id="number" value="0" disabled="disabled" />
<button id="minus" data-inline="true">-</button>
</div>
Code
$('#plus').unbind('click').bind('click', function () {
var value = $('#number').val();
value++;
$('#number').val(value);
});
$('#minus').unbind('click').bind('click', function () {
var value = $('#number').val();
value--;
$('#number').val(value);
});
JSFiddle
In jQM the input type number does the most of the magic you want
<input type="number" name="number" value="0"/>
If you require more fancy styling you have to follow Omar's code
<i onclick="qty('plus');" class="fa fa-plus c_pointer"></i>
<input type="text" id="prdqty" name="qty" value="1" placeholder="1">
<i onclick="qty('minus');" class="fa fa-minus c_pointer"></i>
function qty(val){
pqty = $('#prdqty').val();
if (val == "plus") {
var newVal = parseFloat(pqty) + 1;
} else {
if (pqty > 1) {
var newVal = parseFloat(pqty) - 1;
} else {
newVal = 1;
}
}
$('#prdqty').val(newVal);
}
For fields in my ASP.NET MVC view that have been attributed as required, is there any way for the framework to render some sort of indicator automatically that the field is marked as required in metadata?
Should be able to do this with CSS since MVC3 adds in those custom attributes to the element:
<input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" value="" />
You could key off the data-val-required in CSS like so:
input[data-val-required] {
background:red
}
or set a background image of an asterisk etc.
I did that way because my required fields must be dynamic (defined in a configuration file)
Add at the end of your View:
<script type="text/javascript">
$('input[type=text]').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
</script>
I modified Renato Saito's answer to include more field types (all types of input and select lists) and use the jQuery namespace instead of the generic $. Here is my revision:
<script type="text/javascript">
// add indicator to required fields
jQuery('input,select').each(function () {
var req = jQuery(this).attr('data-val-required');
if (undefined != req) {
var label = jQuery('label[for="' + jQuery(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
</script>
Here is one that will attach a red asterisk to the right side of anything with the attribute 'data-val-required'.
<script type="text/javascript">
$('[data-val-required]').after('<span style="color:red; font-size: 20px; vertical-align: middle;"> *</span>');
</script>
Adding html attribute is not enough. This will only cause javascript validation error. If you want to indicate that the field is required you'd probaly want to add an asterisk to it. You can do it by means of extenssion method of HtmlHelper. You can find a thorough explanation here
Indicating required field in MVC application
A Small Modification Is Done From My Side.
Actually I had primary keys (Identity Columns in DB). That I did no want to highlight.
So I Used Below Code Snippet to select only input[type=text] fields that has required attribute in annotation.
$("[data-val-required]").not(":hidden").not(":radio").not(":checkbox").after('<span style="color:red;max-width:10px;min-height:30px;">*</span>');
I have Made the CheckboxList like this?
<%foreach(ListItem m in bootcamp.STPs.ProjectManagement.Controllers.MemberController.JALLMembers()){%>
<label for=""><%= m.Text %></label>
<input id="Mana" type="checkbox" value="<%= m.Value %>" name="chkbx" />
<%}%>
How can I get the Values of selected checkboxes through ajax script in controller?
I am using Asp.net MVC?
Or serialize the form?
$('form').submit(function() {
alert($(this).serialize());
return false;
});
I have find the answer
var data2="";
$("input[name=chkbx]").each(function()
{
if($(this).attr("checked")==true || $(this).val()==undefined)
return false;
data2 +=$(this).val() + ",";
});
By this you can collect all selected checkboxes Values with comma seprated.