Add an attribute on focus - javascript

What is the best way to add an attribute to an <input /> on focus using js / jQuery?
Right now, off the top of my head, I would think
$(document).ready(function(){
$('input').focus(function(){
$(this).attr(attributeHere);
});
});
Is that correct? Does the attribute have to have quotes around it?
Right now, it is just going to be an attribute with no value. Value will be added later.

This is what you can do :
$(document).ready(function(){
$('input').on("focus",function() {
$(this).attr('name', 'value'); // value could be '' if you would like to specify it later.
});
});
I hope it helps.

Looks fine to me. Only one thing I would add is that even if you want to leave the attribute empty, you should give it an empty string as a value.
var attrName = 'someAttr';
$(this).attr(attrName,'');
By not passing a value (even an empty string), you are actually calling the getter function for the attribute where you really want to be calling the setter.

You need to do this -
$(this).attr('attributeName','attributeValue');
What you are trying .attr(attributeName) is used to access attribute value
Description: Get the value of an attribute for the first element in
the set of matched elements.
See the api :
http://api.jquery.com/attr/
.attr( attributeName, value )
attributeName
Type: String <-- Either a var containing string or an "string"
The name of the attribute to set.
value
Type: String or Number
A value to set for the attribute.

Related

jQuery data attr not setting

This appears very simple but I cannot see why it's not working. The selector is correct however the div .faqContent is simply not being updated with the data-height attribute.
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).data('height',h);
});
I have checked that var h is correct, it is in colsole.log as correctly holding the height.
EDIT
It's absolutely not conflict, and console shows no errors.
The data function confuses a lot of people, it's not just you. :-)
data manages jQuery's internal data object for the element, not data-* attributes. data only uses data-* attributes to set initial values, and more, it guesses at what type you want those to be based on what they look like (so something that looks like a number is converted to a number; something that looks like JSON gets converted to an object). The data method never sets data-* attributes on elements, it only sets the data on its internal data object. That means the two (the internal data object and the attribute) get out of sync:
const t = $("#target");
let value;
// Getting the attribute always gets a string
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// Using `.data`, jQuery will guess that because the attribute looks like a number,
// you want it converted to a number
value = t.data("height");
console.log(`${value} (${typeof value})`); // 1 (number)
// `data` only sets the internal data object properties, not the attribute...
t.data("height", 2);
// ...so the attribute still has `"1"`
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// ...even though the data object has 2
value = t.data("height");
console.log(`${value} (${typeof value})`); // 2 (number)
<div id="target" data-height="1"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you want to actually set a data-* attribute, use attr:
$(this).attr("data-height", h);
const t = $("#target");
let value;
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 1 (string)
// `attr` converts whatever you give it to string
t.attr("data-height", 2);
value = t.attr("data-height");
console.log(`${value} (${typeof value})`); // 2 (string)
<div id="target" data-height="1"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But if you only want this information for future use, data is fine (assuming you're okay with its automatic type conversion), just don't expect to see it in the DOM inspector, because jQuery doesn't write this information to the DOM.
You will not be able to see it in the element inspector but it is there as jquery set the data attribute internally.
try console.log($(this).data('height'));
.data() is only stores the associated new value in memory(or internally). It'll not change the attribute in the DOM hence you cannot see it updated using inspector tools.
To change the attribute, you can use .attr():
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).attr('data-height',h);
});
JQuery .data() stores the value on the element itself, it won't add an attribute.
http://api.jquery.com/data/
If you want to add an attribute, use attr:
$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).attr('data-height', h);
});
http://api.jquery.com/attr/

Javascript set attribute using variable

I'm unsure of the syntax here, but the code I have so far is this... (Note: I am passing the id's of three textboxes in the form '#begmile','#endmile','#totmile', and I want to set the value of the 'totmile' checkbox to endmile-bigmile)
function subtract(begmile, endmile, totmile){
y=$(begmile).attr('value');
z=$(endmile).attr('value');
y=z-y;
$(totmile).setAttr('value',???);
}
I'm not sure if my syntax here so far is correct, but assuming it is (that y is properly set to endmile-begmile, how do I use setAttr to set the value of totmile to the value of y?
This is the correct syntax:
var href = 'http://cnn.com';
$(selector).attr('href', href);
your last line isn't calling the right method:
$(totmile).setAttr('value',???);
should be:
$(totmile).attr('value',???);
e.g.
$(totmile).attr('value', y);//set the value to the variable "y"
you can also call .val(); instead to easily get the value of a field, or .val(newValue); to set the value.
also note that if your values for "y" and "z" are not actually representing numbers you'll get a weird result.
The value attribute refers to the default value for the textbox, not the current one. The current one is stored in the value property.
function subtract(begmile, endmile, totmile) {
document.getElementById(totmile).value =
document.getElementById(endmile).value - document.getElementById(begmile).value;
}
This also removes the need for jQuery, since the JavaScript Sledgehammer is far too excessive for this job. To make sure it works, just remove the # when you pass IDs to the function.

Does the data("key", value) method set data- attributes?

Will the jQuery $("..").data("key", value) method set the data-key attribute if one is present?
Adam Freeman's Pro jQuery states that it does:
Tip The data method takes the data attributes into account when
setting values as well. When you specify a key, such a [sic] product, the
data method checks to see whether there is a corresponding HTML5 data
attribute, such as data-product. If there is, then the value you
specified is assigned to the attribute. If not, then the data is
stored internally by jQuery.
But I thought that it didn't, and the test that I ran implies that it doesn't. (I checked the errata section—nothing)
Full code is below, but the short of it is that when I set the data-name attribute by calling the attr method, the attribute value changes and can be seen in the chrome elements tab, and retrieved into newValue. When I set it with the data method, neither of these conditions are satisfied; it seems as though using data() always sets the value internally and never on the attribute, even if one is present.
Unfortunately, the docs' only mention of html5 data-attributes is in the section of the data method that takes only a key, and returns the concomitant value; the description of data("key", value) doesn't seem to mention html5 data-attributes at all.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script type="text/javascript">
$(function () {
var oldValue = $("#d").data("name");
alert("old value " + oldValue);
$("#d").data("name", "Adam");
//$("#d").attr("data-name", "Adam");
var newValue = $("#d").attr("data-name");
alert("new value " + newValue);
});
</script>
</head>
<body>
<div id="d" data-name="none"></div>
</body>
</html>
I think that Adam Freeman's description is incorrect, or at least not completely accurate.
According to the jQuery documentation:
As of jQuery 1.4.3 HTML 5 data- attributes will be automatically
pulled in to jQuery's data object.
This implies that jQuery pulls these attributes into its own internal representation, rather than overriding the values in the actual attributes.
A quick perusal of the code suggests the same.
According to jQuery's .data() method documentation:
Note that this method currently does not provide cross-platform
support for setting data on XML documents, as Internet Explorer does
not allow data to be attached via expando properties.
It seems it uses the data= if it's there and doesn't throw an error.
Take a look for yourself:
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery's .data() function doesn't interact with the HTML5 data-* attributes at all, other than taking the initial values from them; I'm not entirely sure when this is done, though - another answer suggests it's done at the first call to .data(), which may be correct (it definitely makes sense).
Using .attr() to specify a new value for a data-* attribute doesn't modify the value that jQuery has stored to access using .data(). To illustrate, take a look at this jsFiddle. If you inspect the <div> element and then click on the button, you can see that whilst the attribute on the element has its value changed the two console.log() calls output the same value.

Changing the content of a div with javascript

I have a function ImageIndexing(type,data) that will return a string according to the two variables. Than I have classes: portoflioTitle, portfolioThumbnail, portoflioBig; and I need to change their content, src, id accordingly to their data-title, data-thumb and data-big. Its really hard to explain, so let me try.
So:
After the page loads a function is executed.
First, the function changes the innerHTML (content) of all the divs with class portfolioTitle. It changes it trough the ImageIndexing function to which it passes 'title' as the type and its data-title as the data. The ImageIndexing function will then return the string we need to change the innerHTML to. (can you understand it so far?)
It repeats the same with the other classes. With portfolioThumbnail it passes 'image' as the type and its data-thumb as the data and than sets the returned string to its src. portfolioBig passes 'big' and data-big and uses the string as its id.
Edit: You should use .attr to get the value of the element. Updated jsFiddle here
I am not sure what you really want, but from your comment I believe you want to know hwo to pass data-x and set the innerHTML of the corresponding div.
Below is just rough version, let us know if you have any questions.
$('div.portoflioTitle').each (function(index) {
$(this).html(ImageIndexing(this.title, $(this).attr('data-title')));
});
function ImageIndexing(type, data) {
//do w.e you have to do and return
return "<span>can return anything that you wanna set inside the div</span>";
}

Locating text and performing operation based on its existence

I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript.
My site is in VB.NET and I'm putting jQuery code on both my actual .ascx UserControl and in a separate file (something like myscripts.js). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page.
What I would like to do is the following:
Grab text from a textbox and make it all lowercase
Get the username from the login info. I've done this like so on my actual page:
var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>";
Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true.
How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript....
To get the value of a text field, you use the jQuery function val():
var value = $('#mytextbox').val();
To turn a string to lower case, you use the string method toLowerCase():
var value = $('#mytextbox').val().toLowerCase();
Since val() returns a string we can throw that at the end.
To check if a string is within another string, you use the string method indexOf():
var needle = 'Hello';
var haystack = 'Hello World';
var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case
Another thing to remember is that ASP.NET renames all your control ID's. To access your controls in JavaScript, you should use the following in place of the Control ID <%= txtUserName.ClientID %>.
In jQuery, here is what my selector would look like for a textbox with the ID "txtUserName".
$('#<%= txtUserName.ClientID %>')
Enjoy,
Zach
var userName = "username as it comes out of your web app";
// stuff happens
var $myTextbox = $('#ID_of_textbox');
var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0;
Short explanation:
$('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox
.val() // the jQuery function that gets the textbox value
.toLowerCase() // self explanatory
.indexOf() // returns the position of a string in a string (or -1)
See the JavaScript String object reference at w3schools.
Alternative (to check if the textbox value equals the username):
var userNameIsEqual = $myTextbox.val().toLowerCase() == userName;
The basics of JQuery are like so: Find a list of dom elements, and perform actions on them.
In your case, you should start off by finding the dom element that is your testbox. For example's sake, we'll choose $('#userName'). The selector # means "id" and together with the name "userName" it finds all elements with the id of "userName". (Ids on a page should be unique if you're following best practices.)
Once you have that list (in this case, a list of one element), you can ask it what the value is.
$('#userName').val()
This gets you the value of the value="" attribute of the input tag.
You can then assign it to a variable and use standard javascript String functions to do the rest!
function checkLogin(userName){
return $('#mytextbox').val().toLowerCase() == userName
}
if ($("#textBoxID").val()) != "") { /*Do stuff*/ }

Categories