Apply error message to textbox - javascript

i am trying to apply some validation error to controls like textbox. i initially was using qtip.js but for some reason it's not working well. so, i was trying to manually show error at the position i would like to show.
How would i exactly get the coordinates at the right-top corner of a control(eg: textbox as shown in picture) so i can show error message. i tried to use offset feature but to no avail.
var x = $("txtBox1").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);

I think it's best to just place the error right under the textbox using just plain HTML positioning. The manual positioning using JavaScript is not necessary.
Here is a fiddle: https://jsfiddle.net/v0k1jbug/
<input type="text">
<div class="error">Error</div>
Then if you are using JQuery you can show/hide/populate the error message as you wish.
Hope this helps.

jsFiddle : https://jsfiddle.net/jchotdjk/1/
html
<div class="container">
<div class="input-group">
<input type="text" />
<span class="error">Invalid email address</span>
</div>
</div>
CSS
.container {
padding: 25px;
background-color: #9b9;
}
.input-group input{
height: 20px;
}
.input-group .error{
position: relative;
top: -20px;
}
To place the error just above the input and to the right, place the error in a span. Then you need to set the position of the error to relative and then force it up by the total height of the input which I have specified as 20px

What you need to do is the following:
Create 3 elements, a container, an input and an element for the error.
<div class="input__group">
<input type="text">
<span class="error">Error Message.</span>
</div>
Then define the following CSS:
.input__group {
position: relative;
display: inline-block;
margin-top: 50px; /* Since the error position is absolute, you will need
to add some space, in this demo we are using a margin.*/
}
.error {
position: absolute;
bottom: 100%; /* Used to place the element to
the top by the total container's height (100%) */
left: 100%; /* Used to place the element to
the right by the total container's width (100%) */
}
.input__group {
position: relative;
display: inline-block;
margin-top: 50px;
}
.error {
position: absolute;
bottom: 100%;
left: 100%;
color: whitesmoke;
background-color: coral;
}
<div class="input__group">
<input type="text">
<span class="error">Error Message.</span>
</div>

Something like the below could be helpful.
Idea is to have a absolute positioned element inside a relative and then to adjust the position based on top (as per your question). It can be done without even using external library.
Sample to play around with:
$(document).ready(function() {
$("#validate").click(function(e) {
$(".inputForm").find(".inputFormMessage").show();
});
});
.inputForm {
position: relative;
}
.inputFormMessage {
display: none;
position: absolute;
top: -10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="inputForm">
<label for="txtBox">Enter Input:</label>
<input type="text" id="txtBox" />
<span class="inputFormMessage">Input is not valid!</span>
</div>
<div>
<input type="button" id="validate" value="Validate" />
</div>
</div>
Another snippet to play around with (positioning is controlled by Styles and rendering upon action)
window.onload = function() {
// Attach handler to `validate` button
document.querySelector("#validate").onclick = function(e) {
var isValid = false;
var elementToCheck = null;
// Disable if any `message` elements are active
Object.values(document.querySelectorAll(".inputFormRowMessage")).forEach(function(element, index, array) {
element.style.display = "none";
});
// Validate First name
elementToCheck = document.querySelector("#txtBoxFirstName");
isValid = elementToCheck.value.length > 0;
if (!isValid) {
// Show the error message
document.querySelector(".inputFormRowMessageFirstName").style.display = "inline-block";
}
// Validate Last name
elementToCheck = document.querySelector("#txtBoxLasttName");
isValid = elementToCheck.value.length > 0;
if (!isValid) {
// Show the error message
document.querySelector(".inputFormRowMessageLasttName").style.display = "inline-block";
}
// .. do other validations and stylings...
// ...
};
};
.inputForm {
font-family: "Trebuchet MS", Verdana, Tahoma;
font-size: 12px;
}
.inputFormRow {
position: relative;
padding: 10px;
margin: 10px;
}
.inputFormRow > label {
width: 100px;
display: block;
float: left;
}
.inputFormRowMessage {
display: none;
position: absolute;
top: -10px;
padding: 2px;
color: red;
}
<div>
<div class="inputForm">
<div class="inputFormRow">
<label for="txtBoxFirstName">First Name:</label>
<input type="text" id="txtBoxFirstName" />
<span class="inputFormRowMessage inputFormRowMessageFirstName">Please enter First Name.</span>
</div>
<div class="inputFormRow">
<label for="txtBoxLasttName">Last Name:</label>
<input type="text" id="txtBoxLasttName" />
<span class="inputFormRowMessage inputFormRowMessageLasttName">Please enter Last Name.</span>
</div>
<div class="inputFormRow">
<label for="txtBoxAge">Age:</label>
<input type="text" id="txtBoxAge" />
<span class="inputFormRowMessage">Not a valid age format.</span>
</div>
<div>
<input type="button" id="validate" value="Validate" />
</div>
</div>

Related

Two different colors for input text

I have to achieve the output as like below image
Black color text is name and Orange color text is status. Depending on status it can change like Pending --> Orange, Completed-->Green. These things I can able to achieve by having one input tag and span tag inside a div which position is relative
<div style="display: inline-block;position: relative;overflow: hidden;width:100%">
<input
id="input"
class={computedInputClass}
type="text"
role="textbox"
required={required}
autocomplete="off"
value={computedInputValue}
name={name}/>
<span class={computedStatusClass} style={componentStyle}> - {inputStatus}</span>
</div>
The only problem what I am facing is placing the position of status text.
Depending on the length of name text the left of status text also has to be adjusted. I am doing left adjustment with this calculation but its not working
get componentStyle() {
// this.computedInputValue = 'William Thomas';
return `left:${this.computedInputValue.length-2}em`;
}
If my approach is wrong please suggest me for good solution but for sure I have to use <input> tag and I cant remove that also as it is LWC component
Here is what I tried
HTML
<template>
<div style="display: inline-block;position: relative;overflow: hidden;width:100%">
<input
id="input"
class={computedInputClass}
type="text"
role="textbox"
autocomplete="off"
value={computedInputValue}
/>
<span class={computedStatusClass} style={componentStyle}> - {inputStatus}</span>
</div>
</template>
JS
import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
#track inputStatus='Pending';
get computedInputValue() {
return 'William ThomasS';
}
get componentStyle() {
return `left:${this.computedInputValue.length-2}em`;
}
get computedStatusClass()
{
return 'customizedDropdownInputStatusLeft customizedDropdownPendingStatusColor';
}
get computedInputClass() {
return'slds-input';
}
}
CSS
.customizedDropdownInputStatusLeft{
position: absolute;
top:8px
}
.customizedDropdownPendingStatusColor{
color:orange;
}
.customizedDropdownStatusPadding{
padding-left:5px;
}
I believe you can achieve your desired result with the following code.
The key part is a hidden span element and a resizeUserInput function:
hiddenSpan.textContent = userInput.value - copy the input text into the hidden span element.
userInput.style.width = hiddenSpan.offsetWidth + px - get the width of the hidden element and apply it to the width of the user input.
Working example
HTML
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link href="src/styles.css" rel="stylesheet" />
</head>
<body>
<div class="box">
<p>
<span class="hidden-span" id="hidden-span"></span>
<input class='user-input' id="user-input" type="text" value="William Thomas" />
<span> - </span>
<span class="status">Pending</span>
</p>
<div>
<script src="src/index.js"></script>
</body>
</html>
CSS
body,
input {
font-family: sans-serif;
font-size: 16px;
margin: 0;
padding: 0;
}
.box {
border: 1px solid lightgrey;
border-radius: 5px;
display: flex;
padding: 0 10px;
margin: 10px;
justify-content: space-between;
}
.hidden-span {
position: absolute;
height: 0;
overflow: hidden;
white-space: pre;
}
.user-input {
border: none;
min-width: 10px;
outline: none;
}
.status {
color: orange;
}
JS
const px = "px";
const hiddenSpan = document.getElementById("hidden-span");
const userInput = document.getElementById("user-input");
const resizeUserInput = () => {
hiddenSpan.textContent = userInput.value;
userInput.style.width = hiddenSpan.offsetWidth + px;
};
resizeUserInput() // run onload
userInput.addEventListener("input", resizeUserInput); // run on subsequent changes

input type password is immovable

I have this code and the 1st input won't ever move whatever I do the only thing that made it move was float:right; but I don't want it to be like this I even created this div->P so maybe it would move. Has anyone encountered this problem before?
Is it possibly interfearing with my js? That's the only thing I can think of rn
.inner {
display:inline-block;
margin-right:500px;
}
.pswd {
display:inline-block;
margin-right:500px;
}
</style>
</head>
<body>
<div class="P">
<input class="inner" type="password" id="pswd">
<input class="inner" type="button" value="Submit" onclick="checkPswd();"/>
</div>
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "admin";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="A.html";
}
else{
alert("Password incorrect.");
}
}
</script>
This should work if you use the ID selector rather than the class selector (i.e. use # rather than .):
#pswd {
display:inline-block;
margin-right:500px;
}
There are multiple ways to center-align a div both vertically and horizontally on the screen.
I have used display:flex for the same.
'use-strict'
function checkPswd(form) {
const confirmPassword = "admin";
let passwordProvided = form.elements.newPassword.value;
if (passwordProvided === confirmPassword) {
// If correct
} else {
// If failure
}
// to prevent default action
return false;
}
.form--wrapper {
width: 150px;
height: 150px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
form {
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
width: 100%;
border: 2px dashed orange
}
<div class="form--wrapper">
<form name="change-password" onsubmit="return checkPswd(this)">
<input class="inner" name="newPassword" type="password">
<input class="inner" type="submit" value="Submit" />
</form>
</div>

Notification show as input textbox click with jquery patterns

I don't know that I will explain my question well or not because I'm new on stack overflow. I've read the T&C and have tried my best to explain what I want to accomplish. I hope you understand what I'm asking.
I would like to create a system using javascript or jQuery that will display a popup box on the top or bottom of a browser window with custom text and colors defined in my css styles. The "notification" would tell users to about what they need to do in the text box like "Write your email" etc.
This is the code that will show you what I'd like them to look like:
<div class="warning"id="notification"><span>This is default message show first time</span></div>
<div class="information" id="notification"><span>Enter your registered Email ID</span></div>
<div class="error" id="notification"><span>Email ID is incorrect</span></div>
<div class="error" id="notification"><span>Email is correct - good : show me for 5 sec only after I will hide automatically if I am in green else show until cursor inside textbox.</span></div>
<input type="text" name="email" id="username"/>
<input type="text" name="mobile" id="phone"/>
<input type="submit" id="ok" name="done"/>
<style>#notification {
position:fixed;
width: 100%;
text-align: center;
z-index:99;
overflow:hidden;
}
#notification h2{
font-size:16px;
font-weight:400
}
/*#notification.showNote{
width:50%;
left:230px
}*/
/*error, info, notice, alert*/
.success,.warning,.error,.information{display: block; position: relative; padding:5px 20px}
.information{background-color:#3bafda}
.success{background-color:#8cc152}
.warning{background-color:#f6bb42}
.error{background-color:#e9573f}
.notify h2{color:#fff}</style>
Some tips:
ids are unique in each page. You can not define multiple elements with just one id. Instead, You should use class attribute`.
To do something after some seconds, You should use setTimeout function
You must know about jQuery selectors and some of its functions. Read available tutorials on the web.
To validate a value, You must know Regex
A simple working example of your question is this. Hope it helps
let time2Hide = 5000;
function f(selector) {
$(selector).show();
setTimeout(() => {
$(selector).hide();
}, time2Hide);
}
f("#warning");
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function onSubmit() {
let email = $("#email").text()
if(!email) {
f("#information" )
}
else if(validateEmail(email)) {
f("#success");
}
else {
f("#error")
}
}
/**********************************************/
/* notification styles */
.notification {
position: fixed;
width: 100%;
text-align: center;
z-index: 99;
overflow: hidden;
}
.notification h2 {
font-size: 16px;
font-weight: 400
}
/*#notification.showNote{
width:50%;
left:230px
}*/
/*error, info, notice, alert*/
#success,
#warning,
#error,
#information {
display: none;
position: relative;
padding: 5px 20px
}
#information {
background-color: #3bafda
}
#success {
background-color: #8cc152
}
#warning {
background-color: #f6bb42
}
#error {
background-color: #e9573f
}
.notify h2 {
color: #fff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning" class="notification">
<span>This is default message show first time</span>
</div>
<div id="information" class="notification">
<span>Enter your registered Email ID</span>
</div>
<div id="error" class="notification">
<span>Email ID is incorrect</span>
</div>
<div id="success" class="notification">
<span>Email is correct - good : show me for 5 sec only after I will hide automatically if I am in green else show until cursor inside textbox.</span>
</div>
<hr><br><br><br>
<input type="email" name="email" id="username" />
<input type="phone" name="mobile" id="phone" />
<input type="submit" id="ok" name="done" onclick="onSubmit()"/>
let time2Hide = 5000;
function hideAll() {
$("#error").hide();
$("#warning").hide();
$("#success").hide();
$("#information").hide();
}
function show(selector) {
hideAll();
$(selector).show();
}
function showNHide(selector) {
hideAll();
$(selector).show();
setTimeout(() => {
$(selector).hide(); show("#warning");
}, time2Hide);
}
$("#username")
.on("input click", () => {
show("#information");
})
.on("input", () => {
let email = $("#username").val();
if (!email) {
show("#information");
} else if (validateEmail(email)) {
showNHide("#success");
} else {
show("#error");
}
})
.on('focusout', () => {
show("#warning");
});
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function onSubmit() {
let email = $("#username").val();
if (!email) {
show("#information");
} else if (validateEmail(email)) {
showNHide("#success");
} else {
show("#error");
}
}
show("#warning");
/**********************************************/
/* notification styles */
.notification {
position: fixed;
width: 100%;
text-align: center;
z-index: 99;
overflow: hidden;
}
.notification h2 {
font-size: 16px;
font-weight: 400
}
/*#notification.showNote{
width:50%;
left:230px
}*/
/*error, info, notice, alert*/
#success,
#warning,
#error,
#information {
display: none;
position: relative;
padding: 5px 20px
}
#information {
background-color: #3bafda
}
#success {
background-color: #8cc152
}
#warning {
background-color: #f6bb42
}
#error {
background-color: #e9573f
}
.notify h2 {
color: #fff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning" class="notification">
<span>This is default message show first time</span>
</div>
<div id="information" class="notification">
<span>Enter your registered Email ID</span>
</div>
<div id="error" class="notification">
<span>Email ID is incorrect</span>
</div>
<div id="success" class="notification">
<span>Email is correct - good : show me for 5 sec only after I will hide automatically if I am in green else show until cursor inside textbox.</span>
</div>
<hr><br><br><br>
<input type="email" name="email" id="username" />
<input type="phone" name="mobile" id="phone" />
<input type="submit" id="ok" name="done" onclick="onSubmit()" />

Use percentage instead of px as value for script [duplicate]

Is it possible to set the height/width of an element in percent using JavaScript or jQuery?
document.getElementById('header').style.width = '50%';
If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.
jQuery way -
$("#id").width('30%');
I always do it like this:
$("#id").css("width", "50%");
The question is what do you want the div's height/width to be a percent of?
By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.
So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:
obj.style.width = '50%';
Yes, it is:
<div id="myid">Some Content........</div>
document.getElementById('myid').style.width = '50%';
Also you can use .prop() and it should be better because
Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.
$(elem).prop('width', '100%');
$(elem).prop('height', '100%');
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>

How to set width of a div in percent in JavaScript?

Is it possible to set the height/width of an element in percent using JavaScript or jQuery?
document.getElementById('header').style.width = '50%';
If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.
jQuery way -
$("#id").width('30%');
I always do it like this:
$("#id").css("width", "50%");
The question is what do you want the div's height/width to be a percent of?
By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.
So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:
obj.style.width = '50%';
Yes, it is:
<div id="myid">Some Content........</div>
document.getElementById('myid').style.width = '50%';
Also you can use .prop() and it should be better because
Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.
$(elem).prop('width', '100%');
$(elem).prop('height', '100%');
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>

Categories

Resources