is an element an input? - javascript

How can you check if an element is an input?
if(elm.val() == null){
// is not an input
}
else{
// is an input
}

Well you know what element you are selecting.
or (if you really do not know) you can do:
if(elm.is('input')) {} //assuming elm is a jQuery element
else {}

You can use the is function to determine if an element is an input tag:
jQuery(elm).is("input");

//jquery
if( $("#elementid").is("input") ){}
else
{}

Related

Fetch specific element using custom attribute in jQuery

Below is a sample structure from which i'm trying to get the specific value of custom attribute
<div id="123"></div>
<div id="456"></div>
<div context="james"></div>
Below is how i'm trying to fetch, but it always returns false.
if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}
The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:
var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")
You could also use .filter:
if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");
Note: If you used data-context="james" you would use the .data() method rather than .attr().
Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:
// Select by attribute
var theDiv = $("div[context='james']");
// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}
// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");
// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>

How to check if one element is exist under a form in jQuery

I have a form with id commentform and if any logged in user visit the page a p tag gets generated under the form that with class logged-in-as. Now I am trying to check if that p exists and if not exists then do my validation which uses keyup(). Here is a small snippet...
$('form#commentform').keyup(function() {
if( ! $(this).has('p').hasClass('logged-in-as') ) {
....
} else {
......
}
}
});
Now the problem is that the if( ! $(this).has('p').hasClass('logged-in-as') ) is not returning me the expected result whether or not that specific p exists.
Can any of you guys tell me any other/better way to check this?
$('form#commentform').keyup(function() {
if($(this).find('p.logged-in-as').length == 1) {
....
} else {
......
}
}
});
You can do this to find it.
You can use
if ($('.logged-in-as', this).length)) {
But I would rather use a variable to store that state instead of relying on checking the presence of a raw tag : what if you change your HTML a little ?
Side note: Don't use overqualified selectors. $('#commentform') is faster and logically more consistent than $('form#commentform').
Check if an element witth class "xxx" exist
if( $( ".xxx" ).size() > 0 ) {
// EXISTS
}
Edit: forgot the dot ( ".xxx" )

Detecting an html attribute's value with a userscript?

I am trying to make myself a personal user script, but I need to detect an html attribute's value. For example:
<div id="a">Stuff</div>
<div id="b" value="false"></div>
How could I create an if statement in the script, that triggers if the "value" attribute of element b turns to true?
element = document.getElementById("b");
if(element != null) {
if (element.value == "true") {
// do something
}
}
Check out this link... it says that you can import JQuery into your userscript.
youtube video
You can then get the value of any attrubute using jquery API for attr
Jquery Api attr
which can be done like
var bAttrValue = $("#b").attr("value");
You then coulld write a function which takes in an Id and an attribute like
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
var elemAttrValue = $("#"+elemId).attr(attribute);
return elemAttrValue;
}
You could then consume it like
var DivbValue = GetAttributeValue("b", "value")
if(DivbValue) //true
{
//do something
}
else //false
{
//do something
}
alternatively write this in JavaScript
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
element = document.getElementById(elemId);
return element[attribute];
}

jquery check values in form

I have two inputs where I am checking to make sure that they are not empty before the form submits.
My issue is that it only validates #from_date. Is the issue that .val will only check the last id in the list?
$('#submitDates').click(function () {
// Get the fields you want to validate
var name = $("#to_date, #from_date");
// Check if field is empty or not
if (name.val()=='') {
alert ('Please Select Dates')
return false;
} ;
});
});
Any specific reason you're hooking on .click and not .submit?
You can iterate through the selected elements and check for a violating element using .each
var found = false;
$("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && $(name).val()=='') {
alert ('Please Select Dates')
found = true;
} ;
});
return !found;
In your example var name = $("#to_date, #from_date"); is giving you a collection of two inputs and by doing if (name.val()=='') jQuery is checking only the first element in the collection, so it's not working. You may try this
$('#submitDates').click(function () {
var name = $("#to_date, #from_date");
if ( name[0].value == '' || name[1].value == '' ) {
alert ('Please Select Dates');
return false;
}
});
In the above example name[0].value refers to the first element and name[1].value refers to the second element. If you want to use jQuery's val() method then you can use it like $(name[0]).val() and $(name[1]).val().
Also you should consider to use submit event of the form instead of button's click event.

Check if DOM Element is a checkbox

How can I check if a given DOM element is a a checkbox.
Scenario:
I have a set of textboxes and checkboxes in which the values are assigned dynamically. I don't have a way to identify if the DOM element is a checkbox or a textbox.
Using only vanilla javascript you could do
if (el.type && el.type === 'checkbox') {
...
}
or even shorter
if ((el || {}).type === 'checkbox') {
...
}
or in modern browsers you could use matches()
if (el.matches('[type="checkbox"]') {
...
}
If you're using jQuery, you can use the :checkbox pseudo-class selector along with is method:
if($("#that-particular-input").is(":checkbox")) {
}
Checks anything
function isCheckbox (element) {
return element instanceof HTMLInputElement
&& element.getAttribute('type') == 'checkbox'
}
if( $(element)[0].type == "checkbox" ) {
}
OR
if( $(element).is(':checkbox') ) {
}
Take a look at the checkbox selector.
var checkboxes = $("form input:checkbox");
You can tell what type an input is like this:
if ($(".your-input").is(":text"))
{
// Textbox
}
else if ($(".your-input").is(":checkbox"))
{
// Checkbox
}
if (<DOMNode>.type === "checkbox") {
// ...
}
Try this;
$(element).is(':checkbox');
here element is selector to your element
if( $(element).is(':checkbox') ) {
// do something
}
jQuery is():
if ($el.is(':checkbox')) { ... }
You can use the pseudo-selector :checkbox with a call to jQuery's is function:
$('#myinput').is(':checkbox')
You should have a decent naming convention which allows you to know if an element is a checkbox from just seeing it's id or name.
e.g. "chkMyCheckbox"

Categories