I'm an experienced .NET developer, and am "getting there" with jQuery and Bootstrap. I'm attempting to integrate jQuery form validation (jquery.validator.js add-on), and can't seem to get the basics in place. I feel like I'm doing exactly what the documentation specifies in order to make a basic example work, but I'm obviously missing something.
Here's my page includes:
<link href="/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="/Content/bootstrap-theme.min.css" rel="stylesheet" type="text/css" />
<link href="/Content/datepicker3.css" rel="stylesheet" type="text/css" />
<link href="/Content/site-style-main.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/bootstrap.min.js" type="text/javascript"></script>
<script src="/Scripts/bootstrap-datepicker.js" type="text/javascript"></script>
<script src="https://www.google.com/recaptcha/api.js" type="text/javascript"></script>
<script src="/Scripts/site-script-step1validate.js" type="text/javascript"></script>
Here's the relevant HTML pertaining to one of the fields to be validated, and the form:
<form name="aspnetForm" method="post" action="Step1.aspx?RecertID=1" id="aspnetForm" class="form-horizontal" enctype="multipart/form-data" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">First Name</span>
<input name="ctl00$PageContent$RecertVFCFormView$ProviderFirstName" type="text" maxlength="256" id="ProviderFirstName" class="form-control" />
</div>
</div>
<a id="ExitButton" class="btn btn-primary btn-sm" href="javascript:__doPostBack('ctl00$PageContent$RecertVFCFormView$StepController$ExitButton','')">
<i class="glyphicon glyphicon-new-window" aria-hidden="true"></i> Exit
</a>
</form>
And here's what my jQuery looks like (site-script-step1validate.js):
$(document).ready(function () {
$('#ProviderMedLicenseExpiration').datepicker();
$('#aspnetForm').validate({
onsubmit: false,
rules: {
ProviderFirstName: {
required: true
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
}
});
$('#ExitButton').click(function (e) {
var isValid = $('#aspnetForm').valid();
if (!isValid) {
e.preventDefault();
}
});
});
At this point my expectation is simply that without that first name field populated, the form will fail to submit; it does not. I know that my ExitButton.click function is being reached and that isValid winds-up as true.
Seems pretty straight-forward and I can't quite make-out what I'm missing. Likely something very simple.
The problem is that ProviderFirstName rule must match with the name of the input control you're trying to validate. If you check the HTML you'll see that name is ctl00$PageContent$RecertVFCFormView$ProviderFirstName. Because of this the rule is just ignored.
A possible solution if you're using asp.net 4+ is to define ClientIDMode for TextBox control as static to avoid .net engine to change the id based on parent container.
Another option that may goes against your training purposes is adding required to TextBox markup and remove the custom rule ProviderFirstName. It would have the same end result and definitively would make more sense on a real scenario.
Related
I am very novice with coding, I just started learning about it a week ago.
To cut the story short, i have a code here.
function lookup (){
var mac_address = document.getElementById('mac_address');
var resultDiv = document.getElementById("result");
if(mac_address.value.length<6){
alert('Enter at least 6 characters!')
}else{
var lookUpAdress = '<object type="text/html" id="lookupresult" data="http://macvendors.co/api/jsonp/'+mac_address.value+'"></object>';
resultDiv.innerHTML=lookUpAdress;
}
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
<div style="padding:0px;">
<label>Enter mac address:</label>
<input type="text" id="mac_address" />
<input type="button" value="Lookup!" onclick="lookup();" />
<div id="result" style="margin-top:10px;" class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
</div><!-- Result. -->
</div><!-- Input Box. -->
</div><!-- Container. -->
</body>
</html>
I want to get the result of the Look Up and show it in a better format like :
Company :
Prefix :
Address :
Takenote I'd be happy just to get the "Company."
TIA.
Load jquery together with your html, make sure jquery is loaded otherwise you wont be able to use $.ajax and will have to go the javascript way. Also it is alot easier to use jquery than javascript to manupilate the dom. So if you are a beginner, first learn jquery then move on to javascript.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Use the above one or any other. You can google jquery cdn.
Then add a script to the bottom of your html:
<script>
$(document).ready(function(){
GetMacAddress();
});
function GetMacAddress(){
$.ajax({
url:'http://macvendors.co/api/jsonp/34:13:e8:1b:82:e4',
type:'get',
success:function(data){
// do something with data
alert(data.result.company);
},
error:function(){
console.log('oops');
},
});
}
</script>
This code will get you the result, change the code to suite your needs, i.e. display something in textbox
I guess this would solve your problem but:
You had to look up how to do it in non jQuery (or use jQuery)
I couldn't get it to work with https connections
$.getJSON('https://anyorigin.com/go?url=http%3A//macvendors.co/api/jsonp/34%3A13%3Ae8%3A1b%3A82%3Ae4&callback=?', function(data){
console.log(data.contents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You may read more about it here:
https://medium.freecodecamp.org/client-side-web-scraping-with-javascript-using-jquery-and-regex-5b57a271cb86
I have made a form with Material Design components.
My TextField floating labels float when AutoFill fills the inputs, but not when a user types in them.
function fillFields() {
$("#passwordTextField").val("test");
$("#usernameTextField").val("test");
}
p.highlight-red-on-error {
transition: color 180ms cubic-bezier(0.4, 0, 0.2, 1);
}
div.mdc-text-field--invalid~p.highlight-red-on-error {
color: #b00020;
}
<head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link href="https://fonts.googleapis.com/css?family=Work+Sans" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="https://unpkg.com/material-components-web#latest/dist/material-components-web.min.css">
<script src="https://unpkg.com/material-components-web#latest/dist/material-components-web.min.js"></script>
</head>
<body>
<div>
<div class="mdc-text-field">
<input type="text" id="usernameTextField" name="username" class="mdc-text-field__input" pattern="[A-Za-z]*" required minlength=3 maxlength=32 data-mdc-auto-init="MDCTextField">
<label for="usernameTextField" class="mdc-floating-label">Username</label>
<div class="mdc-line-ripple"></div>
</div>
<p class="highlight-red-on-error">Username must be between 3 and 32 characters and contain only alphanumeric characters.</p>
</div>
<br>
<!-- password field -->
<div>
<div class="mdc-text-field" data-mdc-auto-init="MDCTextField">
<input type="password" id="passwordTextField" name="password" class="mdc-text-field__input" pattern="[A-Za-z!%^&*$?~`=+-_()]*" required minlength=8>
<label for="passwordTextField" class="mdc-floating-label">Password</label>
<div class="mdc-line-ripple"></div>
</div>
<p class="highlight-red-on-error">Password must be at least 6 characters. Some special charcaters are not allowed</p>
</div>
<p>
Typing in the fields doesn't float the labels, but using autofill does.
</p>
<button onClick="fillFields()">Fill fields (doesn't float labels)</button>
<script>
window.mdc.autoInit();
// from https://github.com/material-components/material-components-web/tree/master/packages/mdc-auto-init#using-as-part-of-material-components-web
</script>
</body>
As you can see, neither editing the fields through JavaScript, nor typing in them floats the label. Only using auto-fill does. In addition, the autoInit(); doesn't seem to work.
I found that using autoInit(); didn't work for some reason, so I had to manually initialise the components.
An example (using jQuery) for TextFields is:
$('.mdc-text-field').each(function (i, obj) {
mdc.textField.MDCTextField.attachTo(obj);
});
The above code applies the correct properties and methods, etc. for all items with the class mdc-text-field
I believe that the data-mdc-auto-init has to be added to the top level mdc-text-field and not the input field. I just ran into this myself and adding it to the top level and calling mdc.autoInit() after the onload event on the page solved the issue.
I've got this form with bootstrap but I can't find why it's not working properly ant I've no idea why.
HEAD>>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css"/>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/corrections.css" rel="stylesheet" type="text/css"/>
<script src="js/JQuery-2.1.1-min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
--> code here
</body>
HTML >>
<div class="col-lg-4">
<form class="form-inline well">
<div class="form-group">
<label class="sr-only" for="text">Some label</label>
<input id="text" type="text" class="form-control" placeholder="Text here">
</div>
<button type="submit" class="btn btn-primary pull-right">Ok</button>
<div class="alert alert-danger" style="display:none">
<h4>Error</h4>
Required amount of letters is 4
</div>
<div class="success alert-success" style="display:none">
<h4>Success</h4>
You have the required amount of letters
</div>
</form>
</div>
JS >>
<script>
$(function () {
$("form").on("submit", function () {
if ($("input").val().length < 4) {
$("div.form-group").addClass("has-error");
$("div.alert").show("slow").delay(4000).hide("slow");
return;
} else if ($("input").val().length > 3) {
$("div.form-group").addClass("has-success");
$("div.success").show("slow").delay(4000).hide("slow");
return;
}
});
});
</script>
the alert class shows everytime, any idea why?
The use of $("input") here is unusual. That selector will pull back all elements on the page that are <input>s, which is almost certainly not what you mean. (If there are other inputs on the page, you might get exactly what you're describing.) Use a more precise selector, like $("#text"), and maybe use debug to output the value of val().length so you know what you're evaluating.
(On a side note, "text" is not a very useful name for a text input, and your else-if seems redundant, but they probably aren't causing problems in your code.)
I create a login form in popup box. When the username field is left blank, an error message will appear to notify the user to fill in the empty username field. As a test, I click on the login button leaving the username field, and the message appears in the popup box as expected. But the problem is the popup box is closed immediately.
So, my question is how do I keep the popup box open with the error message shown?
Here is my script:
<!doctype html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Modal Login Window Demo</title>
<link rel="shortcut icon" href="http://designshack.net/favicon.ico">
<link rel="icon" href="http://designshack.net/favicon.ico">
<link rel="stylesheet" type="text/css" media="all" href="http://designshack.net/tutorialexamples/modal-login-jquery/style.css">
<script type="text/javascript" src="http://designshack.net/tutorialexamples/modal-login-jquery/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://designshack.net/tutorialexamples/modal-login-jquery/js/jquery.leanModal.min.js"></script>
</head>
<body>
<div id="w">
<div id="content">
<center><a href="#loginmodal" class="flatbtn" id="modaltrigger">Modal Login</a</center>
</div>
</div>
<div id="loginmodal" style="display:none;">
<?php
if($_POST["loginbtn"]){
if(!$_POST["username"]){
echo "<center><font color=red>please fill your username</font></center>";
}elseif(!$_POST["password"]){
echo "<center><font color=red>please fill your password</font></center>";
}
}
?>
<h1>User Login</h1>
<form method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username" class="txtfield" tabindex="1">
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="txtfield" tabindex="2">
<div class="center"><input type="submit" name="loginbtn" id="loginbtn" class="flatbtn-blu hidemodal" value="Log In" tabindex="3"></div>
</form>
</div>
<script type="text/javascript">
$(function(){
$('#loginform').submit(function(e){
return false;
});
$('#modaltrigger').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
});
</script>
</body>
</html>
The closeButton option will always cause the modal to be closed when the corresponding button is clicked. And looking at the leanModal source, there doesn't seem to be any direct way to manipulate its event-handling callback.
So if all you want to do is to keep the form modal opened if the fields are not filled, and let your server-side codes perform the validation you can just do the following:
$('#loginform').submit(function(e){
if(!$('#username').val()) {
$('#loginmodal').show();
}
else
console.log("Enter your username");
return false;
});
Live demo on jsfiddle. Notice that I added an id to the form tag, and fixed some of the malformed HTML tags in the fiddle.
Haven't had a chance to test but try stopping the propagation of the click function, doing that tells the browser to not complete the default action for this event.
$('#loginbtn').click(function(e){
if(!$('#username').val()){
e.stopPropagation();
}
});
or as the other answer suggests try using jquery validation which will help in getting all this to work much more easily I like to use: http://jqueryvalidation.org/
This appears to be very similar to this question: How to force a html5 form validation without submitting it via jQuery
That answer assumes that you would be adding the required attribute to the necessary form elements, and also that you use a polyfill such as html5shiv if old browser support is a requirement.
use jquery validationEngine. It is a good one for your requirement.
See demo here
You have some missing information in the sample html, the form ID is missing therefor jQuery will not attach to it.
I handle this situation by using AJAX for the form action with a json response.
Here is an example from one of my recent apps... Notice the event.preventDefault() method to keep the form from submitting.
$(function () {
jQuery('body').on('submit', '#frmlOGIN', function (event) {
event.preventDefault();
jQuery.post("?action=ajax_signup", jQuery("#frmlOGIN").serialize(), function (data) {
if (data.status == "OK") {
jQuery("#modal_content").html(data.content);
} else {
jQuery("#error_message").html(data.response);
}
});
});
$('#modaltrigger').leanModal({
top: 110,
overlay: 0.45,
closeButton: ".hidemodal"
});
});
Here is a jsfiddle example.
http://jsfiddle.net/LqmzwwL3/
Can you please tell me how to show an error message on submit button click ?.I am getting an error message after running the program (when I write required :true). I need to show an error message when a user submits the form. I am using this plugin https://github.com/McNull/angular-febworms
Can we get onchange event of select field ?
In my example a red border is displayed when I run the application. I don't want this. I need this when a user clicks the 'submit' button
http://plnkr.co/edit/JOI82JrEBcKJMrzLgtZd?p=preview
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css#2.3.2" data-semver="2.3.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" />
<link rel="stylesheet" href="https://rawgithub.com/McNull/angular-febworms/master/package/febworms.min.css" />
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="http://code.angularjs.org/1.2.0/angular.js" data-semver="1.2.0"></script>
<script src="http://code.angularjs.org/1.2.0/angular-route.js"></script>
<script type="text/javascript" src="https://rawgithub.com/McNull/angular-febworms/master/package/febworms.min.js"></script>
<script type="text/javascript" src="dummy-schema.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MyFormController as frmCtrl">
<div class="container">
<div class="row-fluid">
<form class="form-horizontal" name="form.state" novalidate>
<div febworms-form
febworms-schema="form.schema"
febworms-form-data="form.data">
</div>
<div class="form-actions">
<a class="btn btn-primary" ng-disabled="form.state.$invalid" ng-click="frmCtrl.save()">Save changes</a>
</div>
</form>
</div>
</div>
</body>
</html>
But need to blur event to validate or onchange event ?
Since your form name is 'form.state' and your field name is 'required' (which is a bit confusing by the way, you may want to change that), you can get useful information about your validation state with the following expressions in the scope of your form:
form.state.required.$error // yields something like { "required": true, "pattern": false }
form.state.required.$valid // yields a boolean
form.state.$error
form.state.$valid
I haven't heard of a way of knowing whether a form has already been submitted or not. My best shot would be to add some state for this in the controller :
$scope.errorShown = false;
$scope.showErrorMessage = function(){
$scope.errorShown = true;
};
And in your HTML :
<div class="form-actions">
<a class="btn btn-primary" ng-disabled="form.state.$invalid" ng-click="(form.state.$valid ? frmCtrl.save() : showErrorMessage())">Save changes</a>
</div>
<div ng-if="errorShown && form.state.$invalid">
Your form is not valid.
</div>
Plunkr here.