skwidbreth
skwidbreth

Reputation: 8424

set attributes of elements stored in variables

Is there anyway to use jQuery to dynamically set the attributes of HTML elements that are stored in variables?

For example, at one point in my application, a user creates a varying number of select input fields. For eventual processing by PHP, the elements need to be named in the format name='input'+siteNumber+'['+x+']', where x is the number of elements created in a for loop.

Here's a rough sketch of what I'm thinking needs to be done - THIS IS NOT FUNCTIONAL CODE, IT IS ONLY AN ILLUSTRATION.

$(".number_select").change(function(){
    numberFound = $(this).val();
    siteNumber = $(this).parent().attr('data-site_number');
    //HERE'S THE INPUT TO BE NAMED
    selectInput = "<select></select>";

    this['inputArray' + siteNumber] = [];

    for(x = 1; x <= numberFound; x++){  
        //THIS IS WHAT I'D LIKE TO ACCOMPLISH - SETTING THE ATTRIBUTE - THOUGH THIS UNDERSTANDABLY DOES NOT WORK IN THIS PARTICULAR FORMAT           
        this['inputArray' + siteNumber].push(selectInput.attr("name", "species"+siteNumber+"["+x+"]"));
    };

    $(this).parent().append(this['inputArray' + siteNumber]);
};

Thank you.

Upvotes: 1

Views: 147

Answers (2)

skwidbreth
skwidbreth

Reputation: 8424

Thanks everyone - I actually ended up deciding to handle this a little differently, but it works perfectly - rather than storing the elements in variables, I used a function instead...

function inputs(siteNumber, x){
    return ("<select name='selectInput"+siteNumber+"["+x+"]'>"+list+"</select>");
};

$(".number_select").change(function(){
    numberFound = $(this).val();
    siteNumber = $(this).parent().attr('data-site_number');

    this['inputArray' + siteNumber] = [];

    for(x = 1; x <= numberFound; x++){
        this['inputArray' + siteNumber].push(inputs(siteNumber, x));
    };

    $(this).parent().append(this['inputArray' + siteNumber]);
};

Don't know why I didn't think of this in the first place, it seems obvious to me now. Oh well, live and learn.

Upvotes: 1

Brian Dillingham
Brian Dillingham

Reputation: 9356

To vaguely answer your question, you can dynamically generate an element and use jQuery's attr for adjusting the name attribute pretty easily like so.

var select = $('<select>').attr('name', 'add-name-here');

$('<option>').attr('value', 'some-value').text('Option').appendTo(select);

$('#wrapper').html(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   
<div id="wrapper"></div>

Which outputs

<select name="add-name-here">
    <option value="some-value">Option</option>
</select>

In your case, instead of adding it to #wrapper you would build up the select box as you need and append it to whichever select box has the change? Not sure your specific use case. Hope it helps.

Upvotes: 0

Related Questions