I often use classes as a means to identify a related set of elements, for example:
<input value="10" class="sum-this" />
<input value="20" class="sum-this" />
<input value="30" class="sum-this" />
The sum-this class has no CSS, and isn't defined in any CSS files -it's simply used in some jQuery - for example:
var total = 0;
$(".sum-this").each(function(i, el){
total += parseInt($(el).val());
});
console.log(total); // 60?
Is there a correct way to do this? Should I use another attribute? rel or data-*?
As #Pointy and #JustinPowell have stated in the comments, this is completely valid. In fact, it's also explicitely stated in the W3C HTML4 specification that using class attributes for purposes other than selecting style is completely valid. I quote:
The class attribute, on the other hand, assigns one or more class names to an element; the element may be said to belong to these classes. A class name may be shared by several element instances. The class attribute has several roles in HTML:
As a style sheet selector (when an author wishes to assign style information to a set of elements).
For general purpose processing by user agents.
However, HTML5 also added the custom data-* attributes (where * is a custom string) for this purpose.
LINKS
A blog post discussing your question
W3C HTML4 attributes
W3C HTML 5 data attribute
As said in the comments, it's perfectly fine to use classes in the JavaScript only. But here's a suggestion: when my colleagues want to use a class for this purpose only, they prefix it by 'js-' in order to distinguish classes used for styling from classes made for JS.
While your code is syntactically valid using classes and there's nothing wrong with it, since you're looking for something that's semantically correct I'd recommend data attributes. Classes are really meant to be used for styling while data attribtes were created "with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. "
You could write your HTML like:
<input value="10" data-item="sum-this" />
<input value="20" data-item="sum-this" />
<input value="30" data-item="sum-this" />
And your jQuery like:
var total = 0;
$('input[data-item="sum-this"]').each(function(i, el){
total += parseInt($(el).val());
});
console.log(total);
jQuery selector optimization is less important than it used to be, as more browsers implement getElementsByClassName, querySelector and querySelectorAll which parses CSS syntax.
So the burden of selection shifts from jQuery to the browser and now jQuery supports most CSS3 selectors, as well as some non-standard selectors and you can choose the selector you want to work with.
However, there are still some tips to keep in mind:
Use an ID if Possible
Avoid Selecting by Class Only
Avoid overly complex selectors
Increase Specificity from Left to Right
Avoid Selector Repetition
As everyone else has said, it's entirely appropriate to class elements for the purposes of javascript only.
In the example that you give, the alternative to collecting these elements:
<input value="10" class="sum-this" />
<input value="20" class="sum-this" />
<input value="30" class="sum-this" />
with:
document.querySelectorAll('.sum-this'); (or $('.sum-this') in jQuery)
might be to collect these elements:
<input value="10" />
<input value="20" />
<input value="30" />
with:
document.querySelectorAll('input[value]');
Related
Django formsets have an empty_form attribute.
empty_form
BaseFormSet provides an additional attribute empty_form
which returns a form instance with a prefix of __prefix__ for easier
use in dynamic forms with JavaScript.
The Django documentation doesn't actually say how to replace the __prefix__ with Javascript. Several online examples show how to do it with jQuery, but I specifically want to do it with Javascript - no jQuery.
Here is the resulting HTML from my {{ formset.empty_form }}:
<div id="prerequisiteEmptyForm">
<input type="text" name="prerequisites-__prefix__-text" maxlength="100" id="id-prerequisites-__prefix__-text">
<label for="id-prerequisites-__prefix__-DELETE">Delete:</label>
<input type="checkbox" name="prerequisites-__prefix__-DELETE" id="id-prerequisites-__prefix__-DELETE">
<input type="hidden" name="prerequisites-__prefix__-id" id="id-prerequisites-__prefix__-id">
<input type="hidden" name="prerequisites-__prefix__-content" value="21" id="id-prerequisites-__prefix__-content">
</div>
Everywhere it shows __prefix__, I want to replace it with a number... let's say 321.
Correct solution:
<div id="prerequisiteEmptyForm">
<input type="text" name="prerequisites-321-text" maxlength="100" id="id-prerequisites-321-text">
<label for="id-prerequisites-321-DELETE">Delete:</label>
<input type="checkbox" name="prerequisites-321-DELETE" id="id-prerequisites-321-DELETE">
<input type="hidden" name="prerequisites-321-id" id="id-prerequisites-321-id">
<input type="hidden" name="prerequisites-321-content" value="21" id="id-prerequisites-321-content">
</div>
So my question becomes
Using Javascript only, how do I replace a constant value ("__prefix__") with something else ("321") across several elements (inputs and labels) within multiple attributes (name, id)? Specifically, I want to do it cleanly for repeatability. I don't want a highly custom solution to this specific problem. It needs to be a general approach... since this is replacing a constant, surely Javascript has a clean way to do this? I'm still learning Javascript and trying to not be so dependent on jQuery.
I used this concept:
const emptyForm = document.querySelector('#prerequisiteEmptyForm');
clone = emptyForm.cloneNode(deep=true);
clone.innerHTML = clone.innerHTML.replace(/__prefix__/g, '321');
I need a way to change the value of an input box by referring to it by form and class name. Given a form that looks like this:
<form name="foo">
<input type="text" class="bar" value="someval" />
</form>
Is there a one-line solution to this? I've tried some things such as:
document.foo.getElementsByClassName('bar')[0].setAttribute("value", "newvalue");
And
document.forms['foo'].getElementsByClassName('bar')[0].setAttribute("value", "newvalue");
To no avail. There must be something obvious I'm missing, but what?
This is precisely what .querySelector() was designed to help with. You can pass any valid CSS selector to it and it will return the first element that matches the query or undefined if no match is found.
And, don't use .getElementsByClassName() or document.forms (ever) as they are both ancient techniques that either introduce major performance issues or non-modern approaches that are inferior to the APIs we have today.
// Find the input element with a class of "bar" that is a direct child of a form with a name attribute of "foo"
document.querySelector("form[name='foo'] > input.bar").value = "blah"
<form name="foo">
<input type="text" class="bar" value="someval" />
</form>
Try this:
<form>
<input type="text" class="bar" value="someval" />
</form>
<script>
document.getElementsByClassName("bar")[0].value = "newvalue";
</script>
You can use something like this
document.forms[0].querySelector(".bar").value
And if you have multiple forms, just loop through document.forms and get values by class name, use querySelector or select by id whatever suits you.
Hope this helps.
I wonder if it's possible (by jQuery or other method) to have the <label for> attribute bound to the input by the name attribute instead of the id attribute?
The regular way:
<input type="checkbox" id="element_id" name="element_name">
<label for="element_id">Checkbox</label>
What I need to do:
<input type="checkbox" id="element_id" name="element_name">
<label for="element_name">Checkbox</label>
The suggestion from JJJ above works semantically, but when it comes to applying CSS I found it better (and less hacky) to drop the use of <label> entirely, and instead do the styling via custom tags, eg. <customlabel>Label text</customlabel>.
The <customlabel> can be targeted from css by eg. [type="radio"]:checked + customlabel:before {}.
I'm writing a 100% JavaScript webapp that manages a catalog of products.
I'm using Backbone & Mustache, among other things.
Each product has a name, which needs to be translated. So for each product, I add as many <input> elements as there are languages to translate, something like this :
<input type="text" name="name_fr" value="Bonjour" class="i18n lang_fr">
<input type="text" name="name_en" value="Hello" class="i18n lang_en">
<input type="text" name="name_es" value="Hola" class="i18n lang_es">
I show/hide <input> elements depending on the currently selected language relying on CSS classes, on the first rendering and also when the user changes the language :
var $html = ...; // Render Mustache template
var cssClass = 'lang_' + currentLanguageId;
$html.find('.i18n.' + cssClass).show();
$html.find('.i18n:not(.' + cssClass + ')').hide();
This method is a maybe a little bit naïve, but it is simple, because each input field contains all the necessary information in its attributes to save the data. I'm listening the blur event to save data when the user leaves the field.
The problem is that the language switch is slow when the number of elements grows.
Am I using the good technique ? I don't think re-rendering the product items when the language changes would be a good solution.
Can't you use css instead of javascript to toggle the show/hide?
E.g.:
.lang_fr,.lang_en,.lang_es {display:none}
.fr .lang_fr {display:inline}
.en .lang_en {display:inline}
.es .lang_es {display:inline}
...
<div class="fr">
<input type="text" name="name_fr" value="Bonjour" class="i18n lang_fr">
<input type="text" name="name_en" value="Hello" class="i18n lang_en">
<input type="text" name="name_es" value="Hola" class="i18n lang_es">
</div>
Then just toggle the fr class of the outer div.
I currently have some third party client-side "magic widgets" library that I have to deal with... :) All I have to do really is to add some small amount of behavior to those things with jQuery to accommodate for some simple business rules. A lot of times, I find myself selecting a bunch of elements in the same way. Since "magic widgets" are already super heavy on JS, and I even notice it on my fast machine, I was trying to keep my own JS to an absolute minimum. So, given that the user clicks on one of the following inputs, what is the most efficient way to select all the inputs, including the clicked one, in the following structure with jQuery?
<div>
<label><input ... /></label>
<label><input ... /></label>
<label><input ... /></label>
</div>
First of all, your inputs shouldn't be wrapped in labels, but that's a different argument.
The fastest way is probably:
$('input').click(function(){
var siblings = $(this).closest('div').find('input');
});
This will select your clicked input again too, though. If that's a problem, try:
$('input').click(function(){
var siblings = $(this).closest('div').find('input').not($(this));
});
If you were using correct markup so that the label tags preceded each input element, then your HTML would look like
<div>
<label for="input1" /><input id="input1" ... />
<label for="input2" /><input ... />
<label for="input3" /><input ... />
</div>
Then your jQuery code becomes way easier:
$('input').click(function(){
var siblings = $(this).siblings('input');
});
Well, assuming none of the elements in that markup have unique id's or class names, the most efficient selector you can use is a combination of tag names and the >, or first-child selector:
$("div > label > input");
$("div>label>input") I presume. Although you could give each input a common class and do $("input.class").
it depends. if the markup only consists of your fragment than:
$('input');
All modern broswers have a cache to tags.
If your looking for the inputs in within the div add an id to the div:
<div id="input_fields">
<label><input ... /></label>
<label><input ... /></label>
<label><input ... /></label>
</div>
and use this selector:
$('#iput_fields > label > input');
The id is important since it is the fastest possible query a browser can perform.
Seems like using class name better than using tag names without any parent. Here is the test for it for test your self.
Maybe more complex html structure give different results.