How to position ngshow messages in angular js - css

How to have ng-show messages beside the text box rather than underneath it. Right now it is displaying all the validation messages underneath the input box.
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
"use strict";
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.cityArray = ["hyderabad", "secunderabad", "delhi", "mumbai"];
$scope.submit = function ($event) {
if ($scope.myForm.$invalid) {
// Or some other update
$scope.myForm.$submitted = true;
$event.preventDefault();
}
};
});
app.directive('uniqueUsername', function ($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind('blur', function (e) {
ngModel.$setValidity('unique', true);
$http.post('CheckUserName2.do').success(function (data) {
if (data) {
ngModel.$setValidity('unique', false);
}
});
});
}
};
});
</script>
</head>
<body ng-controller="MainCtrl">
<div class="container">
<div class="col-md-6 col-md-offset-0">
<div class="panel panel-login">
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<h2 class="text-muted">Registration form</h2>
<div>
<form name="myForm" action="RegistrationServlet.do" method="POST" >
First name:<input type="text" class="form-control input-sm" name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="uname" unique-username="" placeholder="First Name" required/>
<span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
<span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span><br/>
<span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
<button class="form-control btn btn-success" type="submit" ng-click="submit($event)">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Here's the plunker

You don't have space to the right to display error messages beside the input box. Putting error messages just above the submit button will cause a minor UI issue: with each error, your form submit-button will flicker vertically.
Viz.
- Submit your form without entering any input to get the error message.
- type/erase any character in the input box to see the flickering
Workaround:
Either keep the error messages below submit button or provide dedicated height to error messages to avoid undesirable effects or both
<form name="myForm" action="RegistrationServlet.do" method="POST" >
First name:<input type="text" class="form-control input-sm" name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="uname" unique-username="" placeholder="First Name" required/><br><br>
<button class="form-control btn btn-success" type="submit" ng-click="submit($event)">Submit</button>
<div style="height=100px">
<span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
<span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span><br/>
<span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
</div>
</form>
Demo

Related

Displaying Error Message in Bootstrap Modal in Spring MVC Project

Is it possible to display "User with this username does not exist" Error Message in Bootstrap Modal in Spring MVC Project through the controller?
login.jsp
<div class="modal-body">
<form id="register-form" role="form" autocomplete="off" class="form"
method="POST"
action="${pageContext.request.contextPath }/recoverPassword">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-envelope color-blue"></i></span> <input
id="email" name="username" placeholder="your username"
class="form-control" type="text"> ${error}
</div>
</div>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<button class="btn btn-lg btn-primary btn-block" type="submit">
Send email link</button>
</form>
controller
#RequestMapping(value = "/recoverPassword", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void sendingEmailForForgot(#RequestParam("username") String username) {
// Check whether email exists in DB
System.out.println(userDAO.getUserByName(username));
System.out.println(username);
if (userDAO.getUserByName(username) == null) {
System.out.println("This ID does not exists");
redirectAttributes.addAttribute("error", "wrong");
} else {
System.out.println("mail sent to your id");
}
// If exists then hash and send url link
// else error
}
I have validated username whether if exists, but how to display that error on same currently opened modal?
If not possible through controller please share any other way to do so.
Finally solved it through AJAX, still don't know if possible through the controller. Works fine for me, I have used this:
function doAjaxPost() {
// get the form values
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: contexPath + "/AddUser.htm",
data: "name=" + name + "&education=" + education,
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
userInfo = "<ol>";
for(i =0 ; i < response.result.length ; i++){
userInfo += "<br><li><b>Name</b> : " + response.result[i].name +
";<b> Education</b> : " + response.result[i].education;
}
userInfo += "</ol>";
$('#info').html("User has been added to the list successfully. " + userInfo);
$('#name').val('');
$('#education').val('');
$('#error').hide('slow');
$('#info').show('slow');
}else{
errorInfo = "";
for(i =0 ; i < response.result.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
}
},
error: function(e){
alert('Error: ' + e);
}
});
}
Following trick worked for me
1. put ${error} in p tag with unique id
2. On login.jsp page load,check if innerHtml of p tag is empty.
3 If it is not empty open the login modal.
function modelopen(){
var temp = document.getElementById("errormsg").innerHTML;
if(temp!==""){
$('#modallogin').modal('show');
}
You can try:
1) RestController instead of Controller (I think that this is way you solved this)
2) You can use validations and return your error as part of BindingResult https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html
3) Use exceptionHandler
function errorshow() {
const input1 = document.getElementById('input1').value;
const input2 = document.getElementById('input2').value;
const div = document.getElementById("erroM");
if (input1 == '' && input2 == '') {
div.innerHTML = "hey";
setTimeout(() => {
div.remove()}, 2000);
}}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<title>Erorr Show in Modal</title>
</head>
<body>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div id="erroM"></div>
<div>
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="errorshow()">save</button>
</div>
</form>
</div>
</div>
</div>
<!-- Button trigger modal -->
<button id="button" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Click</button>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>

Datetimepicker doesn't function inside collapse panels

*********THIS WAS A MISTAKE- THE DATETIMEPICKER.JS WAS CORRUPTED* APOLOGIES.********
<div id="post" class="panel-collapse collapse">
<div class="panel panel-default">
<br />
<br />
<div class="container">
<div class="form-group col-sm-6">
<script type="text/javascript">
$(document).ready(function() {
$('.datepicker1').datepicker();
</script>
<div id="datetimepicker1" class="input-append date">
<input id="date_txt" runat="server" data-format="dd/MM/yyyy" type="text" />
<span class="add-on"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
The datepicker works fine everywhere else. Except when put inside a collapsible panel such as this.
Am I doing it wrong?
UPDATED CODE:
<div class="col-sm-9">
<script type="text/javascript">
$(function () {
$('#datetimepicker2').datetimepicker({
pickTime: false
});
});
</script>
<div id="datetimepicker2" class="input-append date">
<input id="date_txt" runat="server" data-format="dd/MM/yyyy" type="text" />
<span class="add-on"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
Two reasons, datepicker not working inside collapse panels
in HTML you have id selector
<div id="datetimepicker1" class="input-append date">
in script, you are targeting class
$('.datepicker1').datepicker();
should be
$('#datepicker1').datepicker();
and you are missing closing braces }); for ready event which causes syntax error.
<script type="text/javascript">
$(document).ready(function() {
$("#datepicker1").datepicker();
}); <---This was missing
</script>
Edit
As you only want to show the date not time, I believe this pickTime: false not supported because pickDate and pickTime have been removed from current version.
So try like this and also you can set the date-format too which I think you are trying to set inside input.
<script type="text/javascript">
$(function () {
$("#datetimepicker2").datetimepicker({
format: "DD/MM/YYYY"
});
});
</script>
Working Fiddle

Post back Method not get call on button click in MVC4

i have created a login page without _layout.cshtml in mvc4 and added two text box with a button. But when i click button it no getting post back. I have tried using breakpoint. pls help. My Code
#model MapProjectMVC.Models.LoginModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Special Spots</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="loginBox">
<div class="loginHead">
<img src="img/logo.png" alt="Special Spots - responsive admin panel" title="Special Spots - responsive admin panel" />
</div>
<div class="control-group">
<label for="inputEmail">
User Name</label>
#Html.TextBoxFor(a => a.UserName)
</div>
<div class="control-group">
<label for="inputPassword">
Password</label>
#Html.TextBoxFor(a => a.Password)
</div>
<div class="control-group" style="margin-bottom: 5px;">
</div>
<div class="form-actions">
<button type="submit" class="btn btn-block">
Sign in</button>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
</body>
</html>
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel LM)
{
var UserId = new ObjectParameter("userId",typeof(string));
var res = new ObjectParameter("res",typeof(Int32));
int i = ssc.ValidateAdminLogin(LM.UserName, LM.Password, UserId, res);
if (Convert.ToInt32(res) == 1)
{
}
else
{
ModelState.AddModelError("", "Login details are wrong.");
}
return View(LM);
}
You have to put the input elements and submit button in form. For this purpose you can use asp.net mvc Html Helper Extension for form Html.BeginForm() this way:
#using(Html.BeginForm())
{
<div class="loginBox">
<div class="loginHead">
<img src="img/logo.png" alt="Special Spots - responsive admin panel" title="Special Spots - responsive admin panel" />
</div>
<div class="control-group">
<label for="inputEmail">
User Name</label>
#Html.TextBoxFor(a => a.UserName)
</div>
<div class="control-group">
<label for="inputPassword">
Password</label>
#Html.TextBoxFor(a => a.Password)
</div>
<div class="control-group" style="margin-bottom: 5px;">
</div>
<div class="form-actions">
<button type="submit" class="btn btn-block">
Sign in</button>
</div>
</div>
}
There are many overloads of Html.BeginForm(), See all overloads here

When click on submit button it navigates to New page with same window **dynamically loading** using `meteor`

I am try to when click on Form submit button it navigates to new page with same window dynamically but it is not loading the details but it navigates to that page.I am sending my code also please help me.
Html page
<head>
<title>sample</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="container">
{{> header}}
{{> body}}
{{> footer}}
</div>
<div class="row-fluid">
{{render-Router}}
</div>
</body>
<template name="header">
<header>
<div class="header">
<img src="./logo.png" style="height:100px;width:200px;"/>
</div>
</header>
</template>
<template name="body">
<div class="bgbody">
<div align="center">
<form id="login-form" action="/admindetails">
<table>
<p class="admin">Admin Login</p>
<tr>
<td><p for="username">Admin Name</p></td>
<td><input type="text" id="username" name="username" placeholder="UserName"></td>
</tr>
<tr>
<td><p for="password">Password</p></td>
<td><input type="password" id="pwd" name="password" placeholder="password"></td>
</tr>
<td></td><td><input class="btn btn-success" type="submit" value="Log In"></td>
<td><input class="btn btn-capsule" type="button" value="New User"></td>
</table>
</form>
</div>
</div>
</template>
<template name="footer">
<div class="footer">
<div style="padding:20px;">
<div class="footerlinks"><p>AboutUs</p></div>
<div class="footerlinks">|</div>
<div class="footerlinks"><p>ContactUs</p></div>
<div class="copyright"><p>Copyright#Healt_Care</p></div>
</div>
</div>
</template>
Client code:
if (Meteor.isClient) {
Meteor.Router.add({
'/admindetails':'admindetails'
})
Template.body.events
({
'submit #login-form' : function (e,t)
{
/* template data, if any, is available in 'this'*/
if (typeof console !== 'undefined')
console.log("You pressed the button");
e.preventDefault();
/*retrieve the input field values*/
var email = t.find('#username').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
alert(err.reason);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
Meteor.Router.to("/admindetails");
}
});
}
});
}
You manage the submit event yourself, so there's no need to set up the action parameter of the form. Setting that parameter causes browser to load target page on submit. Simply remove the parameter and things should work as intended.

Retrieve an element by XPath/CSS from HTML

I am trying retrieve an element "Nature News Standard Article in Nature News & Comment" which is part of below HMTL code.
I have following WebDriver code in selenium:
if ("Polopoly CM".equals(driver.getTitle())) {
System.out.println("----> Title of page <----");
driver.findElement(By.xpath("//*[starts-with(#id,'nav_') and #class='p_textOutput']"));
System.out.println("----> Xpath Selected <----");
driver.findElement(By.xpath("//*[starts-with(#id,'nav_') and #class='p_textOutput']")).click();
System.out.println("----> Xpath Clicked <----");
}
Problem is: i am unable to retrive the required element through Xpath/CSS from HTML
HTML:
<document>
<html xmlns:polopoly="http://www.polopoly.com/polopoly/cm/app/gui" xmlns="http://www.w3.org/1999/xhtml" style="cursor: default;">
<head>
<body id="nav_3" class="navFrameBody" onbeforeunload="busyCursor();" onload="onLoad(); idleCursor();">
<script type="text/javascript"> <!-- Jasmine.createFrame('nav'); //--> </script>
<form id="mainform" name="mainform" method="post" action="CM">
<input type="hidden" value="2852906396" name="owid"/>**
<input type="hidden" value="1332852912984" name="ofid"/>
<input type="hidden" value="nav" name="ofn"/>
<input type="hidden" value="true" name="ofs"/>
<input id="nav_1" type="hidden" value="0" name="nav_1"/>
<input id="nav_2" type="hidden" value="0" name="nav_2"/>
<div id="nav_13_placeHolder" class="ajax_placeHolder">
<fieldset id="nav_14" class="field"/>
<div id="nav_4" class="p-group quickCreator expanded">
<div id="nav_4_state">
<input id="nav_15" type="hidden" value="expanded" name="nav_15"/>
</div>
<div class="toggleIcon clearfix"/>
<script lang="javascript">$(document).ready(function() {p_makeExpandable('nav_4', 'nav_15')});</script>
<fieldset id="nav_16" class="contentCreator field topContentCreator">
<div class="quickCreator contentCreator container">
<div class="quickCreator header clearfix">
<h2> Create New </h2>
<a id="nav_17" class="customize" href="javascript:actionEventData({$contentId:"18.232.1319560059", $action:"edit", $target:"work", $opentab:"menu/quickCreatorLayout"})">Customize</a>
</div>
<div class="list">
<div class="quickCreator link">
<input type="hidden" value="" name="nav_18"/>
<a id="nav_18" href="javascript:submitForm(document.mainform, document.mainform.nav_18, "x")">
<img id="nav_19" class="centered" alt="" src="images/icons/transparentIcon.png"/>
<span id="nav_20" class="p_textOutput">Nature News Standard Article in Nature News & Comment</span>
</a>
</div>
</div>
</div>
</fieldset>
</div>
<div id="nav_5" class="p-group contentTree expanded">
<div id="nav_5_state">
<input id="nav_21" type="hidden" value="expanded" name="nav_21"/>
</div>
<div class="toggleIcon clearfix"/>
<script lang="javascript">$(document).ready(function() {p_makeExpandable('nav_5', 'nav_21')});</script>
<div class="field contentTree">
<div id="nav_6_placeHolder" class="ajax_placeHolder">
<div class="header">
<span class="label">Content Tree</span>
<button id="nav_9" type="button" value="Refresh tree" name="nav_9">
<img id="nav_22" class="centered" alt="" src="images/icons/refresh.png"/>
<span id="nav_23" class="p_textOutput"> Refresh tree</span>
<script type="text/javascript"> <!-- jQuery(document).ready(function() { addOnClickEvent("nav_9",null, "nav_9_placeHolder", null, new IndicatorLifecycleHook('p.std_ajaxIndicator', true, 0.8, "createImageTop('images/ajax/busy_indicator_big_green.gif')")); }); //--> </script>
</button>
</div>
<div class="tree">
<div id="nav_8_placeHolder" class="ajax_placeHolder">
<script type="text/javascript"> jQuery.require(["script/polopoly-ui.js"]); </script>
<input id="nav_8" type="hidden" value="" name="nav_8"/>
<script type="text/javascript"> jQuery.require(["script/polopoly-ui.js"]); </script>
<ul id="nav_8_tree" class="tree">
</div>
</div>
</div>
</div>
</div>
<fieldset id="nav_24" class="field clipboard">
<input id="nav_25" type="hidden" value="" name="nav_25"/>
</fieldset>
</form>
<script type="text/javascript"> <!-- jQuery(document).ready(function() { if(window.parent.SeleniumPageLoadCountnav==null) { window.parent.SeleniumPageLoadCountnav=1; window.parent.SeleniumPageLoadCountnavOld=0; } else { window.parent.SeleniumPageLoadCountnav+=1; } }); //--> </script>
</body>
</html>
</document>
I see two elements which can be selected by your xpath locator. Try to find both of them.
List<WebElement> elements = webDriver.findElements(By.xpath("your_xpath"));
for (Element element : elements) {
element.click();
}
Your HTML code is:
Nature News Standard Article in Nature News & Comment
So, You can use id or xpath to retrieve the element text as follows:
Using id:
String s = driver.findElement(By.id("nav_20")).getText();
System.out.println(s);
Using xpath:
String s1 = driver.findElement(By.xpath("//span[#id='nav_20']")).getText();
System.out.println(s1);
css=a[href*='javascript:submitForm'] > span.p_textOutput
Try the above CSS Selector. I am sure it will work out.
Please Let me know is it working or NOT.

Resources