ThisBetterWork
ThisBetterWork

Reputation: 503

Retrieve input value from jQuery UI dialog box

I am working on a small project (just a practice example - not for real use). Its a very simple CRUD application, and I am not allowed to alter the index.html. Also have to use jQuery UI Dialog and not prompt().

I got up to ADD functionality and I'm stuck. I've created a jQuery UI dialog that appends a form - its triggered when 'Add item' is clicked. Then The action for clicking 'yes' in the form needs to return what was in the input. I am unable to retrieve the value and there is no server side technology (like PHP) involved. function add_item() in answers.js is where I am working now.

I also don't know why, but an additional input box appears on the bottom of my html page after clicking 'Add item' (it should only append to the form )

*Note: CRUD functions begin after document.ready...lower on the page. Also, besides the one default item in index.html list items are originally from a JSON file *

answer.js

   $(document).ready(function()
    {

///////// REMOVE ALL  ////////////
    $(document).on("click", "div a:nth-of-type(3)", function(e)
    {
        e.preventDefault();
        remove_all();
    });
    $("div a:nth-of-type(3)").click(remove_all);

    ///////// ADD ITEM  ////////////
    $(document).on("click", "#add_item", function(e)
    {
          e.preventDefault();
          add_item();
    });
    $("#add_item").click(add_item);

///////// LOAD ALL ////////////
        $(document).on("click", "div a:nth-of-type(2)", function(e)
        {
            e.preventDefault();
            load_all();
        });

///////// REMOVE ITEM  ////////////
        $(document).on("click", "#my_list a", function(e)
        {
            e.preventDefault();
            var current_item = $(this).parent();
            remove_item(current_item);
        });
        $("#my_list a").click(remove_item(current_item));

///////// EDITABLE ITEM  ////////////

});

/// CRUD FUNCTIONS ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function add_item()
{

$('body').append('<div id="dialog-form"><form> Add your item:<br><input type="text" name="new_item" id="new_item" ></form></div>');

//  JQUERY UI DIALOG
  $( "#dialog-form" ).dialog({
    resizable: false,
    title:'Add new item',
    height:240,
    width:260,
    modal: true,
    buttons: {
      "Yes": function() {
        var test = $('#new_item').val();
         alert(test);

        $( this ).dialog( "close" );
      },
      Cancel: function() {
        $( this ).dialog( "close" );
      }
    }
  });

}

function remove_all()
{
      $('#my_list li').hide();
}

function load_all()
{
        $.getJSON( "myLists/myList.json", function( json )
        {
            var items = json;
            $('#my_list li').remove();

            $.each(items, function(index,the_item)
            {
              $('#my_list').append('<li>'+the_item+'<a href="#">x</a></li>')
            });
        });
}

function remove_item(current_item)
{
        // APPEND DIALOG BOX DIV
        $('<div id="dialog-confirm">').appendTo('body');

        // JQUERY UI DIALOG
        $( "#dialog-confirm" ).dialog({
          resizable: false,
          title:'Remove this item?',
          height:140,
          width:260,
          modal: true,
          buttons: {
            "Yes": function() {
              $(current_item).hide();
              $( this ).dialog( "close" );
            },
            Cancel: function() {
              $( this ).dialog( "close" );
            }
          }
        });
  }

INDEX.HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <link href="jquery-ui/css/ui-lightness/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" media="screen" />
    <script type="text/javascript" src="jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="jquery-ui/js/jquery-ui-1.10.3.custom.min.js"></script>
    <script type="text/javascript" src="answer.js"></script>
    <title>jQuery Test</title>
</head>
<body>
    <div>
        <h1>My Shopping List</h1>
        <a href="#" id="add_item">Add Item</a> | <a href="#">Load List</a> | <a href="#">Clear List</a>
        <ul id="my_list">
            <li>Brand New Shoes <a href="#">x</a></li>
        </ul>
    </div>
</body>
</html>

Upvotes: 0

Views: 3103

Answers (1)

Twisty
Twisty

Reputation: 30883

Offering a few updates that I think might help:

Working Example: https://jsfiddle.net/Twisty/5g72nncw/

$(document).ready(function() {

  ///////// REMOVE ALL  ////////////
  $(document).on("click", "div a:nth-of-type(3)", function(e) {
    e.preventDefault();
    remove_all();
  });
  $("div a:nth-of-type(3)").click(remove_all);

  ///////// ADD ITEM  ////////////
  $(document).on("click", "#add_item", function(e) {
    e.preventDefault();
    console.log("Running Add Item.");
    add_item();
  });
  $("#add_item").click(add_item);

  ///////// LOAD ALL ////////////
  $(document).on("click", "div a:nth-of-type(2)", function(e) {
    e.preventDefault();
    load_all();
  });

  ///////// REMOVE ITEM  ////////////
  $(document).on("click", "#my_list a", function(e) {
    e.preventDefault();
    var current_item = $(this).parent("li");
    remove_item(current_item);
  });
  //$("#my_list a").click(remove_item(current_item));

  ///////// EDITABLE ITEM  ////////////

});

/// CRUD FUNCTIONS ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function add_item() {
  if ($("#dialog-form").length == 0) {
  console.log("Dialog not found, creating new Dialog.");
    var newDialog = $("<div>", {
      id: "dialog-form"
    });
  } else {
  console.log("Dialog Found.");
    var newDialog = $("#dialog-form");
    newDialog.dialog("open");
    return true;
  }
  newDialog.append("<label style='display: block;'>Add your item:</label><input type='text' id='new_item' />");
  //$('body').append('<div id="dialog-form"><form> Add your item:<br><input type="text" name="new_item" id="new_item" ></form></div>');

  //  JQUERY UI DIALOG
  newDialog.dialog({
    resizable: false,
    title: 'Add new item',
    height: 240,
    width: 260,
    modal: true,
    autoOpen: false,
    buttons: [{
      text: "Yes",
      click: function() {
        var test = $('#new_item').val();
        console.log(test);
        $("#my_list").append("<li>" + test + " <a href='#'>x</a></li>");
        $(this).dialog("close");
        $('#new_item').val("");
      }
    }, {
      text: "Cancel",
      click: function() {
        $(this).dialog("close");
        $('#new_item').val("");
      }
    }]
  });
  //$("body").append(newDialog);
  newDialog.dialog("open");
}

function remove_all() {
  $('#my_list li').remove();
}

function load_all() {
  $.getJSON("myLists/myList.json", function(json) {
    var items = json;
    $('#my_list li').remove();

    $.each(items, function(index, the_item) {
      $('#my_list').append('<li>' + the_item + '<a href="#">x</a></li>')
    });
  });
}

function remove_item(current_item) {
  // APPEND DIALOG BOX DIV
  $('<div id="dialog-confirm">').appendTo('body');

  // JQUERY UI DIALOG
  $("#dialog-confirm").dialog({
    resizable: false,
    title: 'Remove this item?',
    height: 140,
    width: 260,
    modal: true,
    buttons: {
      "Yes": function() {
        $(current_item).hide();
        $(this).dialog("close");
      },
      Cancel: function() {
        $(this).dialog("close");
      }
    }
  });
}

When removing an item, you want to pass the <li> to your function. This way it is removed from the <ul>.

When adding the item, I did not append the <div> to the body. I noticed when you appended the <div>, since it was not in the DOM when the page loaded, it does not get initialized as a .dialog() and thus is rendered into the HTML. My method avoids this.

Nothing wrong with the way you create the buttons, yet this is more specific and is how it is described by the UI API: http://api.jqueryui.com/dialog/#option-buttons

Hope this helps.

Upvotes: 2

Related Questions