Get custom field value on span element using javascript - javascript

If I have something like this:
<span stylecode="123456789" class="punctis-social-widget"></span>
How can i get the stylecode value using javascript (not jquery). Also, is valid to use custom fields on spans?
Note: The field stylecode sometimes is not present, so the result of the function could be null.

It's not valid to use custom attributes. If you need to store any values consider using the HTML5 data attribute.
<span id="item1" data-stylecode="123456789" class="punctis-social-widget"></span>
Then use JS to fetch that:
<script>
var element = document.getElementById('item1'); // You could use class
var sDataValue = element.getAttribute('data-stylecode'); //123456789
</script>
For jQuery fetch value with:
$('item1').data('stylecode'); //123456789

Provided you can select the span element, you can simply do this:
spanElem.getAttribute('stylecode');
If the attribute doesn't exists, getAttribute() will simply either return null or a '' (seems to vary between browsers).
Selecting it would be easier if it had an id, in which case you could use document.getElementById('id'); Otherwise you can use document.getElementsByClassName('punctis-social-widget') in newer standards-compliant browsers, or use document.getElementsByTagName('span'); and loop over them and inspect their className properties.
As mentioned by Matthew, custom attributes are not valid (but usually don't cause any problems afaik), but provided you use HTML 5, turning it into a data-attribute will make it valid.

Though it is not good practice to use custom attributes like this, you can accomplish this task as such:
var apan = document.getElementsByTagName('span');
var code = span[0].getAttribute('stylecode');
console.log(code);
Use the data attributes.

I know how to catch the value of attribute :
var span = document.getElementsByTagName("span");
var stylecode = span.getAttribute("stylecode");
But I don't know about the second part of your question. Sorry.

Related

jQuery single line code optmization for getting and setting for the same input element

I'm using PHPStorm and have the following js code
$('#id'.val($('#id'.attr('default'));
The idea is to reset the value of a input field to it's default which is set in default attribute of the input element.
Now the IDE is suggesting me to avoid duplicate selectors.
Though it is working I'm interested in finding out what is the best way to optimize this code line?
Not exactly what you asked for but more future proof using data and not an attribute. You could even store complex data or other information in there as well like "originalvalue" or "lastchangedvalue" etc.
Storing in an attribute is fine however I prefer to store things like this in the data of the element like:
<myelementtag id="myid" data-defaultvalue="defaultvalue" />
You then access it like:
$('#myid').data("defaultvalue");
For example:
var myElement = $('#myid');
myElement.value = myElement.data('defaultvalue');
Want to reset the default?
var mynewdefault = "mynewvalue";
myElement.data('defaultvalue', mynewdefault);
Since you asked only one selector and one line code, please use like this as stated in jQuery documentation (middle section):
$("#id").val(function(index,value) {
return $(this).attr('default');
});
or if you want to avoid $(this):
$("#id").val(function (index, value) {
return this.getAttribute('default');
});
JSFiddle
And yes, as other members have pointed out, it would be better if you use data attribute (data-defaultValue) instead.
This is a more compact solution:
var id = $('#id');
id.val(id.attr('default'));
You really don't need to use $(...) every time.
Store your jQuery element in a variable:
var $id = $('#id');
$id.val($id.attr('default'));

How to get non-DOM properties of HTML in Javascript

Say a HTML snippet like this:
<div a_example = "x" b_example = "y" class = "z"></div>
What is the proper way to get the corresponding properties of a_example and b_example in Javascript?
Can xpath do the job?
Use getAttribute:
var elem = document.getElementsByClassName("z")[0],
a = elem.getAttribute("a_example");
Here's a working example.
But, as has already been mentioned, you should really be using HTML5 data-* attributes, otherwise your markup is invalid.
Some browsers will add all attributes as named properties of the DOM element, others will only add standard attributes. In both cases you can get non–standard attributes using getAttribute, however such a scheme is not recommended.
It is common to use standard attributes and DOM properties and only use getAttribute where necessary as it is inconsistently implemented in different browsers.
You should take a look at HTML5 data attributes, here is a useful article: http://html5doctor.com/html5-custom-data-attributes/
Reading data attributes from a tag is really easy, and a fallback is available for older browsers. An example from the article:
<div id="sunflower" data-leaves="47" data-plant-height="2.4m"></div>
<script>
// 'Getting' data-attributes using dataset
var plant = document.getElementById('sunflower');
var leaves = plant.dataset.leaves; // leaves = 47;
</script>
If you are using jQuery, it is as simple as saying:
HTML
<div id="testDiv" a_example = "x" b_example = "y" class = "z"></div>
Javascript:
var attr1 = $('#testDiv').attr('a_example');
element.getAttribute(attributename)
This should work for you.
I agree you should look at data attributes and better ways to do add non-standard attributes, but here's a 'raw' answer to your question, but I wouldn't treat this as universally supported (or advisable):
alert(document.getElementsByTagName('div')[0].getAttribute('b_example'));

How do I set the value of an input-element via jQuery, when I only know it's "name"-attribute

I need to reset some text-boxes which only have an unique name (not an unique id).
I tried it with jQuery, but my code seems to do nothing:
$('input[name=customergroupname]').value="";
Try this:
$('input[name="customergroupname"]').val("");
Getting and setting value of form elements wrapped in a jQuery object is being done with use jQuery val function:
$('input[name="customergroupname"]').val("");
.value can only be used for DOM elements, like this:
$('input[name="customergroupname"]').eq(0).value ="";
$(...) // This is a jQuery object.
$(...)[n] // This is a DOM object in the nth place in the set.
$(...).eq(n) // This is a DOM object in the nth place in the set.
Working demo http://jsfiddle.net/vN74v/2/
Code
$('#hullk').click(function(){ // in example when you click the button
$('input[name="customergroupname"]').val("");
});
​
According to DOM level 2 specifications, you can access:
document.forms["foo"].elements["customergroupname"].value = '';
If formName and fieldName are constants rather than variables you can use literal syntax:
document.forms.foo.elements.customergroupname.value = '';
try:
$('input[name="customergroupname"]').value="";
I've wrapped customergroupname in quotes.
Very true, I mixed the quotes up. Edited now.

set a new id for a class in javascript

I have a class as
<div class="group-left article_left">
I need to add a id for this class dynamically using JavaScript.
i have added the following code
var thediv = document.getElementByClass("#group-left");
thediv.id = "pad_id";
But the id is not appearing in my code.Can anyone help me.
The method is called getElementsByClassName and returns a NodeList, not a single node (so you need to treat it as an array and either loop over it or just grab the first element from it).
You also need to spell your class name correctly. You don't have a # character in it.
var thediv = document.getElementsByClassName("group-left")[0];
thediv.id = "pad_id";
It isn't supported by Internet Explorer 8 or lower so you may wish to use a polyfill or a library (such as YUI or anything else implementing a selector engine) with equivalent functionality instead.
There is now getElementsByClass method in javascript unless you use some library. You can use jquery
$('.class').attr('id','pad_id');
You should only use one id per element though. Remember that
You have to use setAttribute, like such:
thediv.setAttribute("id", "pad_id");

Can a variable be passed as an element id in javascript

I'm trying to get some AJAX running with Django using jQuery. The problem is that the ID of the element I'm trying to change isn't set in stone, it's a Django template variable so it is different for each element in the table, but I want to use AJAX to change that element. I'm passing the dictionary from a Django view to JavaScript via simplejson, the pertinent objects being ID and model (not real variable names, just wanted to make it obvious what I am trying to do). Some pseudo code (third line, wrote it like python because I don't know how to do this in JavaScript):
var quantity_update = function(msg, elem) {
var response_obj = eval('(' + msg + ')');
var newtotal = document.getElementById("%s, %s"); % (response_obj.id, response_obj.model)
subtotal.innerHTML = "<td>"+response_obj.subtotal+"</td>";
Is something like this possible, and if so how?
Javascript doesn't have fancy string formatting (%s), but you can use plain string concatenation, just like you can in Python:
var id = response_obj.id + ', ' + resonse_obj.model
You don't need to worry about the string being generated dinamically. It is still a string after all and getElementById accepts it the same way .
You probably shouldn't be doing the eval() yourself to parse the JSON. I'm pretty sure you can have JQuery do that for you when you do the AJAX request.
If your element ID is not set in stone, you might want to identify the element using other means. Many JS framework such as jQuery supports identification via CSS Selector. For example you can identify the element you want to change by combination of its tag and class.
For documentation on the available selector you should read jQuery Selector Documentation
You can totally pass jquery css selectors as variables. Simple example:
var elementId = $('td').eq(0).attr('id'),
myElement = $('#'+elementId);
In this example, we grab the ID of the first TD in your document, find its id, and use that to get "myElement"
You may find it helpful to review the "selectors" section of the jQuery documentation (api.jquery.com) to review all your options for finding an element. In my example I also am using the jquery.eq() method, which filters a list of selectors (in this case all the TDs) to a specific one.

Categories

Resources