Javascript to replicate placeholder functionality in input text - javascript

When a textbox is created, default, gray text (#888) is given a displayed. When it is given focus, the value should disappear and start showing the typed value. I've written the code for this problem and it is as follows:
<html>
<script type="text/javascript">
function Focus(i) {
if (i.value == i.defaultValue) {
i.value = "";
i.style.color = "#000";
}
}
function Blur(i) {
if (i.value == "") {
i.value = i.defaultValue;
i.style.color = "#888";
}
}
</script>
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="Focus(this)" onblur="Blur(this)" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;"
value="lastname" onfocus="Focus(this)" onblur="Blur(this)" />
</body>
</html>
But, here whenever the textbox is focused, the value is disappearing. What should I do in order to correct this? Even though the text box is under focus, the value should not disappear and the value should disappear only when I start typing in it. I'm a new user so I can't post screenshots.

what you want is called placeholder.
use it like this:
<input type="text" name="enterfirstname" placeholder="First Name" />
<input type="text" name="enterlastname" placeholder="Last Name" />

Try with
<html>
<head>
<script type="text/javascript">
function Focus(i) {
if (i.value == i.defaultValue) {
i.value = "";
i.style.color = "#000";
}
}
function Blur(i) {
if (i.value == "") {
i.value = i.defaultValue;
i.style.color = "#888";
}
}
</script>
</head>
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="Focus(this)" onblur="Blur(this)" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;"
value="lastname" onfocus="Focus(this)" onblur="Blur(this)" />
</body>
</html>
Note:script tags not inside body/head elements create invalid HTML

Try using "onkeydown" as following...
function Focus(cntrl,value)
{
if (cntrl.value == value)
{
cntrl.value = '';
cntrl.style.color = '#000';
}
}
function Blur(cntrl,value)
{
if (cntrl.value == '')
{
cntrl.style.color = 'gray';
cntrl.value = value;
}
}
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;" value="First Name" onkeydown="Focus(this,'First Name')" onblur="Blur(this,'First Name')" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;" value="lastname" onkeydown="Focus(this,'lastname')" onblur="Blur(this,'lastname')" />
</body>

Related

Add html attribute if the input value meet requirements

Let say I have two input.
When I key-in value in input1 for example 0.4 and meets the requirement then the input2 will remove the readonly attribute. Meanwhile if I input value in input1 is 0.3 then the input2 attribute will become readonly again.
It doesnt work. Maybe i missed out anything here
$(".input1").keydown(function() {
var dInput = $(this).val();
if (dInput >= 0.4 && dInput <= 0.6) {
$(".input2").attr('readonly', true);
} else {
$(".input2").removeAttr("readonly");
}
});
function isNumberKey(e) { // stub
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />
<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />
1: Use keyup function, as the value fills up in a field later and you are trying to capture at keydown
2: I have switched the if and else block statements as per your description. Your original code contradicts what you are saying here.
$(".input1").keyup(function() {
var dInput = $(this).val();
if(dInput >= 0.4 && dInput <= 0.6)
{
$(".input2").removeAttr("readonly");
}
else
{
$(".input2").attr('readonly',true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" o id="input1" name="input1" value="" />
<input type="text" class="input2" id="input2" name="input2" value="" readonly />
You are setting the attribute in the wrong condition. I also prefer input event instead of keydown here:
$(".input1").on('input', function() {
var dInput = $(this).val();
if(dInput >= 0.4 && dInput <= 0.6){
$(".input2").removeAttr("readonly");
}
else{
$(".input2").attr('readonly', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" id="input1" name="input1" value="" />
<input type="text" class="input2" id="input2" name="input2" value="" readonly />
use keyup
function isNumberKey(e){
}
$(".input1").keyup(function() {
var dInput = $(this).val();
dInput = parseFloat(dInput);
console.log(dInput);
if(dInput >= 0.4 && dInput <= 0.6)
{
$(".input2").attr('readonly',true);
}
else
{
$(".input2").removeAttr("readonly");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />
<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />

Uncaught TypeError: Cannot read property 'value' of null at signUpValidate (fhe.js:26) at HTMLInputElement.onclick

I am trying to have users enter their information for signing up. I am coming across an error and it looks like I know what the error is but I do not know how to fix it. Someone help, please.
Uncaught TypeError: Cannot read property 'value' of null at signUpValidate (fhe.js:26) at HTMLInputElement.onclick
HTML Code:
<!DOCTYPE html>
<html lang="en">`enter code here`
<head>
<script type="text/javascript" src="fhe.js"></script>
<link rel="stylesheet" href="fheCss.css"/>
<meta charset="UTF-8">
<title>Sign Up Page</title>
<h1>Family Home Evening</h1>
<h3>Sign Up</h3>
</head>
<body class="backgroundPic">
<form class="mySignUpForm">
<input type="text" placeholder="First Name" name="firstName" required/><br><br>
<input type="text" placeholder="Last Name" name="lastName" required/><br><br>
<input type="text" placeholder="Username" name="signUpUserName" pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{8,20}$" required/><br><br>
<input type="text" placeholder="Password" name="signUpPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required/><br><br>
<input type="text" placeholder="Verify Password" name="signUpVerPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required/><br><br>
<input type="button" value="Sign up" id="signup" onclick="signUpValidate()"/><br><br>
Back to Login<br><br>
</form>
<h4>Username: Username must be between 8 to 20 character<br><br>
Password: Password must contain 1 uppercase, lowercase and number</h4><br><br>
</body>
</html>
JS Code:
var signUpAttempt = 3;
function signUpValidate() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var signUpUserName = document.getElementById("signUpUserName").value;
var signUpPassword = document.getElementById("signUpPassword").value;
var signUpVerPassword = document.getElementById("signUpVerPassword").value;
if (firstName == "Ashish" &&
lastName == "Pokhrel" &&
signUpUserName == "ashishpokhrel" &&
signUpPassword == "ashishpokhrel69" &&
signUpVerPassword == "ashishpokhrel69"){
alert("Signed Up Successful");
window.location = "login.html";
return false;
}
else {
signUpAttempt --;
alert("Please fill out correct input." + "You have " + signUpAttempt + "attempt.");
if(signUpAttempt == 0){
document.getElementById("firstName").disabled = true;
document.getElementById("lastName").disabled = true;
document.getElementById("signUpUserName").disabled = true;
document.getElementById("signUpPassword").disabled = true;
document.getElementById("signUpVerPassword").disabled = true;
document.getElementById("signup").disabled = true;
return true;
}
}
}
You are using document.getElementById() to fetch the value from the form, but you haven't provided the id attribute in the input elements.
<input type="text" id="firstName" placeholder="First Name" name="firstName" required/><br><br>
<input type="text" id="lastName" placeholder="Last Name" name="lastName" required/><br><br>
<input type="text" id="signUpUserName" placeholder="Username" name="signUpUserName" pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{8,20}$" required/><br><br>
<input type="text" id="signUpPassword" placeholder="Password" name="signUpPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required/><br><br>
<input type="text" id="signUpVerPassword" placeholder="Verify Password" name="signUpVerPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required/><br><br>
You're using document.getElementById to get your elements, but you haven't defined IDs on the elements themselves (in the HTML). Note that an element's name is not the same as its ID.
The problem is, that you are trying get getElementById, but you have no element with that ID, so you need to add an ID on all the input fields you are trying to get the data from
<!DOCTYPE html>
<html lang="en">`enter code here`
<head>
<script type="text/javascript" src="fhe.js"></script>
<link rel="stylesheet" href="fheCss.css"/>
<meta charset="UTF-8">
<title>Sign Up Page</title>
<h1>Family Home Evening</h1>
<h3>Sign Up</h3>
</head>
<body class="backgroundPic">
<form class="mySignUpForm">
<input type="text" placeholder="First Name" name="firstName" id="firstName" required/><br><br>
<input type="text" placeholder="Last Name" name="lastName" id="lastName" required/><br><br>
<input type="text" placeholder="Username" name="signUpUserName" id="signUpPassword" pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{8,20}$" required/><br><br>
<input type="text" placeholder="Password" name="signUpPassword" id="signUpPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required/><br><br>
<input type="text" placeholder="Verify Password" name="signUpVerPassword" id="signUpVerPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required/><br><br>
<input type="button" value="Sign up" id="signup" onclick="signUpValidate()"/><br><br>
Back to Login<br><br>
</form>
<h4>Username: Username must be between 8 to 20 character<br><br>
Password: Password must contain 1 uppercase, lowercase and number</h4><br><br>
</body>
</html>

javascript set new data value

I have 2 input boxes.
When I input a value into the first one, the javascript function checkMyKad() is triggered.
checkMyKad() gets value in first input box, edits it, and alerts new value.
I want new to be set into second input box. How do I get new value to be shown in 2nd input box?
<div class="form-group" style="color:#0000FF; margin-left:160px;" >
<input type="text" placeholder="Please input value" id="myKadC" maxlength="4" size="10" onchange="checkMyKad()" required>
<input type="text" id="newVal" maxlength="20" size="20"/>
</div>
javascript function
function checkMyKad() {
var mykadC = $('#myKadC').val();
var newVal='Value is : '+'-'+mykadC;
alert(newVal);
$('#newValId').val(newVal);
}
You seem to target the wrong id, it should be $('#newVal')
function checkMyKad() {
var mykadC = $('#myKadC').val();
var newVal='Value is : '+'-'+mykadC;
alert(newVal);
$('#newVal').val(newVal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" style="color:#0000FF; margin-left:160px;" >
<input type="text" placeholder="Please input value" id="myKadC" maxlength="4" size="10" onchange="checkMyKad()" required>
<input type="text" id="newVal" maxlength="20" size="20"/>
</div>
You have $('#newValId') instead of $('#newVal')
target id is wrong.
$('#newValId').val(newVal); -> $('#newVal').val(newVal);
Personally I would do something like this:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="form-group" >
<h3>Pure JavaScript</h3>
<input type="text" placeholder="Please input value" maxlength="4" size="10" onchange="checkMyKad(this)" required>
<input type="text" maxlength="20" size="20"/>
</div>
<div class="form-group" >
<h3>Using jQuery</h3>
<input type="text" placeholder="Please input value" maxlength="4" size="10" onchange="checkMyKadJQuery(this)" required>
<input type="text" maxlength="20" size="20"/>
</div>
<script type="text/javascript">
function checkMyKad(element) {
   let oldValue = element.value;
   let newValue = 'Value is : -'+oldValue;
   alert(newValue);
   element.nextElementSibling.value = newValue;
}
function checkMyKadJQuery(element) {
let oldValue = $(element).val();
   let newValue = 'Value is : -'+oldValue;
alert(newValue);
$(element).next().val(newValue);
}
</script>
Doing it like that would allow the functions to be reused.

jQuery Validation 4 fields but only required to fill in one

How do I validate in case when where I have 4 fields and only 1 is required. I want the pop up alert message to come up only when all 4 of the fields are left blank when user tries to save form.
My html looks like this.
<input id="txtWorkPhone" name="txtWorkPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput"/>
<input id="txtHomePhone" name="txtHomePhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" required="required" />
<input id="txtEmail" name="txtEmail" maxlength="260" required="required" class="k-textbox standardInput" style="width: 54%;" />
<input id="txtCellPhone" name="txtCellPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
As you can see I marked all the fields are required.. So how should i go about the validation of these fields ?
You can do custom validation as I did. Please check.
$('#submit').click(function () {
var allFilled = true;
$(':input:not(:button)').each(function(index, element) {
if (element.value === '') {
allFilled = false;
}
});
alert(allFilled);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input id="txtWorkPhone" name="txtWorkPhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput"/>
<input id="txtHomePhone" name="txtHomePhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
<input id="txtEmail" name="txtEmail" maxlength="260" class="k-textbox standardInput" style="width: 54%;" />
<input id="txtCellPhone" name="txtCellPhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
<input type="button" id="submit" name="submit" value="Submit">
</form>
On a button click you can simply do this:-
$('button').on('click', function () {
var isEmpty = $('input[required]').filter(function () {
return $.trim(this.value).length > 0
}).length == 0;
if (isEmpty) {
alert('Empty');
} else {
alert('Valid');
}
});
Now here:-
$('input[required]').filter(function () {
return $.trim(this.value).length > 0
})
Checks for all the inputs having some data entered in it. Next if that .length == 0; that means all of the inputs are empty. If that value is greater than 0 that means atleast one of the inputs out of 4 have some value.
Hope it helps!
<form onsubmit="myFunction()">
<input id="txtWorkPhone" name="txtWorkPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput"/>
<input id="txtHomePhone" name="txtHomePhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" required="required" />
<input id="txtEmail" name="txtEmail" maxlength="260" required="required" class="k-textbox standardInput" style="width: 54%;" />
<input id="txtCellPhone" name="txtCellPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
</form>
<script>
function myfunction()
{
if($(#txtWorkPhone).value() === '' && if($(#textHomePhone).value() === '' && if($(#txtEmail).value() === '' && if($(#txtCellPhone).value() === '')
{
// do whatever.
}
}
</script>

Combining javascript functions

hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/

Categories