My Name:<input class="clr" id="name" type="text" /><span class="clr" id="name_error">Name is required</span> <br /><br />
My Email Adress:<input class="clr" id="email" type="text" /><span class="clr" id="email_error">Email is required</span> <br /><br />
My Organisation Name:<input class="clr" id="organisation" type="text" /><span class="clr" id="org_error">Organisation is required</span> <br /><br />
I have 3 input fields. I'm using span to display error message when submitting empty fields.
My problem is, if name field is empty, we should get "Name is required" error, if email field is empty, we should get "email is required" error and so on.
For this, I'm writing below code.
if (name == "")
$("#name_error").show();
else
$("#name_error").hide();
if (email == "")
$("#email_error").show();
else
$("#email_error").hide();
if (organisation == "")
$("#org_error").show();
else
$("#org_error").hide();
Is there any way to reduce if/else statements?
Using jQuery effectively, you can do this way.
$('input.clr').each(function(){
if ($(this).val() == "")
$(this).next('span.clr').show();
});
Before that, we need to hide them this way:
$('span.clr').hide();
You could do this :
var obj = window; // or something else, depending on your scope
['name', 'email', 'organisation'].forEach(function(v) {
var $e = $('#'+v+'_error');
if (obj[v]=="") $e.show();
else $e.hide();
});
Note that
this supposes a little more strictness, with the replacement of "org" by "organisation"
I tried to mimic your code but changing at the root (i.e. where you fill the variables like name) would allow for a simpler code
if you know the DOM doesn't change and the error span always follows the input, Praveen's answer is probably simpler and suited
Related
When i try to call the form id's and tell the code if i click submit and the username and password fields are empty display "Please enter both login and password." and when there's text on the fields it displays "please stand by" None of this is displaying and i'm not sure what i'm doing wrong
$(document).ready(function() {
$("#login").click(function() {
$("#login").toggleClass('minus');
$("form").slideToggle(1000);
$("form").submit(function(){
if ("#username" == "" || "#pw" == "") {
$("#error").text("Please enter both login and password.");
} else {
$("#error").text("Please stand by");
}
});
}); // end click
}); // end ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="pw">Password:</label>
<input type="password" name="pw" id="pw">
</p>
<p>
<input type="button" value="Submit">
</p>
<!-- placeholder for response if form data is correct/incorrect -->
<p id="error"> </p>
</form>
You are not comparing the value of these elements but are comparing if f.e. the string "#username" is equal to "", which it of course will never be. You need to actually retrieve the value of your element by using val().
So you might instead do this:
if ($("#username").val() == "" || $("#pw").val() == "") {
$("#error").text("Please enter both login and password.");
}
Also maybe have a look at the documentation for further help http://api.jquery.com/val/
Here is fiddle
Also make your input submit button as type "submit" and check the ".val()" of your inputs
$("#login").click(function() {
$("#login").toggleClass('minus');
$("form").slideToggle(1000);
}); // end click
$("form").submit(function(e) {
e.preventDefault();
if ( $("#username").val() === "" || $("#pw").val() === "" ) {
$("#error").text("Please enter both login and password.");
} else {
$("#error").text("Please stand by");
}
});
This question already has an answer here:
Why doesn't my equality comparison using = (a single equals) work correctly? [duplicate]
(1 answer)
Closed 5 years ago.
I'm trying to build a form that will check (live) to see whether a person has mismatched a string when entered into text fields. The practice is a user entering data into a password form.
HTML Below:
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" value="" placeholder="Password" onKeyUp="checkPasswordStrength();">
</div>
<div class="form-group">
<input type="password" name="vPass" id="cpassword" class="form-control" value="" placeholder="Password">
<span id="output"></span>
</div>
And below is the jQuery used:
<script type ="text/javascript">
$("#cpassword").blur(function checkPassMatch(){
var originEmpt = $("#password").text(""); // Checking if input is empty
var origin = $("#password").text(); // Password
var conf = $("#cpassword").text(); // Confirm password
if (origin != conf){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else {
$("#output").html("");
}
if (originEmpt){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
$("#output").html("");
}
})
</script>
Through debugging, if I totally remove the first if else statement from the jQuery, I can receive the $("output").html(); as desired.
I have tried for both input fields:
$("#password").text() / .val(); / .html(); / .innerHTML();
But the code still fails to check whether one input field matches another. Any ideas why?
Cause your second checks output overrides the first one. You need to nest it:
if (origin != conf){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else if (!originEmpt){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
$("#output").html("");
}
I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.
I want to clear the text field when the user clicks on that
<input name="name" type="text" id="input1" size="30" maxlength="1000" value="Enter Postcode or Area" onfocus=="this.value=''" />
Unless you are doing something specific where you only want to clear onclick, I would suggest (as others have noted) to use the onfocus actions instead. This way if someone is using tab to navigate it will also clear the default text.
You can also use onblur to check if it's empty to bring it back:
<input type="text" value="Default text" name="yourName" onfocus="if(this.value == 'Default text') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Default text'; }">
To do this you will need to use a scripting language, probably javascript. Here an example
<input type='text' value'Some text' onclick='javascript: this.value = ""' />
Hope this helps.
Edit:
To meet what David is explain here is a second example in case that is what you are looking for
<script type='javascript'>
var clear = true;
function clear(obj)
{
if(clear)
{
obj.value = '';
clear = false;
}
}
</script>
<input type='text' value'Some text' onfocus='clear(this);' />
Using jQuery library:
<input id="clearme" value="Click me quick!" />
$('#clearme').focus(function() {
$(this).val('');
});
Or you can simply use the placeholder attribute
For example<input name="name" type="text" id="input1" size="30" maxlength="1000" placeholder="Enter Postcode or Area"/>
You can use <input ... onfocus="this.value='';"/>.
This way, the field will be cleared when it gains focus. However, if you only want to clear it when user clicks on it (i.e. not when the field gains focus with the keyboard for example), then use onclick instead of onfocus.
However, as pointed by David Dorward in a comment, this behavior may not be expected by the user. So be careful to set this feature on really specific fields (such as search field).
This is how I use it for a temperature converter/calculator - when the user types (keyup), the text input box calculates using the assigned function; when the user selects the other text input (there are only two inputs), the selected text input will clear.
HTML:
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" onfocus="this.value='';" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" onfocus="this.value='';"placeholder="Temperature (Fahrenheit)" />
</p>
JavaScript:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}
try this ,it worked for me
add this into your input tag
<code>
onfocus="this.value='';"</code>
for example if your code is
<code>
<input type="text" value="Name" /></code>
use it like this
<code><input onfocus="this.value='';" type="text" value="Name" /></code>
function Clear (x) {if (x.cleared) {} else {x.value = ""; x.cleared = true}}
onfocus = "Clear (this)"
Add a following script to your js file:
var input1 = document.getElementById("input1")
input1.onfocus = function() {
if(input1.value == "Enter Postcode or Area") {
input1.value = "";
}
};
input1.onblur = function() {
if(input1.value == "") {
input1.value = "Enter Postcode or Area";
}
};
I see this all over the web, but was wondering if anyone has the JavaScript code for the EASIEST way to show input value on blur, but hide in on focus.
This always worked for me:
<input
type="text"
value="Name:"
name="visitors_name"
onblur="if(value=='') value = 'Name:'"
onfocus="if(value=='Name:') value = ''"
/>
Since this still comes up on google, I'd like to point out that with HTML 5 you can use the placeholder attribute with an input to achieve this in one piece of html.
<input type="text" id="myinput" placeholder="search..." />
Placeholder is now standard across modern browsers, so this really would be the preferred method.
I prefer jQuery way:
$(function(){
/* Hide form input values on focus*/
$('input:text').each(function(){
var txtval = $(this).val();
$(this).focus(function(){
if($(this).val() == txtval){
$(this).val('')
}
});
$(this).blur(function(){
if($(this).val() == ""){
$(this).val(txtval);
}
});
});
});
It is modified Hide Form Input Values On Focus With jQuery by Zack Perdue.
The simplest approach I know of is the following:
<input
name="tb"
type="text"
value="some text"
onblur="if (this.value=='') this.value = 'some text'"
onfocus="if (this.value=='some text') this.value = ''" />
If you don’t care about valid HTML, you use the placeholder attribute. It will work out of the box on a Safari, and you can add some unobtrusive JS to mimic this behavior in other browsers.
More reading:
http://www.beyondstandards.com/archives/input-placeholders/ (JS implementation)
http://lab.dotjay.co.uk/experiments/forms/input-placeholder-text/
And google. ;-)
The solution is similar to the one Josh Stodola posted, but it’s more flexible and universal.
This is what I use on my blog. Just go there and check out the source code behind.
function displaySearchText(text){
var searchField = document.getElementById('searchField');
if(searchField != null)
searchField.value = text;
}
Your input field should look something like this:
<input id='searchField' name='q' onblur='displaySearchText("Search...");' onfocus='displaySearchText("");' onkeydown='performSearch(e);' type='text' value='Search...'/>
For all browsers:
<input onfocus="if(this.value == 'Your value') { this.value = '';}" onblur="if(this.value == '') { this.value = 'Your value';}" value="Your value" type="text" name="inputname" />
For newest version of browsers:
<input type="text" name="inputname" placeholder="Your value" />