one
one
and each div t" /> one
one
and each div t" /> one
one
and each div t"/>

Create div Using Array

112 Views Asked by At

I have an array of strings, I want to show each array element in its own <div> tag like <div "class">one</div><div class"two">one</div> and each div tag should have a class that is common for all. All process start on click button

BUTTON CODE

<asp:Button OnClientClick="abc();" runat="server" />

JAVASCRIPT FUNCTION

function abc()
    {
        debugger;
        var arrayVariable = "one,two,three";
        var arrayLength = arrayVariable.length;
        var temp;
        for (i = 0; i < arrayLength; i++) {
            temp = document.createElement('div');
            temp.className = 'results';
            temp.innerHTML = arrayVariable[i];
            $('#inputcomshow').append(temp);
            //document.getElementById("#inputcomshow").value = replaced
        }

        }
3

There are 3 best solutions below

1
Naveen On BEST ANSWER

Use This

<asp:Button OnClientClick=" javascript:return abc();" runat="server" />



    <script>
    function abc() {
        debugger;
        var stringVariable = "one,two,three"; // string
        var arrayVariable = stringVariable.split(","); // now string to array
        var arrayLength = arrayVariable.length;
        var temp;
        for (i = 0; i < arrayLength; i++) {
            temp = document.createElement('div');
            temp.className = 'results';
            temp.innerHTML = arrayVariable[i];
            $('#inputcomshow').append(temp);
            //document.getElementById("#inputcomshow").value = replaced
        }
        return false;
    } 
</script>
4
Gautam Rai On

You need to convert string into array first.
Use this:

   function abc()
    {
        debugger;
        var stringVariable = "one,two,three"; // string
        var arrayVariable = stringVariable.split(","); // now string to array
        var arrayLength = arrayVariable.length;
        var temp;
        for (i = 0; i < arrayLength; i++) {
            temp = document.createElement('div');
            temp.className = 'results';
            temp.innerHTML = arrayVariable[i];
            $('#inputcomshow').append(temp);
            //document.getElementById("#inputcomshow").value = replaced
        }
     return false;
    }
0
Hanif On

Try it with less number variable and pure javascript, because you only used single line jQuery code $('#inputcomshow').append(temp);.

function abc(){
    var arrayVariable = "one,two,three";
    arrayVariable = arrayVariable.split(',');
    for (i = 0; i < arrayVariable.length; i++) {
        temp = document.createElement('div');
        temp.className = 'results';
        temp.innerHTML = arrayVariable[i];
        document.getElementById("inputcomshow").appendChild(temp);
    }
}