0

I'm just wondering, is it possible at all to assign an attribute name via .attr() using a pre-determined variable? The example below will show what i mean..

HTML

<select id="dobPicker" data-test="1" data-another-test="2">
    <option></option>
</select>

<div class="select">
    <ul>
        <li>
    </ul>
</div>

jQuery

$(document).ready(function() {
    var attrs = $("select")[0].attributes;

    for (var i = 0; i < attrs.length; i++) {
        var attrName = attrs[i].nodeName,
            attrVal = attrs[i].nodeValue;

        if (attrVal.length == 0) {
            attrVal = "NULL";
        }

        $(".select").attr({
            attrName: attrVal
        });
    }
});

Please bear in mind, this is a very short example. I have much more complex methods to creating the custom select, by pre-wrapping the original select within a <div class='select'> tag, but anyway that isn't relevant. As you can see the attribute names and variables are returned, the issue is, (obviously they would) attrName shows as attrName and not the variable equivalent, whereas attrVal works. Is there any possible way to output a variable for the attribute name?

0

1 Answer 1

3

don't use object use simply name value pair .attr('somename','somevalue');

 $(".select").attr(attrName, attrVal);

fiddle here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.