Reputation: 10075
I had this code working all right, until I transitioned from "_" to camel case. Here is the code:
//Selecting the form id
formSelector = "#" + formId;
//Selecting all input/select/textarea fields with data- attributes
elementSelector = formSelector + " input[data-errArrow], " +
formSelector + " select[data-errArrow], " + formSelector
+ " textarea[data-errArrow]";
//For each selected element...
$(elementSelector).each(function(index,element) {
console.log($(this).prop("tagName"));
console.log($(this).attr("data-errArrow"));
console.log($(this).data("errArrow"));
...
}
The console output is:
INPUT
mylib.js:25 R
mylib.js:26 undefined
If data-errArrow attribute's value is correctly displayed as "R", should .data of that element not also show the same result? Why is it undefined. There is some discussion here on camel case in the JQuery docs related to the data- attribute. It says:
"In case no data is stored with the passed key, jQuery searches among the attributes of the element, converting a camel-cased string into a dashed string and then prepending data- to the result. So, the string lastValue is converted to data-last-value."
I do not see how this could be applicable above. I need to fix this. I want .data to return 'R' in the example.
Upvotes: 2
Views: 2563
Reputation: 3510
data-err-arrow="valuehere"
will return value with:
.data('errArrow')
data-errArrow="valuehere"
since there is no dash will return with:
.data('errarrow');
Because there is no dash the key gets transformed to all lowercase.
This isn't the jQuery code but just gives you an idea of what it is doing:
function CamelCase(str) {
var key;
var data = str.split("-");
for (i = 0; i < data.length; i++) {
if (i == 0) {
key = data[i].toLowerCase();
} else {
key += (data[i].charAt(0).toUpperCase() + data[i].slice(1)).toString();
}
}
return key
}
var datakey = 'err-arrow';
var datakey2 = 'errArrow';
console.log(CamelCase(datakey)); //returns errArrow
console.log(CamelCase(datakey2)); //returns errarrow
Upvotes: 7