0

I'm implementing an extend form function, in which I need to increment certain attributes including ones like data-display="#display_student_1_gender".

There is no problem in finding the attribute but it fails (marked below) when I am trying to rename it. What gives?

The Javascript:

<script>
var counter = 0;
function moreFields(val1, val2, val3) {
    counter++;
    var newField = document.getElementById(val1).cloneNode(true);
    newField.id = '';
    newField.style.display = 'block';
    var newFields = newField.querySelectorAll('[name], [id], [for], [data-display]');
        for (var i=0;i<newFields.length;i++) {
            var theNames = newFields[i].name
            if (theNames)
                newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
            var theNames2 = newFields[i].id;
            if (theNames2)
                newFields[i].id = theNames2 + counter;
            var theNames3 = newFields[i].htmlFor;
            if (theNames3)
                newFields[i].htmlFor = theNames3 + counter;
            var theNames4 = newFields[i].attr('data-display'); //line 14 Error
            if (theNames4)
                newFields[i].attr('data-display') = theNames4 + counter;    
        }           
    var insertHere = document.getElementById(val2);
    insertHere.parentNode.insertBefore(newField,insertHere);
}
</script>

1 Answer 1

1

You are dealing with dom element(newFields[i]) references which does not hae method like attr()(I think you got in from some jQuery references - but since you have not tagged the question with jQuery, I'm assuming you are not using it).

You need to use getAttribute() and setAttribute() to get/set attribute values

var theNames4 = newFields[i].getAttribute('data-display');
newFields[i].setAttribute('data-display', theNames4 + counter)

or if you are using data api

var theNames4 = newFields[i].dataset.display;
newFields[i].dataset.display = theNames4 + counter
Sign up to request clarification or add additional context in comments.

6 Comments

Need to convert to Number too btw.
@potatopeelings number?
I believe naming 4 attributes separately like this is repetitive. Would you be so kind to advise whether there is a faster way to do this? If its not too much for a short answer.
@AlvinMok since you are dealing with 4 different attributes and all of them has different values I think this is good
@ArunPJohny - wouldn't theNames4 + counter give you a string? So 0 would become 01, that would become 011...?
|

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.