Watermark and Jquery Unobtrusive validation not working - c#

i added a watermark to my input using this link below
http://www.mkyong.com/jquery/jquery-watermark-effect-on-text-input/
once i added that my required validation using jquery unobtrusive stops to work.
how can i get my validation and watermark both to work?
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div class="editor-field">
#Html.EditorFor(model => model.Person.PersonName)
#Html.ValidationMessageFor(model => model.Person.PersonName)
</div>
$(document).ready(function () {
var watermark = 'Person Name';
init, set watermark text and class
$('#Person_PersonName').val(watermark).addClass('watermark');
if blur and no value inside, set watermark text and class again.
$('#Person_PersonName').blur(function () {
if ($(this).val().length == 0) {
$(this).val(watermark).addClass('watermark');
}
});
if focus and text is watermrk, set it to empty and remove the watermark class
$('#Person_PersonName').focus(function () {
if ($(this).val() == watermark) {
$(this).val('').removeClass('watermark');
}
});
}

<input type="text" name="key" id="searchInput" placeholder="what's up"/> worked for me
– kandroid Feb 18 at 15:19

Related

Why do `JQuery` tabs lose styling after a button click

I am using JQuery tabs in my Asp.Net/C# app.
I am modelling my approach after this article. The JQuery is outside of my
<asp:UpdatePanel ID="UpdatePanel1"...></asp:UpdatePanel>
wrapper while the html components are inside.
Whenever I click a button, my tabs completely lose their CSS styling and I see all of the tab contents, rather than just the
<div id="current-tab">
for that tab.
Why is this happening and how do I fix it?
My guess is that its related to post-back or the update panel somehow, but I am not sure why the added C# code under page_load doesn't keep the selected tab current on post-back when the button is fired.
ASPX
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
...
</script>
....
<table>
<tr>
<td style="padding: 5px;">
<div id="tabs">
<ul>
<li>Tier 1</li>
<li>Tier 2</li>
<li>Tier 3</li>
<li>Tier 4</li>
</ul>
<div class="tab-content">
<div id="tab-1">
...
</div>
<div id="tab-2">
...
</div>
<div id="tab-3">
...
</div>
<div id="tab-4">
...
</div>
</div>
</div>
<asp:HiddenField ID="selected_tab" runat="server" />
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
...
selected_tab.Value = Request.Form[selected_tab.UniqueID];
...
}
You are right, it has something to do with a Partial PostBack. So in order for jquery functions to work again you need to rebind it after the Partial PostBack is done.
<script type="text/javascript">
$(document).ready(function () {
buildTabs();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
buildTabs();
});
function buildTabs() {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
}
</script>
But the selected tab is a different story. You also need to store the active tab somewhere and re-apply it after the partial PostBack is done. See this answer for details.
But basically you need to store the active tab ID in SessionStorage, cookie or Hiddden input and re-apply it in prm.add_endRequest(function () {

DatePicker not displaying properly in Bootstrap ASP.NET MVC 5

I have a date picker in my form and it is not displaying properly in any browser
<div class="col-md-10">
#Html.TextBoxFor(model => model.DateJoined, new { #class = "datepicker" })
#Html.ValidationMessageFor(model => model.DateJoined)
</div>
I have added jquery UI and added Javascript like this:
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script type="text/javascript">
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker(); //Initialise any date pickers
});
</script>
And this is how it is displaying in UI:
Demo
JQuery UI
You need to include following files
//css file jQuery UI
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
//jQuery file js reference.
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
//jQuery UI js reference.
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
In the App_Start/Bundle.config
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/site.css",
"~/Content/jquery-ui.css"));

JQWidgets not working in MVC 4

I am trying to use the sample off of jqWidgets for the ListBox. I have copied the code directly into my index.cshtml file. I am not seeing the desired results, which would be what the sample looks like. All it is showing me is the button.
Here is a link to the page. I have reduced the content and allowed for anyone to look at it: https://drive.azurewebsites.net/Question
Here is the sample's website: http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxlistbox/jquery-listbox-getting-started.htm
I'm not sure how to troubleshoot this or where to look to see what is really going wrong. I am using Chrome and pulled up Inspect Element. The scripts are being retrieved.
Here is my code:
<link rel="stylesheet" href="~/Scripts/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxcore.js"></script><script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxlistbox.js"></script>
<body>
<div id='content'>
<script type="text/javascript">
$(document).ready(function () {
var source = [
"Affogato",
"Americano",
"Bicerin",
"Breve",
"Café Bombón",
"Café au lait",
"Caffé Corretto",
"Café Crema",
"Caffé Latte",
];
// Create a jqxListBox
$("#jqxlistbox").jqxListBox({ source: source, width: '200px', height: '200px' });
// disable the sixth item.
$("#jqxlistbox").jqxListBox('disableAt', 5);
// bind to 'select' event.
$('#jqxlistbox').bind('select', function (event) {
var args = event.args;
var item = $('#jqxlistbox').jqxListBox('getItem', args.index);
$("#eventlog").html('Selected: ' + item.label);
});
$("#button").jqxButton();
$("#button").click(function () {
var item = $('#jqxlistbox').jqxListBox('getSelectedItem');
if (item != null) {
alert(item.label);
}
});
});
</script>
<div id='jqxlistbox'>
</div>
<div style="margin-top: 10px;">
<input id="button" type="button" value="Get Selected Item" />
<div id="eventlog"></div>
</div>
</div>
</body>
Your Scripts are not referenced correctly. In MVC4, the process of referencing Scripts is different - http://www.jqwidgets.com/jquery-widgets-documentation/documentation/asp.net-integration/asp.net-binding-to-sql-database-mvc4.htm

Jquery template anchor tag click

SO i have this jquery template and i need to call a jquery or javascript function on the click of this anchor tag. Ive tried it a few different ways.
<a href="yourfunction()"
Ive tried
$('#number').click(function(e){
So if anyone could help it would be highly appreciated. The anchor tag in question is the phone number one with the id of number.
#model OpenRoad.Web.Areas.Marketing.Models.MobyNumberSelectionModel
#{
ViewBag.Title = "Moby Number Selection";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts {
<script type ="text/javascript">
$('#number').click(function (e) {
alert('test');
});
});
mixpanel.track("View Marketing | Moby | Number Selection");
//$(document).on("click", "#number", function (e) {
// event.preventDefault();
// alert('test'); });
//$('#number').click(function (e) {
// Alert('test');
//});
</script>
}
<label class="lgform" style="text-align: left; padding: 10px 0;">Select state and area code:</label>
#Html.DropDownListFor(m => m.State, OpenRoad.Web.Helpers.DropDownLists.GetOptionValues("States", Model.State),
new { #class = "ddtrigger", data_url = "/Marketing/Moby/GetAreaCodes", data_template = "areaCodeTemplate", data_target = "AreaCode" })
#Html.DropDownListFor(m => m.AreaCode, (IEnumerable<SelectListItem>)ViewData["AreaCodes"],
new { #class = "ddtrigger", data_url = "/Marketing/Moby/GetPhoneNumbers",
data_template = "phoneNumberTemplate",
data_target = "phoneNumbers",
data_listtarget="true" })
#Html.HiddenFor(m => m.MobyNumber)
<script id="areaCodeTemplate" type="text/x-jquery-template">
<option value="${AreaCode}">${AreaCode}</option>
</script>
<br />
<script id="phoneNumberTemplate" type="text/x-jquery-template">
<div class="numberselectbox">
<strong>${FormattedPhoneNumber}</strong> Select<br/>
</div>
</script>
<div id="phoneNumbers">
</div>
Since you are using a template to generate the elements, these elements will be dynamic so you need to use delegated event model.
Also since it is a template, do not use static id for the elements since the elements can be duplicated - use class attribute instead
<script id="phoneNumberTemplate" type="text/x-jquery-template">
<div class="numberselectbox">
<strong>${FormattedPhoneNumber}</strong> Select<br/>
</div>
$(document).on('click', '.number', function(){
//do something
})
You could try jQuery's on() method or click() shorthand:
$(document).ready( function() {
$('#number').on('click', function(e){
// your method implementation here
e.preventDefault();
});
// OR //
$('#number').click(function(e){
// your method implementation here
e.preventDefault();
});
});

MVC Ajax form with unobstructive validation errors not going away

I am having an issue where form errors are persisting on the page even after the form is valid.
I have the following setup:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>
<body>
#RenderBody()
</body>
</html>
index.cshtml:
#model SimpleForm.Models.Name
#{
ViewBag.Title = "Form";
}
<script>
$().ready(function () {
$("#quote_form").submit(function () {
return true;
});
});
</script>
#using (Ajax.BeginForm("RunQuote", "Page", new AjaxOptions { UpdateTargetId = "quoteSummary" }, new { id = "quote_form", onreset = "return confirm('Clear all form data?')" }))
{
<input type="submit" value="Send" />
<fieldset>
<legend>Name </legend>
<dl>
<dt>First</dt>
<dd>#Html.TextAreaFor(m => m.first, new { onblur = "$('#quote_form').submit();" })</dd>
<dt>Last</dt>
<dd>#Html.TextAreaFor(m => m.last, new { onblur = "$('#quote_form').submit();" })</dd>
</dl>
</fieldset>
<div class="qMatrixSubText">
#Html.ValidationSummary()
#{
Html.ValidateFor(m => m.first);
Html.ValidateFor(m => m.last);
}
</div>
<div id="quoteSummary" class="quoteSummary">
</div>
}
FormController.cs
using System;
using System.Web.Mvc;
using SimpleForm.Models;
namespace SimpleForm.Controllers
{
public class FormController : Controller
{
//
// GET: /Form/
public ActionResult Index()
{
return View();
}
public String RunQuote(Name quote)
{
return "Success!";
}
}
}
Name.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace SimpleForm.Models
{
public class Name
{
[Required()]
public string first { get; set; }
public string last { get; set; }
}
}
The form populates fine, I see the error if I don't put anything into first and the form won't submit. After populating something into first I get the ajax call and then it posts "Success" to the div.
However, this is the problem, the error "the first field is required." still remains on the page. It's as if the ajax submit form is going through before the validation gets a chance to clear the error, and then it never gets the chance.
Any way to get the validation to still remove the errors?
The form is not being validated, because your onblur event is short-circuiting the submission process in jquery-unobtrusive-ajax.js.
Instead, change your onblur event for both fields to the following:
$(this).parents('form:first').find(':submit')[0].click();
This will invoke the jquery.unobtrusive-ajax.js script, causing validation to occur prior to the Ajax submission to the server.
UPDATE
When I looked back at your view, I saw that you are calling #Html.ValidateFor() for your properties. This creates HTML markup outside of the div created by #Html.ValidationSummary.
Because this markup is outside of where unobtrusive validation expects it, this markup is never overwritten, and will always remain. Remove the #Html.ValidateFor() lines. If you need to have the validation messages after your initial load, call validate() on document.ready to set your validation messages.
Because I haven't found a proper solution to this problem, I've decided to simply target the validation-summary-errors div and add the class display:none; to the li elements. This hides the validation errors that have otherwise not cleared before submitting the form.
$('#form_errors').children('div.validation-summary-errors').children('ul').children('li').css('display','none')
There has to be a better solution, but I've tried everything and can't figure out why my attempts to force validation don't work.

Categories

Resources