简体   繁体   中英

How to get values from dynamically added (using javascript) elements?

On my aspx page I dynamically create html controls on client side using javascript. For example, after page load you can click button in a browser, by clicking button html input and select elements appear. You may click once again, and this elements ( input and select ) will added again. So, you can create so many inputs and selects as you want (all this using javascript, no postbacks)

After user created some inputs and selects and entered some information in it, he posted form. I want on server side to find all this dynamically added elements and perform some actions depends on values in this controls.

How can I find dynamically added elements, and what is the best and elegant way to achieve this?

Thanks in advance.

Create a loop that loops through each input and select object, that grabs the name/id of the current object and its corresponding value. Then add those items to an array and once the loop is completed, pass those values to your aspx file.

You can view an example with this approach at: http://jsfiddle.net/euHeX/ . It currently just alerts the values, but you could easily modify it to pass the values as a parameter via ajax to your handler aspx file. The code will add new inputs or select boxes based off of the input provided. This would of course be modified to reflect your current setup.

HTML:

<div id="dynamic"></div>
<input type="button" id="submit-form" value="Submit>>">

JavaScript (using jQuery):

function createInput(type){
    for(var i=0; i<5; i++){
        if(type==0){
            var obj = '<input type="text" id="'+i+'" class="dynamicContent">';
        }else if(type==1){
            var obj = '<select id="'+i+'" class="dynamicContent"><option>--Select--</option></select>';
        }
        $("#dynamic").append(obj);
    }
}

function getContent(){
    var inputArray = [];
    $(".dynamicContent").each(function(k,v){
        var o = $(this);
        var oType;
        if(o.is("input")){ oType = "input"; }
        if(o.is("select")){ oType = "select"; }        
        var oID = oType+o.attr("id");
        var oValue = o.val();
        inputArray.push(oID+'='+oValue);
    });
    alert(inputArray);
}

$("#submit-form").click(function(){
    getContent();    
});

// Set type to 0 for input or 1 for select
var type = '1';
createInput(type);

In the Javascript that creates the new elements, increment a counter each time an element is created. Add the value of the counter to the name of the input element so each element has a unique name.

Add the final value of the counter to a hidden form field when the form is posted.

In your server side code, create a loop that starts at zero and continues until you have reached the value of the counter. Within the loop, fetch the posted value of the corresponding form field.

When you add the elements, assign unique IDs to them, and then retrieve their values using Request.Form["UniqueIdHere"] (C#) or Request.Form("UniqueIdHere") (VB.NET).

If you're using jQuery you can use .live() to achive this like a peace of cake! http://api.jquery.com/live/

I don't know if your controls will survive the postback the way you're creating them, but a good technique for accessing dynamically generated controls (assuming that you've figured out how to persist them) is to do something like the following:

Add a panel to your page. Add your dynamically created controls to this panel.

In the OnClick event handler (or other method), do something like the following:

foreach (DropDownList ddl in Panel1.Controls.OfType<DropDownList>())
{
    //put code here
}

foreach (TextBox txt in Panel1.Controls.OfType<TextBox>())
{
   //put code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM