Difficulties with displaying error messages - javascript

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");
}
});

Related

Validate only visible fields in a form

I am validating one form. when required fields are not entered it will return alert.its working fine.
Now I have hide some form fields by adding ng-class,when I click submit I don't want to validate hidden fields I want to validate only those fields which are not having hidden class.
These are my inputs:
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.name" />
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.id"/>
</section>
<section>
<input class="required" type="text" ng-model='currentData.age'/>
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model='currentData.gender'/>
</section>
<section>
<input class="required" ng-model='currentData.description'/>
</section>
Here am validating my fields :
$form.find('input.required').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
I have added `:visible` its working good.But that wont be a proper solution I guess.Because if there are multiple tabs which is not having `hidden class`means, it will validate only current tab user currently viewing.
$form.find('input.required:visible').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
Any other suggestions?
$('form').find('input.required').parent('*:not(".hidden")').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
assuming $('form') is <form></form>,
otherwise it should be something like
$('#form') for <div id="form"></div>
Got solution:
$form.find('section').not(".hidden").closest('input.required').each(function() {})
I just changed my elements order.

How do I allow form submission with the submit button and the enter key?

I want the user to be able to submit a form by clicking the submit button or the enter key. I'm using jQuery and here's my code:
<input id="weather"/>
<button id="myButton" type="text">Response</button>
</div>
<script type="text/JavaScript">
$("#myButton").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#myButton").submit();
}
});
document.getElementById("myButton").onclick = function() {
if (document.getElementById("weather").value.toLowerCase() != "nice" && document.getElementById("weather").value.toLowerCase() != "crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if (document.getElementById("weather").value.toLowerCase() == "nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
};
</script>
Wrap the whole thing in a form tag and change the button type to submit. Enter will then submit the form.
<form>
<input id="weather"/>
<button id="myButton" type="submit">Response</button>
</form>
JSFiddle
<input type="text" id="weather" />
<input type="button" id="myButton" value="Response"/>
The onclick script should be
document.getElementById("myButton").onclick(function(){
if (document.getElementById("weather").value.toLowerCase() !="nice" && document.getElementById("weather").value.toLowerCase() !="crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
}
else if (document.getElementById("weather").value.toLowerCase() =="nice"){
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
You should use submit type of button. It should not be a text type.
Best way is to wrap input and button with form and check input only in case of form submit like:
$(function() {
$("#weatherForm").submit(function(event) {
event.preventDefault();
var $weatherElement = $('#weather');
if ($weatherElement.val() != "Nice" && $weatherElement.val() != "Crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if ($weatherElement.val() == "Nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" id="weatherForm">
<input id="weather" name="weather" />
<input type="submit" id="myButton" value="Response" />
</form>

Angular form validation with skip some fields

I have a page which has a form in it named as profile updation and when a user comes to this page for any updation of his profile that time he only update 1 or 2 fields so every time form checks the form is valid or not then only saves in db, but I want to save if password and confirm password fields are not updated then also update his profile, but also when he wants to change password that time save button will get disabled and checks validation after that update the profile.
Means when user update only name that time also update the profile and also user update the password that time first check validation and then update the profile.
Save and isValid check:
app.controller('DemoCtrl', function($scope, $http) {
$scope.saveProfile = function(){
if($scope.profile.$valid){
ngProgress.start();
user.saveProfile($scope.currentUser.details,function(response){
angular.copy(response,shared.data.currentUser);
notification.success($filter("il8n")("_ProfileUpdateMessage_"));
ngProgress.done();
});
}
}
$scope.isValidForm = function(){
//if(($scope.profile.confirmpassword && $scope.profile.newpassword && $scope.profile.newpassword.$modelValue !== $scope.profile.confirmpassword.$modelValue))
// return true;
if(!$scope.profile.$valid){
if(($scope.profile.confirmpassword && $scope.profile.newpassword && $scope.profile.confirmpassword.$modelValue && $scope.profile.newpassword.$modelValue && ($scope.profile.newpassword.$modelValue.length == 0 || $scope.profile.confirmpassword.$modelValue.length == 0))){
return false;
}
if(($scope.profile.confirmpassword && $scope.profile.newpassword && $scope.profile.confirmpassword.$modelValue && $scope.profile.newpassword.$modelValue && $scope.profile.newpassword.$modelValue === $scope.profile.confirmpassword.$modelValue)){
return false;
}
}
if($scope.profile.$valid && $scope.profile.$dirty)
return false;
if($scope.profile.newpassword.$invalid || $scope.profile.newpassword.$dirty && $scope.profile.confirmpassword.$invalid || $scope.profile.confirmpassword.$dirty){
//$scope.profile.newpassword.$valid;
//$scope.profile.confirmpassword.$valid;
return false;
}
//if($scope.profile.newpassword.empty && $scope.profile.confirmpassword.empty ){
// return true;
//}
return true;
}
});
Find plnkr here.
As I see it, you want form where user can update few fields then update them?
About password change, I think you should split profile information from password change into two separate forms, where user can change password without changing other data. Then if user wants to change other user data (which is binded to ng-model and placed already into text boxes), then user change data and saves them.
Problem solved. If u want so, i can try to edit your plunk and show how it would look like :)
Plunk - New format
<form ng-submit="SAVE FUNCTION HERE">
<fieldset>
<div class="row">
<div class="col-sm-4">
<label class="proxima-nova nova-bold form-label">Change Password</label>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label data-ng-class="{'state-error': profile.newpassword.$invalid && profile.newpassword.$dirty && profile.newpassword.$error.strongPassword}">
<input type="password" class="form-control" placeholder="Enter new password" data-ng-model="currentUser.details.password" name="newpassword" data-password-check="currentUser.details.password" />
</label>
<div class="ng-cloak invalid" data-ng-show=" profile.newpassword.$error.strongPassword && profile.newpassword.$dirty && profile.newpassword.$invalid">
Password should contain atleast one special character, number, uppercase letter, and atleast 8 characters.
</div>
</div>
<div class="col-sm-3">
<label data-ng-class="{'state-error': profile.confirmpassword.$dirty && currentUser.details.password != currentUser.details.password_confirmation}">
<input type="password" class="form-control" placeholder="Confirm password" data-ng-model="currentUser.details.password_confirmation" name="confirmpassword" />
</label>
<div class="ng-cloak invalid" data-ng-show="profile.confirmpassword.$dirty && currentUser.details.password != currentUser.details.password_confirmation">
Passwords do not match
</div>
</div>
</div>
</fieldset>
</form>
Also in form fieldset you can add save button with type="submit", then that button will call that function which is defined into form tag
<form ng-submit="SAVE FUNCTION HERE">

Form is submitting even if validation fails

Below is a code of a simple html form and javascript code for checking if the fields are empty or not, when user clicks the submit button.
The problem is, that the form is submitted, even if the necessary fields are not filled in.
As you can see, I am just a beginner with JS coding, so I don't know, if the problem is in if/else statements, somewhere else in the JS code or if the form is not set up properly.
<script>
function preveri(pov){
var preveriime = pov.ime.value;
var preverirojstvo = pov.rojstvo.value;
var preverimail = pov.email.value;
var preverikategorijo = pov.kategorija.value;
if (preveriime == "") {
document.getElementById('imeA').style.display="block";
}
if (preverirojstvo == "") {
document.getElementById('datumA').style.display="block";
}
if (preverimail == "") {
document.getElementById('emailA').style.display="block";
}
if (preverikategorijo == "") {
document.getElementById('kategorijaA').style.display="block";
}
if(preveriime != "" && preverirojstvo != "" && preverimail != "" && preverikategorijo != ""){
document.pov.submit();
}
else{
return false;
}
}
</script>
<h4>OBRAZEC ZA SPLETNE PRIJAVE</h4>
<br/>
<form name="pov" method="POST" action="thankUPage.php">
<input name="ime" type="text" placeholder="Ime in Priimek"></input>
<input name="rojstvo" type="text" placeholder="Datum rojstva"></input>
<input name="email" type="text" placeholder="E-pošta"></input>
<input name="kategorija" type="text" placeholder="Kategorija"></input>
<textarea name="povprasaj" placeholder="Povprašaj"></textarea>
<input type="submit" name="submit" id="submit" value="Pošlji!" onclick="preveri(pov)" />
</form>
<div id="imeA" class="imeA">Obvezno polje!</div>
<div id="datumA" class="datumA">Obvezno polje!</div>
<div id="emailA" class="emailA">Obvezno polje!</div>
<div id="kategorijaA" class="kategorijaA">Obvezno polje!</div>
</div>
Tnx in advance!
You're returning false on the click event. You need to bind your callback function to the form's submit event, so returning false will cancel the form's submission.
Pressing "enter" while in a form field will submit the form and might not trigger the click event on the submit button.
<form name="pov" method="POST" action="thankUPage.php" onsubmit="return preveri(this);" >

Error Message will not show in JQuery if it is NOT the first one encountered

I have a feedback form and I am replicating some code to check for values in text inputs and textareas. I have a name field and a feedback field. The errors hide on document load and at the start of a click function The name one shows as expected, but I cannot get the feedback one to show.
I set the errors to show on document load but hide onclick and I could get the feedback error to show if I filled in the name(the name error would hide, as expected).
HTML form.
<div class="slide-out-div">
<h3>Give us Feedback</h3>
<a class="handle" href="#">Content</a>
<p>We would love to hear your ideas to make the site more user-friendly or efficient for your benefit.</p>
<form name="feedbackform" id="feedbackform" action="" method="post">
<label for="feedname">Name:</label>
<input type="text" name="feedname" id="feedname" style="width:100%" /><br />
<label class="error" for="feedname" id="feedname_error">Please insert your name.</label> <br />
<label for="feedback">Feedback:</label><br />
<textarea name="feedback" id="feedback" style="width:100%;height:150px;"></textarea>
<label class="error" for="feedback" id="feedback_error">Please insert your some feedback.</label> <br />
<input type="submit" value="Submit Feedback" id="feedbacksubmit" />
</form>
<div id="feedwrap"></div>
</div>
JQuery Process
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
return false;
}
Var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
return false;
}
//process
return false;
});
Any help would be greatly appreciated.
It's becasue you are returning false as soon as you complete the validation of the name. That'll stop the execution of the function there and the second error message will not show up. May be you can write something like this.
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var returnvalue = true;
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
returnvalue = false;
}
var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
returnvalue = false;
}
//process
return returnvalue ;
});
It appears that if I move the error above the textarea is shows but otherwise it does not, it must show but not visible to the user.

Categories