Accessing dynamically generated form fields.

Asked

Viewed 967 times

0

I have an equipment control system. In this system, while the user fills in the form, he has the option to add another field to register another device that will be associated with a customer. To make this feature I used a code in javascript

    <script type="text/javascript">
        $(document).ready(function () {
            var $link = $('#add_answer');
            var $model = $link.prev('.equipamento');
            $link.click(function () {
                var $clone = $model.clone(false);
                $(this).before($clone);
                $clone.wrap('<div class="wrapper"></div>')
                        .after('<a href="javascript:void(0)" class="remove"></a>')
                        .addClass('added')
                        .parent()
                        .hide()
                        .fadeIn();
            });

            $('a.remove').live('click', function () {
                $(this).parent().fadeOut('normal', function () {
                    $(this).remove();
                });
            });
        });
    </script>

How do I access form fields using Jquery.

Can you help me? Any suggestions? Am I doing it right? Is there a better way to do it?

note:I didn’t program this javascript

  • Could you translate his problem better?

  • The system is made to know why equipment passes the cables here company. It does not have a fixed number of equipment, so the user inserts the tip A (from where the cable comes out), the equipment through which it passes, and the tip B (where the cable ends). As we do not know how many equipment have in this path, I inserted a button + to insert a new equipment (the user inserts as many as you want).

  • So far so good, but then we need to consult these data. What I do not know how to do is that the system checks how many equipment it has registered and manages the fields for visualization. I don’t know how to call this clone created through code.

  • The generation of fields for visualization you can use a loop (for for example) and add the fields with the registered values. At the end of the iteration, you add the link element with the required parameters.

  • 1

    You could better exemplify your problem by adding as your table is in the database, because "inserted in the form of an array" it is not clear how the information is stored.

  • 1

    Welcome. Always try to explain the best possible in the question. For this there is the edition. It makes it easier for everyone to understand the problem and helps search engines index content and help other programmers.

  • Come on, in the code I posted, I’m generating clones. How do I access/call this clone by code? I want to know how I can refer to that clone within the code.

Show 2 more comments

4 answers

1

You can use Knockoutjs to build your layout instead of doing it 'in the hand'. In the library documentation you’ll find what you’re trying to do.

0

To save the array to the database in the form of a string, just serialize the array. You can use, for example, JSON.

Some interesting ways:

http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx

JsonConvert.SerializeObject(product);

JsonConvert.DeserializeObject<Product>(json);

However, the correct way to store would be to go through the array and add equipment to the database. When loading this equipment in a form, you would search the related equipment and assemble the html for each equipment.

Clone script would still work.

0


See if I understand your question, you want to access the clones in javascript.

If there are any possibilities I will address some.

Using each

$(".equipamento").each(function() {
     var obj = $(this); //aqui você irá ter acesso aos "clones"
     console.log(obj);
});

To know how many objects there are you can use length

$(".equipamento").length //retorna a quantidade de "clones"

Using the Filtering jquery (session traversing)

You can access each object separately with eq first last

$(".equipamento").first() //acesso ao primeiro objeto
$(".equipamento").eq(0) //retorna o mesmo objeto de cima

$(".equipamento").eq(1) //acesso ao segundo objeto

$(".equipamento").last() //acesso ao último objeto
$(".equipamento").eq($(".equipamento").length-1) //mesma coisa de cima

Now if the page already creates N objects when it is rendered. You can access the objects using the class ".added" in place of ".equipamento" in the above codes (changing the selector),

  • That’s exactly what I was looking for. Thank you Leandro

0

If your system is ASP.NET MVC with Razor or Web Forms, this package solves everything you need:

https://www.nuget.org/packages/BeginCollectionItem/

An example of usage is below (already translated into Razor). The component is capable of generating a temporary ID for new inserted elements that can be replaced in logic:

@using (Html.BeginCollectionItem("Equipamentos"))
{
    @Html.EditorFor(m => m.Nome)
    @Html.ValidationMessageFor(m => m.Nome)
    <br />
}

In the link below there are examples for Web Forms and further explanations of use, such as validation in Ajax of the data:

http://www.joe-stevens.com/2011/06/06/editing-and-binding-nested-lists-with-asp-net-mvc-2/

  • Enhanced response marked as community Wiki, for anyone who wants to perfect it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.