1

I need to open the same jQuery dialog from different input text controls (including those that have been created dynamically) This is what my page displays when it loads for the first time.enter image description here When the user presses the "Add" button a new row is added to the table enter image description here

So far so good. The problem comes when I have to open the dialog that will let users enter text into the inputs ( the dialog will display upon clicking on them) At first , I thought it would only be necessary to add a class to all the controls and then using the class selector just call the dialog. Unfortunately then I learned that with dynamic controls you have to use ".on" to attach them events. Once overcome these difficulties , I run into one more that I haven't been able to solve yet. This is that if you don't want the dialog to be automatically open upon initialization, you have to set "autoOpen" to false. I did so but the only result I got was that none on the inputs worked. I have also tried putting all the code ,regarding the dialog, into a function and then calling that function when an input is clicked I did also try declaring a variable and setting that variable to the dialog , something like this:

var dialog= $( "#dialog" )

But it didn't work either I have tried some possibles solutions , but no luck as of yet.

EDIT : Here's a fiddle so you can have a better idea of what I'm talking about:

http://jsfiddle.net/3BXJp/

Full screen result: http://jsfiddle.net/3BXJp/embedded/result/

Here is the html code for the aspx page (Default.aspx):

 <form id="form1" runat="server">
    <div>
        <fieldset>
            <legend>Expression Builder</legend>
            <table id="myTable" class="order-list">
                <thead>
                    <tr>
                        <td colspan="2">
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td style="text-align: right;">
                            IF(<input type="text" name="condition1" class="showDialog" />
                            :
                        </td>
                        <td>
                            <input type="text" name="trueValue" class="showDialog" />
                            )
                        </td>
                        <td>
                            <a class="deleteRow"></a>
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" style="text-align: left;">
                            <input type="button" id="addrow" value="+ Add" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="">
                            ELSE (
                            <input type="text" name="else" id="else" class="showDialog" />)
                        </td>
                    </tr>
                </tfoot>
            </table>
        </fieldset>
        <br />
        <input type="button" id="btnEnviar" value="Send" />
    </div>
    <div id="dialog-form" title="Add New Detail">
        <p>
            All the fields are required.</p>
        <table>
            <tr>
                <td>
                    <label for="condition" id="lblcondition">
                        Condition</label>
                </td>
                <td>
                    <input type="text" name="condition" id="condition" class="text ui-widget-content ui-corner-all" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="returnValue" id="lblreturnValue">
                        Return Value</label>
                </td>
                <td>
                    <input type="text" name="returnValue" id="returnValue" class="text ui-widget-content ui-corner-all" />
                </td>
            </tr>
        </table>
    </div>
    </form>

and here is the javascript code:

<script type="text/javascript">
    $(document).ready(function () {
        var counter = 0;
        $("button, input:submit, input:button").button();
        $('input:text').addClass("ui-widget ui-state-default ui-corner-all");
        var NewDialog = $("#dialog-form");
        NewDialog.dialog({ autoOpen: false });
        var Ventana = $("#dialog-form");
        $("#addrow").on("click", function () {

            var counter = $('#myTable tr').length - 2;

            $("#ibtnDel").on("click", function () {
                counter = -1
            });

            var newRow = $("<tr>");
            var cols = "";

            cols += '<td>ELSE IF(<input type="text" name="condition' + counter + '" class="showDialog1" /> </td>';
            cols += '<td>: <input type="text" name="TrueValue' + counter + '" class="showDialog1" />)</td>';

            cols += '<td><input type="button" id="ibtnDel"  value="-Remove"></td>';
            newRow.append(cols);
            var txtCondi = newRow.find('input[name^="condition"]');
            var txtVarlorV = newRow.find('input[name^="TrueValue"]');
            newRow.find('input[class ="showDialog1"]').on("click", function () {

                //Seleccionar la fila
                $(this).closest("tr").siblings().removeClass("selectedRow");
                $(this).parents("tr").toggleClass("selectedRow", this.clicked);

                Ventana.dialog({
                    autoOpen: true,
                    modal: true,
                    height: 400,
                    width: 400,
                    title: "Builder",
                    buttons: {
                        "Add": function () {
                            txtCondi.val($("#condition").val());
                            txtVarlorV.val($("#returnValue").val());
                            $("#condition").val("");
                            $("#returnValue").val("");
                            $(this).dialog("destroy");
                        },
                        Cancel: function () {
                            //dialogFormValidator.resetForm();
                            $(this).dialog("destroy")
                        }

                    },

                    close: function () {
                        $("#condition").val("");
                        $("#returnValue").val("");
                        $(this).dialog("destroy")
                    }
                });
                return false;

            });

            $("table.order-list").append(newRow);
            counter++;
            $("button, input:submit, input:button").button();
            $('input:text').addClass("ui-widget ui-state-default ui-corner-all");


        });


        $("table.order-list").on("click", "#ibtnDel", function (event) {
            $(this).closest("tr").remove();
        });
        $("#btnEnviar").click(function () {

            //Armo el objeto que servira de parametro, para ello utilizo una libreria JSON
            //Este parametro mapeara con el definido en el WebService
            var params = new Object();
            params.Expresiones = armaObjeto();
            $.ajax({
                type: "POST",
                url: "Default.aspx/Mostrar",
                data: JSON.stringify(params),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus) {
                    if (textStatus == "success") {
                        loadMenuVar(data);
                    }
                },
                error: function (request, status, error) {
                    alert(jQuery.parseJSON(request.responseText).Message);
                }

            });

        });

        $(".showDialog").click(function () {

            Ventana.dialog({
                autoOpen: true,
                modal: true,
                height: 400,
                width: 400,
                title: "Constructor",
                buttons: [
                    { text: "Submit", click: function () { doSomething() } },
                    { text: "Cancel", click: function () { $(this).dialog("destroy") } }
                          ],

                close: function () {
                    $(this).dialog("option", "autoOpen", false);
                    $(this).dialog("destroy")

                }
            });
            return false;
        });            

    });

This is the closest I've been able to get to the solution, but still can't get the dialog to remain hidden until a input is clicked

enter image description here

Any advise or guidance would be greatly appreciated. P.S. Sorry for my bad english

5
  • Do you mean that the dialog appears (as a dialog box) when you first open the page? Or that you can see the dialog hanging around at the bottom of the HTML page? In the second case just style the HTML as display:none to hide it on the page and let the dialog show it. Also you should probably go back to having a single function deal with the dialog, there seems to be a lot of duplication your example. Commented Sep 13, 2013 at 8:12
  • It's the second case, the dialog appear at the bottom of the page whenever I close the dialog, because I had to set autoOpen to true so that the dialog can appear when an input is clicked. If don't include autoOpen: true the dialog will never be displayed since it is first loaded with an autoOpen: false Commented Sep 13, 2013 at 11:49
  • @SpaceDog I have created a jsfiddle. Do you think you could check it out?? jsfiddle.net/3BXJp Commented Sep 13, 2013 at 12:07
  • my solution below works on the fiddle, I just put the style into the style box. See here: jsfiddle.net/SpaceDog/rS5pF. But read my comments below as well please ;). Commented Sep 13, 2013 at 12:09
  • @SpaceDog I've just seen your jsfiddle and the problem with bunch of divs being created seems to have disappeared:). I'll have a better look at it. Thank you SO MUCH!!!! (y) Commented Sep 13, 2013 at 12:23

1 Answer 1

3

I suspect it's because you're using destroy() rather than close() on the dialog. At the moment it looks like you're creating and destroying the dialog each time, don't do that. You should create the dialog once, isolate the dialog functionality to a separate function, and then just use open() and close() on it (you'll have to do some extra work to get the values into the right fields).

You can make your current code work if you style the dialog as hidden it'll stop happening, add this to your HTML (in the <HEAD>):

<style>
#dialog-form {
    display: none;
}
</style>

you should probably have a separate style-sheet file you include that has that style in it. Similarly you should put all your JS in a separate file if it isn't already.

But I'd definitely look at re-writing the whole thing to follow the guidelines above, it does look like it can be made a lot simpler which makes it easier to support in the future.

EDIT

This is a simplified version that shows how I would do it.

Script:

var counter = 1; // Counter for number of rows
var currentRow = null; // Current row selected when dialog is active

// Create the dialog
$("#dialog-form").dialog({
    autoOpen: false,
    dialogClass: "no-close", // Hide the 'x' to force the user to use the buttons
    height: 400,
    width: 400,
    title: "Builder",
    buttons: {
        "OK": function(e) {
            var currentElem = $("#"+currentRow); // Get the current element
            currentElem.val($("#d_input").val()); // Copy dialog value to currentRow
            $("#d_input").val(""); // Clear old value
            $("#dialog-form").dialog('close');
        },
        "Cancel": function(e) {
            $("#d_input").val(""); // Clear old value
            $("#dialog-form").dialog('close');
        }
    }
});

// This function adds the dialog functionality to an element
function addDialog(elemId) {
    elem = $("#"+elemId);
    elem.on('click', function() {
        currentRow = $(this).attr('id');
        $("#dialog-form").dialog('open');
    });

}

// Add functionality to the 'add' button
$("#addRow").on('click', function () {
    counter = counter + 1;
    var newId = "in"+counter;
    var newRow = "<tr><td><input id='"+newId+"' class='showDialog'></td></tr>";
    $('TBODY').append(newRow);
    // add the dialog to the new element
    addDialog(newId);
});

// add the dialog to the first row
addDialog("in1");

HTML:

<div>
    <fieldset>
        <legend>Expression Builder</legend>
        <table id="myTable" class="order-list">
            <tbody><tr>
                <td><input id='in1' class='showDialog'></td>
               </tr>
            </tbody>
         </table>
            <input type='button' id='addRow' value='add'></input>                
    </fieldset>
    <br />
    <input type="button" id="btnEnviar" value="Send" />
</div>
<div id="dialog-form" title="Add New Detail">
  <input type="text" id="d_input" />
</div>

Fiddle

This isolates the different functionality into different functions. You can easily expand it to do what you want. If you want the remove functionality I'd consider having a remove button for every row with a given class with a trigger function that removes that row (and the button). Then have a separate count of active rows. At the start use disable() to disable the single button, when you add a row enable() all the buttons of that class. When you remove a row then disable the buttons is existingRows <= 1.

Sign up to request clarification or add additional context in comments.

6 Comments

It's because you're destorying the dialog -- which removes all trace and returns the HTML to the state is was beforehand (it's hidden first because jquery-ui does that when you did that). Basically destorying the dialog removes the autoOpen and everything else. Use close() instead.
I used destroy because close only hides the div , it doesn't remove it and as a result I end up with a bunch of divs in my source code(have you check it out) . Isn't that a problem???
I think that's because you're creating a new dialog each time. Use open() and close() instead.
You caught me when I was bored, I've added an example of how I would do it -- hopefully that gives you an idea how to adapt your version.
Thank you @SpaceDog!!!! I used your example and it worked just as I wanted it to. As for the remove functionality, I don't think I quite understand your idea. I do use a class to identify all the delete buttons and also when one of those buttons is clicked that whole row is deleted.But why should I have a separate count of active rows? Or enable and disable buttons?? Do you think you could possibly explain a little more about that??? I'm really curious :)
|

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.