How to know that a particular input type is present or not in a div?
If I use
$("#inputId").val()
And there is no element present on this, then js gives an error.
So how could I know that the input element named inputId is present or not?
Reply me ASAP
You could check if
$('#inputId').length > 0
i.e. if the current selector matched any elements.
But if $('#inputId').length == 0 then $('#inputId').val() will be undefined. This is different from the scenario where the input exists, because val() would always yield a string, that is or isn't null.
Now, you would produce an error only if you're trying to do stuff with the value, that may or may not be undefined. For instance, the following would not work if #inputId does not exist in the DOM:
if($('#inputId').val().length > 0) { ... }
... since you'd be trying to access undefined.length. However, you could still do
if(!!$('#inputId').val()) {
// this code will only be executed if #inputId exists, and has a value that
// is not an empty string
}
If you're writing form validation, it might be more useful to do
if($('#inputId').val() !== '') {
// this code will be executed if #inputId has a value, or if it does not
// exist in the DOM at all
}
The former condition checks that the result of .val() resolves to true, which is not the case for an empty string or for undefined. (It is also not the case for null, NaN, false or 0, but .val() will never yield any of those results)
The latter checks that the result of .val() is not exactly an empty string, which is true for an actual value, as well as for undefined.
You can use the length property, which will tell you the number of elements in the current selector.
if ($("#inputId").length > 0)
{
// code that depends on inputId being present can go in here
}
if ($("#inputId").length) { }
No need to be verbose, checking whether length === 0 or greater than 0: length value itself is automatically casted as a boolean inside an if statement
Without jQuery:
var input = document.getElementById('inputId');
if (input) {
// the input exists
alert(input.value);
} else {
// the input doesn't exist
alert('Ooops! An input with id "inputId" doesn\'t exist.');
}
Related
I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..
In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.
The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.
It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.
It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead
if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}
length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);
I am checking to see if a form has a "file" input and if it has a vlue. The DOM goes like:
<form id="form123">
<div class="row">
<input type="file">
</div>
</form>
Console
console.log($(formId).find('input[type = "file"]').val().length)
// prints 0
if statement
if ($(formId).find('input[type = "file"]').val().length > 0) {
// run function
It always runs the function!
.has() returns a jQuery collection, not a true/false boolean. So use:
if ($(formId).has('input[type="file"]').length)
.length returns the number of elements matched by .has().
I would use .find() as it has better performance.
if ($(formId).find('input[type="file"]').length > 0) {
}
Edit:
And since .length is an integer, I would compare it with another numeric value instead of just evaluate it to boolean like in other answers.
if (3 > 0) looks more reasonable than if (3), right?
the closing form tag is actually an open one, did you mean that? try removing the spaces between the attribute name and the value class='row'. You can also try $(formId).find(...)
I am dynamically adding text to the input field from facebook signup data, and then populating these data to the form field which has a display:none property. After getting all the data the form should show as in display:block. But that is not working. the code seems to be working on console but not on the browser.
I am checking if the input field is filled then show the form or else no.
Here is the jsfiddle. http://jsfiddle.net/kqHmR/1/
if ($("#firstname").val() == $("#firstname").val(dataCollection.first_name)) {
$("#profileEdit").hide();
} else {
$("#profileEdit").show();
}
What is wrong with it? It is supposed to show me the form when there is something in the input fields but it's not showing .
Couldn't you just check if dataCollection.first_name is empty?
Here's a one-liner
$("#profileEdit").toggle(dataCollection.first_name.length);
Reference: http://api.jquery.com/toggle/
Explanation: .toggle() can accept a boolean. true = show, false = hide.
If a string's .length is zero, it evaluates to false, thus passing false into .toggle(). Vice versa.
In case you really want to check the input field's value instead, then:
$("#profileEdit").toggle( $.trim( $("#firstname").val() ).length );
Translated in English would be: Get me the value of firstname, trim it, and give me the length of that string, then pass it into .toggle()
.val() when called with an argument, sets the value and returns the jQuery object it was called on (to facilitate chaining). It does not return the value as such, unlike when called without arguments.
This means your if condition
if ($("#firstname").val() == $("#firstname").val(dataCollection.first_name)) {
will always fail as the RHS is not the newly set value but the jQuery object $("#firstname") itself.
I'm creating an html5 JS form library. The idea is to turn elements with a class of .form-item into content editable divs, using the elements' data-attributes as instructions for the type of form item, validation, etc that should be created.
The code below creates a validation object for a single form item that checks to see if the minimum length of the field value is met. The object's properties include the DOM element it applies to (el), the minimum length for the field (minLen), the error message (msgError) that should be displayed if that minimum length is not met, and a function (submit) that returns whether the object validates, displaying the error message if it does not.
However, the submit property function always returns false. I'm pretty sure I know why, but I'm not sure of the best way to correct it. I believe the problem I'm running into has to do with the notion of a closure. The submit property checks the length of the innerHTML of the form item element and compares it to the minLen property. But I think this only happens at the moment of instantiation of the validation object, when the innerHTML.length is always 0 (because the form item, and the validation object, must be created prior to the user being able to enter anything into the field). How should I modify the below code so that the submit property function runs anew any time it is called (thereby checking the current length of the innerHTML of the field, rather than the length at the moment of instantiation)?
function formValidateMinLen(item){
var minLen = item.attr('data-minLen');
this.el = item;
this.minLen = minLen;
this.msgError = item.attr('data-error_minLen');
this.submit = function(){
if(this.el.html() >= this.minLen){
return true;
}else{
this.el.after('<div class="msgError">' + this.msgError + '</div>');
return false;
}
}
}
item = new formValidateMinLen($('#registration-form .form-item:first'));
I did come up with one solution, which is to pass the innerHTML of the form item element as an argument to the submit property function, like this:
this.submit = function(html){
if(html >= this.minLen){
...
}
item = new formValidateMinLen($('#registration-form .form-item:first'));
item.submit($('#registration-form .form-item:first').html());
However, I don't like that solution because it seems redundant to have to re-specify the DOM element in the item.submit code (since the object already contains that DOM element in its el property).
So... what should I do?
I'm an idiot. I was comparing the innerHTML to the minimum length, rather than the LENGTH of the innerHTML to the minimum length. Now it works :)
I've got the following jQuery (I've got it wrapped in the document ready function and all that, so please know I'm just showing you the inside of the function.
..
var itemIsSold = $("#itemIsSold").val();
alert(itemIsSold);
if(!itemIsSold) {
...
}
where itemIsSold is a hidden input field. I get the value False upper case F when it hits the alert but never enters my next if statement. I know this has to be something stupid simple.
If the input's value contains the string "False", that will not translate into a false boolean value. You will need to actually check for itemIsSold == "False".
Since the value of the hidden input field is a string, !"False" will be evaluated to false. Note that any string other than a string with the length of 0 is treated as true. So you should rather compare the string value to another string value like "False":
if (itemIsSold == "False") {
// …
}