Рекомендация для простого примера диалога jquery?

Поиск по ключевым словам "простой пример диалога jquery" - со всеми ответами там, я не видел простого и содержательного примера в сжатом автономном документе .html. Даже загружая несколько полных книг по jQuery, я не видел такого примера.

Примеры, которые я нашел, - это диалоговое окно с предупреждающим сообщением "Hello World".. не очень полезно для взаимодействия. Я думаю, что пример реального мира будет тем, что захватывает входные данные и отправляет их обратно на страницу, не требуя отправки на сервер. Сообщение сервера может быть следующим шагом.

Кто-нибудь может рекомендовать ссылку на код в этих строках? Благодаря

РЕДАКТИРОВАТЬ № 3

Я вставил в решение со свежим сообщением ниже. Это полностью автономный файл с готовым к включению. Это работает для меня.

РЕДАКТИРОВАТЬ № 2

Я обновил головной блок, чтобы содержать отсутствующий css. Содержимое диалогового окна теперь не отображается, но диалоговое окно не открывается.. и никаких ошибок в консоли.

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

EDIT ~ ATTEMPT # 1

Основываясь на ответе от @rob-schmuecker, я попробовал следующий код ниже. Я вижу, что это работает на jsFiddle, но моя реализация не работает. В моем браузере консоль не показывает никаких ошибок. Но есть две проблемы, которые я вижу:

  • диалоговое окно div content загружается непосредственно на страницу
  • нажатие кнопки диалога загрузки не работает.

Любая идея, что не так с этим кодом?.. Может быть, мой jquery включает вызовы?

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js" type="text/javascript"></script>

      <script type="text/javascript">

      //Initialize dialog

      $("#dialog").dialog({
          autoOpen: false,
          show: {
              effect: "blind",
              duration: 1000
          },
          hide: {
              effect: "explode",
              duration: 1000
          }
      });

      //Open it when #opener is clicked
      $("#opener").click(function () {
          $("#dialog").dialog("open");
      });

      //When the button in the form is clicked, take the input value and set that as the value of `.myTarget`
      $('.formSaver').on('click', function () {
          $('.myTarget').text($('.myInput').val());
          $("#dialog").dialog('close');
      });

      </script>

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

    </head>
    <body>

    <div>Here is the rest of the page. Hopefully we can get the value from the dialog form?! Should display <span class="myTarget">here</span> when finished.</div>

    <div id="dialog" title="Basic dialog">
        <p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
        <input class="myInput" type="text" />
        <button class="formSaver">Save me!</button>
    </div>

    <button id="opener">Open Dialog</button>

    </body>
    </html>

Ответы

Ответ 1

Я ценю ответы всех, и я видел, как они все работают в Интернете в JsFiddle и jqueryui.com. Для того, что я собирался после, насколько я могу судить, здесь самое сжатое решение, которое я смог получить, используя все удаленные приложения и основанное на решении на java2s.com:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
    <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/redmond/jquery-ui.css">

    <script type="text/javascript">
    $(function() {

        // Allows user to click Enter key in text field and it will submit the dialog
        $('#myDialog').keypress(function(e) {
            if (e.keyCode == $.ui.keyCode.ENTER) {
                getResponse();
            }
        });

        var cancel = function() {
            $("#myDialog").dialog("close");
        }

        var getResponse = function() {
            var answer;
            /*// for radio-button selection
            $("input").each(function(){
              (this.checked == true) ? answer = $(this).val() : null;
            });
             */

            answer = $("#first_name").val();

            // This adds it dynamically
            // $("<p>").text(answer).insertAfter($("#poll"));
            $("#result").text(answer);
            $("#myDialog").dialog("close");
        }

        var dialogOpts = {
            modal : true,
            closeOnEscape : true,
            buttons : {
                "Done" : getResponse,
                "Cancel" : cancel
            },
            autoOpen : false
        };
        $("#myDialog").dialog(dialogOpts);
        $("#poll").click(function() {
            $("#myDialog").dialog("open");
        });
    });
    </script>

</head>
<body>
    <button id="poll">Poll</button>
    <div id="myDialog" class="flora" title="This is the title">
      <p>Question?</p>
      <label for="yes">Yes!</label><input type="radio" id="yes" value="yes25" name="question"><br>
      <label for="no">No!</label><input type="radio" id="no" value="no" name="question">
      <br/>
      First Name: <input type="text" id="first_name" />

    </div>

    <div style='color: green;' id='result'>
    </div>

</body>
</html>

Ответ 2

OK Здесь идет

Демо: http://jsfiddle.net/robschmuecker/9z2ag/1/

HTML:

<div>Here is the rest of the page. Hopefully we can get the value from the dialog form?! Should display <span class="myTarget">here</span> when finished.</div>

<div id="dialog" title="Basic dialog">
    <p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
    <input class="myInput" type="text" />
    <button class="formSaver">Save me!</button>
</div>

<button id="opener">Open Dialog</button>

Диалог начинается с CSS:

#dialog {
    display:none;
}

Затем мы делаем Javascript:

//Initialize dialog
$("#dialog").dialog({
    autoOpen: false,
    show: {
        effect: "blind",
        duration: 1000
    },
    hide: {
        effect: "explode",
        duration: 1000
    }
});

//Open it when #opener is clicked
$("#opener").click(function () {
    $("#dialog").dialog("open");
});

//When the button in the form is clicked, take the input value and set that as the value of `.myTarget`
$('.formSaver').on('click', function () {
    $('.myTarget').text($('.myInput').val());
    $("#dialog").dialog('close');
});

Ответ 3

Причина, по которой он не работает, заключается в том, что ваши вызовы в jQuery и jQuery UI следующие:

http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

Но URL-адрес для загрузки:

https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

Поместите правильный URL-адрес, и он будет работать.

Сложение:

Проблема заключается во втором вызове jQuery:

http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js

Кроме того, что jQuery загружается из https, нет jquery.js, это jquery.min.js.