Javascript if empty not working? - javascript

So I'm trying to change the color of a submit button if the form is empty. So I'm not really sure what I'm doing wrong, since I'm super new, but here's the code I have at the moment.
My partial form
<div class="field">
<input type="email" placeholder="Email">
</div>
<div class="submit">
<input type="submit" value="Reset Password">
</div>
And the JS
if ($('#field'.is(':empty')){
$("#submit").css({"backgroundColor":"black"});
}
Any ideas?

You specified id's in your jQuery when it should be classes -
if ($('.field'.is(':empty'))){ // field is a class, not an id, extra parentheses needed
$("#submit").css({"backgroundColor":"black"});
}
BUT, what you should be doing is checking the value of the email field, because the input makes the field "not empty" which means that the above WILL NEVER WORK
What you need to do is check whether the value of the input has any length, the input's container is not relevant:
if(!$('input[name="email"]').val().length) {
$('#submit').css({"backgroundColor":"black"});
}
EDIT: Finalized code after the OP made his desires clearer (validating e-mail) -
$('input[name="email"]').change(function () {
// regex to validate e-mail address
var regex = /^(([^<>()[\]\\.,;:\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,}))$/;
var validEmail = regex.test( $(this).val() );
if(true == validEmail) {
$('#submit').css({
"background": "#CCCCCC",
"color": "black"
});
}
});

field is a class and you have a syntax error in there. Closing parenthesis after 'field' is missing
Try:
if ($('.field').is(':empty')){
$("#submit").css({"backgroundColor":"black"});
}

Class start with a dot (.)
I'd start with hash #
That is your error

if ($('#field').is(':empty')){
$("#submit").css({"backgroundColor":"black"});
}
You have to close the paren on '#field' so that you get a jquery object back to run the is function on.
Also your 'field' is a class not an id so you need a . not a # selector.
All this of course also depends on you moving the class field to the input, since you don't actually want to check for empty on a div.
So you actually want to do this with your whole code:
<div>
<input class="field" type="email" placeholder="Email">
</div>
<div>
<input class="submit" type="submit" value="Reset Password">
</div>
if ($('.field').is(':empty')){
$(".submit").css({"backgroundColor":"black"});
}

You've got some syntax errors in your code that are keeping it from executing properly:
You are querying the DOM object with an id of field, when you actually assigned your div a class of field. Change your query to $('.field') and it should work.
You neglected to close the parens on your call to the jQuery function $, this will prevent it from properly returning a jQuery object on which to call the is() method.
You are using the jQuery :empty pseudoselector to check if your div has any value entered, but this is not the intended use of this function. Rather, you should use the val() method directly on the input itself to check if the input has had anything entered into itself, and use that as your conditional.
You are querying your submit button with an id of #submit, but your submit input has not been assigned any id. You can either assign it an id of #submit or query it by its type attribute.
With these errors corrected, your code should look like this:
if (!$('.field > input').val()){
$("input[type='submit']").css("backgroundColor", "black");
}
You can check out the working code here

Related

How to set up a specific reject message for a HTML number input element?

I have a loop of html forms <input type="number">, which are basically simple algebra calculations for certain people to fill in. I set the correct answer by limiting both the max and min accepted number to the same number. However, in this way, if the participant gives a wrong answer, the reject message would be something like this: "values must be greater than or equal to ...". It is technically correct but I would like it to only say "incorrect answer, please try again".
Is there any way to do this?
Tried to use something like alert =, but it doesn't meet my requirements.
There's ${parameters.numbers} and ${parameters.answers} in the code because I am using lab.js for the looping. They just mean every time the number in the equation and the answer would change. For example, for the first loop ${parameters.numbers} is 200, and the corresponding answer ${parameters.answers} is 194. lab.js would take care of converting these two parameters to actual numbers for each loop of the form.
<form>
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="${parameters.answers}" min="${parameters.answers}"><br>
<button type="submit">OK</button>
</form>
I try to avoid a dramatic alert dialogue for this, just a non-intrusive message like the default style would be good. If you want to recreate the default "values must be greater than or equal to ..." message, just replace the parameters like this would be good:
<form>
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="194" min="194"><br>
<button type="submit">OK</button>
</form>
I agree with #ElroyJetson that putting the answer inside the tag is not a good idea, but I focused this answer on the way you can set and unset the error message.
I used jQuery, but this can also be done with plain javascript.
The idea is to group the input tag with a span tag (here inside the div with class input-field).
When the value changes or when the form is submitted (in this case when the value changes), you remove any previous error message from the span tag, and then perform the validation. If there is an error you set it in the span tag.
In this way the error message will show below the input element.
To try it fill in an answer and click outside of the input box.
$(document).ready(function(){
$(".input-field").change(function(){
let $inputField = $(this);
let $input = $inputField.find("input");
let $errorMsg = $inputField.find("span.err-msg");
let max = Number($input.data("max"));
let min = Number($input.data("min"));
$errorMsg.text("");
let v = Number($input.val());
if(v < min || v > max){
$errorMsg.text("Invalid answer");
}
});
});
.err-msg{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-field">
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" data-max="194" data-min="194"><br>
<span class="err-msg"></span>
</div>
</form>
Don't set the correct answer with min & max. Instead, just call a javascript function by giving your button tag an onClick to evaluate if the user's answer is correct.
<button onclick="evaluateAnswer('.algebra');" class="submitBtn" >OK</button>
Then your javascript should look something like this:
function evaluateAnswer(cssClass){
var usersAnswer = $(cssClass).val();
var actualCorrectAnswer = 100;
if(usersAnswer == actualCorrectAnswer){
//Do something to proceed
}else{
alert('Sorry, your answer is incorrect');
}
}
Also, I just noticed that you did not want to alert as-in a javascript alert. What you could do is style your message and give it a css class that has the property display:none. Then when you want to show the message when user enters the wrong answer, you can use javascript to remove the class, and also use javascript to add the class back when user enters correct answer.
Edit
You should maybe store your correct answers in a database, evaluate it's correctness serverside, and use Ajax to display the message to prevent users from being able to right-click -> view source and look at the answers in your client-side code
My current solution is like this. There is invisible html elements which stores the correct answer, and the js script validates if the input is correct. Again, the ${} parts represents variables that change in each loop.
html part
<main class="content-horizontal-center content-vertical-center">
<form name="mathEvaluation">
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="answer" type="number" id="answer" required="" size="3"><br>
<button type="submit">OK</button>
<input type="hidden" id="hidenAnswer" value=${parameters.answers} />
</form>
</main>
js part
this.options.validator = function(data) {
if(mathEvaluation.answer.value == mathEvaluation.hidenAnswer.value){
return true
} else {
alert("Please enter the correct number.")
}
}

Can not copy data of HTML tags to JavaScript

For some reasons I am trying to change functionality of submit button. I am facing problem in copying data from HTML tags to JS. The alert generated by following code prints "Undefined" not the data inside tag.
<html>
<body>
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
<script>
function myFunction() {
var TestVar =document.getElementsByClassName('login').value;
alert(TestVar);
}
</script>
</body>
</html>
I know it can be done by form but I need it this way.
try
var TestVar = document.getElementById('email').value
alert(TestVar);
this will get value of text field
getElementsByClassName
^
See that s? Elements is plural. getElementsByClassName returns a NodeList (which is like an Array).
You have to either pick an index from it (foo[0]) or loop over it to get the values.
That said, you don't actually have any elements that are a member of the login class, so it is going to return a Node List of zero length.
You do have an element with id="login", so maybe you should use getElementById instead.
There doesn't seem much point in reading the value from an element that you've hard coded the value for. You might actually want to be using document.getElementById('email')

clear value in an input field with jQuery

Hi I have a number of inputs for telephone numbers, they use the same class and the same show/hide techinque.
I want to be able to clear the contents of the phone number in the input box, i.e. with the class name of input_tel.
However it seems to clear all inputs which I assume is because I am using the following line; input:text , when I put in a class it just fails to work.
My JS and some of my html is below or view a jsFiddle:
$(".contact_numbers").on('click', '.clearnumber', function () {
$(this).siblings('input:text').val('');
});
<div class="telephonetwo contact_numbers">
<input type="text" class="smallinput contactpagelabel" name="faxname" size="10" value="Fax">
<input type="checkbox" class="contact_no" name="showfax" value="Y">
<input type="text" name="fax" size="30" value="016128 13456" class="input_tel">
Hide Clear #
</div>
If you are viewing my JSfiddle click the reveal additional numbers for the clear button to appear.
Update
I want to be able to clear the closest input_tel rather than all of them, as their are multiple numbers.
Thanks in advance
replace:
$(this).siblings('input:text').val('');
with
$(this).siblings('input:text').closest('.input_tel').val('');
JSFIDDLE DEMO
How about targeting the input_tel class then?
$(".contact_numbers").on('click', '.clearnumber', function () {
$(this).parent().parent().find('input.input_tel').val('');
});
Assuming no other input fields have that input_tel class on them.
This should do it...
$(".contact_numbers").on('click', function () {
$(".input_tel").val('');
});
The safe way to clear input fields with jquery
$.fn.noText = function() {/*use the jquery prototype technology to make a chainable clear field method*/
if(this.is('input')){ /*check to c if you the element type is an input*/
this.val('');/*clear the input field*/
}return this;/*means it is chainable*/
};
$('input').noText();

How to erase the text input that the user typed using JavaScript

<div class = "search ui-widget">
<label for = "keyword"></label>
<input type="text" id="keyword" onkeypress="searchKeyPress(event)" placeholder="Search here" required>
<input type="button" id="btnSearch" onclick="loadDeals('search', keyword.value,'')" />
</div>
$('.search input#keyword').Value('');
Basically what I want is to remove the user's input in the text box after the user clicks another menu tab. I tried $('.search input#keyword').Value(''); and $('.search input#keyword').css("value", ''); but it didn't work.
.val() is the right name of the jQUery method, not Value().
You can use jQuery like this:
$('#keyword').val('');
Or you can use plain javascript like this:
document.getElementById('keyword').value = '';
If there are more input fields beside the ones you posted and you want to clear all inputs you can use:
$('.search input').val('');
Here's a pure javascript solution:
document.getElementById('keyword').value = '';
Since HTML id attributes are supposed to be unique I would recommend not using the '#keyword' id in your jquery selector. The solution does work if there's only one text field, but it isn't scalable to multiple text fields. Instead, I would make 'keyword' a class for the input element and use the selector:
$('.search input.keyword').val('');
This is very similar to the solution Sergio gave except it allows you to control, via the 'keyword' class, which input elements have their values cleared.
Use this
$("the_class_or_id").val("");
Link for this: jQuery Documentation
This is introduced in jQuery API. You can use .value in JavaScript, but in jQuery its val(). It gets the value of the object and to clear the value, just add quotes!
JavaScript code would be:
document.getElementById("id_name").value = "";

Handling default form values with jquery.validationEngine.js

I am using jquery.validationEngine.js for form validation .
I was downloaded this js from http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
this site.But it not works for checking validation for default value such as I have first name field whose value is "First Name".I want validation for checking that this field should not be blank but it not works because it contains default value "First Name".
Also I want this should work in jquery.validationEngine.js file because I have to many validations on form & I am using this js.
My field is
<input type="text" id="Uname" name="Uname" value="User Name" onfocus="if(this.value=='User Name')this.value='';" onblur="if(this.value=='')this.value='User Name';" />
If anyone using this file let me know & help to solve this problem.
If you wish to use validationEngine to validate your form the way you describe, there appear to be at least three solutions based on the documentation.
1) You can create a new custom regex in the translation file for each default text value, and then add that custom regex to the relevant form item. This is probably the trickiest of your options, as you will need to use a negative lookahead or something similar to get the regex correct.
2) Have the validator call one or more functions that you write to handle your special cases. I don't know if validationEngine allows you to pass parameters to the function--the documentation says nothing about that--so I'd guess it doesn't. This may mean that you will need to either write a separate function for each default value or else use a global variable to indicate the default value you are checking for. A function for your Uname field in your code snippet might look like this:
function checkUname(field, rules, i, options){
if (field.val() == "User Name") {
return "You must type in your username.";
}
Once that function is defined, you can use something like this to use it:
<input type="text" class="form validate[required,funcCall[checkUname]]" id="Uname" name="Uname" value="User Name" onfocus="if(this.value=='User Name')this.value='';" onblur="if(this.value=='')this.value='User Name';" />
3) You can write a single JavaScript function that goes through each field in your form and, if it finds the default value, changes it to an empty string. Then attach that function to the onsubmit event in your form. This may be the easiest option, but it depends on your function running before the validationEngine code. If that's not the case, then it won't work.
Here is a good example
How do you validate optional fields with default value?
Otherwise see the question I posted as identical question with the possible change
jQuery.validator.addMethod("defaultInvalid", function(value, element) {
if (element.value == element.defaultValue) return false;
}
instead of the switch/case
<input type="text" id="Uname" name="Uname" value="User Name" onfocus="if(this.value==this.defaultValue) this.value=''"
onblur="if(this.value=='') this.value=this.defaultValue" />
You should set the placeholder value using the HTML5 placeholder attribute instead of JavaScript.

Categories

Resources