Firebase:如何设置:节点Foreach输入字段

时间:2016-02-23 01:53:42

标签: firebase

这适用于民意调查网络应用 Polls App
我想要的是什么:

  • 点击“创建投票”按钮后,Firebase会按下(创建唯一ID)。
  • 此唯一ID(例如:-KBAi-3yaROWfzdmuFk5)有一个子poll: "Do you like Pina Coladas?" - 来自问题输入字段。
  • 然后poll:节点获得子Choices:
  • Choices:节点有一个选择的子节点(来自输入字段)
  • 每个选择节点都有一个孩子vote_count: 0
    • .set({ vote_count: 0 });
var myDataRef = new Firebase('https://...firebaseio.com/');

// CLICK Add NEW POLL / Check to see if Poll has Name & least 2 responses
$( "#PollCreate" ).click(function add() {
  var name = $('#pollQuestion').val();
  var text = $('#text1').val();
  var text2 = $('#text2').val();
  if(name != '' && text != '' && text2 != '') {
    var newPostRef = myDataRef.push();
    newPostRef.set({ poll: name });

    $("#choices :input").each(function() {
      var input = $(this).val();
      // check if added choices are Null
      if( input != '') {
        var newPostRef = myDataRef.push();
        newPostRef.child().set({ choice: input }).set({ vote_count: 0
                                                      });
        console.log(input);
      }
      $(this).val('');
    });
  } else { $('.input_Error').show(); }
});

我不知道这种结构是否最适合这种情况。我对其他想法完全开放 我还需要能够将数据恢复出来。
What I can get (Firebase Structure)

1 个答案:

答案 0 :(得分:0)

所以我自己弄明白了。
该网站可以在这里找到。 (除非我删除它)。 http://polls.rioweber.com
这是一页。

以下代码允许您从一组未知的输入字段中添加多个子项。



// When "Vote" button is clicked.
function updateShowPoll() {
  var choice = '';
  //Get which Choice (radio button) was selected
  choice = $('#radioButtons input:radio:checked').val();

  // check that a button was selected
  if ($('#radioButtons input:radio:checked').is(':checked') && choice != '') {

    // Increment the users vote choice
    //Get the Unique ID from the URL Hash
    var randomKey = window.location.hash.substr(1);

    // Increment the "vote_count" for the selected choice
    var voteCountLocation = new Firebase('https://thepolls.firebaseio.com/' + randomKey + '/Choices/' + choice + '/vote_count');
    voteCountLocation.transaction(function(voteCount) {
      // If /users/fred/rank has never been set, currentRank will be null.
      return voteCount + 1;
    });

    // show the data
    PollBreakDown();
  } else {
    // TO bold and highlight the text that says "Please select one of the following options:"
    // If the users hits the Vote button without selecting an option (radio button)
    $('.lead').css({
      'color': 'red',
      'font-weight': '400'
    })
  };
};




这里是整个网站:
(可能因为我更改了我的Firebase权限而无法工作,但你可以自己测试它。你只需要改变FireBase加载到你自己的FireBase URL的位置。)



<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>The Polls | Made w/ Firebase</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <!-- SEO -->
  <meta name="description" content="Polls Made with FireBase">
  <meta name="keywords" content="Bootstrap,Polls,Firebase">
  <meta name="author" content="Rio Weber">
  <!-- FAVICON -->
  <link rel="shortcut icon" href="https://www.firebase.com/resources/images/website/icons/favicon-production.ico">

  <!-- FIREBISE -->
  <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
  <!-- JQuery -->
  <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>

  <!-- ANGULAR -->
  <!-- Angular Material style sheet -->
  <!-- <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> -->

  <!-- BOOTSTRAP -->
  <!-- Latest compiled and minfied CSS -->
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <!-- Latest compiled and minified JavaScript -->
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

  <!--My JavaScript file-->
  <script src=""></script>
  <!-- MY CSS -->
  <link rel="stylesheet" type="text/css" href="style.css">

  <style>
    .navbar {
      border-radius: 0;
    }
    .input_Error,
    .Max_Error,
    #PollNew,
    #viewVote,
    #PollResults {
      display: none;
    }
  </style>

</head>

<body>
  <nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
      <div class="navbar-header">
        <a href="#" id="home" onclick="showAllPolls()" class="navbar-brand" style="color:#FFF;cursor:pointer;">The Polls</a>
      </div>
    </div>
  </nav>

  <!-- POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls -->
  <!-- POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls -->
  <!-- POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls - POLLS - polls -->
  <div id="PollList" class="container">
    <div class="page-header">
      <h1>Poll List</h1>
    </div>
    <div class="row">
      <div class="col-xs-5">
        <a href="#" onclick="makeNewPoll()" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> New Poll</a>
      </div>
      <div class="col-xs-7">
        <input type="text" class="form-control" ng-model="query" placeholder="Search for a poll">
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12">
        <hr>
      </div>
    </div>
    <div class="row">
      <ul id="NoPolls">
        <li><em>No polls in databases. Would you like to <a href="#" onclick="makeNewPoll()">create one</a>?</em>
        </li>
      </ul>
      <ul id="Polls_UL">
      </ul>
    </div>
    <p>&nbsp;</p>
  </div>

  <!-- NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll-->
  <!-- NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll-->
  <!-- NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll - NEW Poll-->
  <div id="PollNew" class="container">
    <div class="page-header">
      <h1>Create New Poll</h1>
    </div>

    <div class="form-group">
      <label for="pollQuestion">Question <span class="input_Error" style="color:red;">- Your Poll must have a name</span>
      </label>
      <input id="pollQuestion" type="text" class="form-control" placeholder="Enter poll question" required>
    </div>

    <div id="choices" class="form-group">
      <label>Choices <span class="input_Error" style="color:red;">- Poll must have at least two options</span>
      </label>
      <div>
        <input id="text1" type="text" class="form-control" placeholder="Enter choice 1 text" required>
        <br>
      </div>
      <div>
        <input id="text2" type="text" class="form-control" placeholder="Enter choice 2 text">
        <br>
      </div>
      <div>
        <input type="text" class="form-control" placeholder="Enter choice 3 text">
        <br>
      </div>
    </div>
    <p class="Max_Error" style="color:red;">Max of 12 choices</p>

    <div class="row">
      <div class="col-xs-12">
        <a href="#" id="addChoice" type="button" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> Add another</a>
      </div>
    </div>

    <p>
      <hr>
    </p>

    <div class="row">
      <div class="col-xs-6">
        <a href="#" onclick="showAllPolls()" class="btn btn-default" role="button"><span class="glyphicon glyphicon-arrow-left"></span> Back to Poll List</a>
        <a id="PollCreate" class="btn btn-primary">Create Poll &raquo;</a>
      </div>
    </div>
    <p>&nbsp;</p>
  </div>

  <!-- View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote -->
  <!-- View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote -->
  <!-- View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote - View/Vote -->
  <div id="viewVote" class="container">
    <div class="page-header">
      <h1>View Poll</h1>
    </div>
    <div class="well well-lg">
      <strong>Question</strong>
      <br>
      <span id="PollName"></span>
    </div>
    <div id="PollVote">
      <p class="lead">Please select one of the following options:</p>
      <div>
        <div id="radioButtons">
        </div>

        <p>
          <hr>
        </p>

        <div class="row">
          <div class="col-xs-6">
            <a href="#" onclick="showAllPolls()" class="btn btn-default" role="button"><span class="glyphicon glyphicon-arrow-left"></span> Back to Poll List</a>
            <a href="#" onclick="$('#PollVote').hide(); $('#PollResults').show();PollBreakDown();" class="btn btn-default" role="button">Skip <span class="glyphicon glyphicon-arrow-right"></span></a>
          </div>
          <div class="col-xs-6">
            <a onclick="updateShowPoll()" class="btn btn-primary pull-right">Vote &raquo;</a>
          </div>
        </div>
      </div>
    </div>
    <div id="PollResults">
      <table id="PollBreakDown" class="result-table">
      </table>

      <p>
        <em>
               <span id="votesCounted"></span> votes counted so far.
               <!-- WILL NEED COOKIES FOR THIS, or something... -->
               <!-- <span ng-show="poll.userChoice">You voted for <strong>{{poll.userChoice.text}}</strong>.</span> -->
            </em>
      </p>

      <p>
        <hr>
      </p>

      <p>
        <a href="#" onclick="showAllPolls()" class="btn btn-default" role="button"><span class="glyphicon glyphicon-arrow-left"></span> Back to Poll List</a>
      </p>
    </div>
    <p>&nbsp;</p>
  </div>

  <!-- SCRIPTS -->
  <!-- Root of the Databse -->
  <script type="text/javascript">
    // link to the Databse
    var myDataRef = new Firebase('https://thepolls.firebaseio.com/');
  </script>

  <script type="text/javascript">
    // Check if URL hash is set, if it is = check if hash exists, if it does = showPoll();
    $(document).ready(function() {
      if (window.location.hash) {
        var hashCheck = window.location.hash.substr(1);
        console.log(hashCheck);

        myDataRef.once("value", function(snapshot) {
          if (snapshot.child(hashCheck).exists()) showPoll();
        });
      };
    });
  </script>

  <script type="text/javascript">
    // When "Vote" button is clicked.
    function updateShowPoll() {
      // remove all the data from Table 
      $('#PollBreakDown').empty();
      var choice = '';
      //Get which Choice (radio button) was selected
      choice = $('#radioButtons input:radio:checked').val();

      // check that a button was selected
      if ($('#radioButtons input:radio:checked').is(':checked') && choice != '') {
        $("#PollVote").hide();
        $("#PollResults").show();
        // Increment the users vote choice
        //Get the Unique ID from the URL Hash
        var randomKey = window.location.hash.substr(1);

        // Increment the "vote_count" for the selected choice
        var voteCountLocation = new Firebase('https://thepolls.firebaseio.com/' + randomKey + '/Choices/' + choice + '/vote_count');
        voteCountLocation.transaction(function(voteCount) {
          // If /users/fred/rank has never been set, currentRank will be null.
          return voteCount + 1;
        });

        // show the data
        PollBreakDown();
      } else {
        $('.lead').css({
          'color': 'red',
          'font-weight': '400'
        })
      };
    };

     // show the data results form the votes
    function PollBreakDown() {
      $('#PollBreakDown').empty();
      /*
      <tr>
         <td>Choice</td>
         <td>
            <table style="background-color: lightblue; width: 50%; text-align: right">
               <tr><td>1</td></tr>
            </table>
         </td>
      </tr>
      */
      var randomKey = window.location.hash.substr(1);

      // ADDING DATA TO POLLBREAKDOWN
      var ChoicesChildren = new Firebase('https://thepolls.firebaseio.com/' + randomKey + '/Choices');

      ChoicesChildren.once("value", function(snapshot) {
        // ForEach that will all up all the

        var totalVotes = 0;

        snapshot.forEach(function(childSnapshot) {
          var childData = childSnapshot.child("vote_count").val();
          totalVotes += childData;
        });
        $("#votesCounted").text(totalVotes);

        // ForEach Choices Child - Add Table with proper width
        snapshot.forEach(function(childSnapshot) {
          // key will be "fred" the first time and "barney" the second time
          var key = childSnapshot.key();
          //console.log(key);
          // childData will be the actual contents of the child
          var childData = childSnapshot.child("vote_count").val();
          //console.log(childData);

          $('<tr>').prepend('<td>' + key + '</td>' +
            '<td>' +
            '<table style="width: ' + ((childData / totalVotes) * 100) + '%;">' +
            '<tr><td>' + childData + '</td></tr>' +
            '</table>' +
            '</td>').appendTo($('#PollBreakDown'));
        });
      });
    };
  </script>

  <script type="text/javascript">
    // View / Make - Polls
    function makeNewPoll() {
      $("#PollNew").toggle();
      $("#PollList").toggle();
      $('.input_Error').hide();
    };
     // View Vote
    $("#Polls_UL").on("click", "li a", function(event) {
      // Change the URL - THIS IS BECAUSE "randomKey" value is set before the URL changes. So must change the URL Manually
      window.location.hash = $(this).attr('href');
      // Show the Poll Details/Vote/Totals
      showPoll();
    });

    function showPoll() {
      $("#PollNew").hide();
      $("#PollList").hide();
      $("#viewVote").show();
      // Will need to update to prevent double voting.
      $("#PollVote").show();
      $("#PollResults").hide();

      //window.location.hash='';

      // Get the Unique ID of the Poll Click on from the (a href="uniqueID")
      var randomKey = window.location.hash.substr(1);
      var pollName = '';

      myDataRef.once("value", function(snapshot) {
        pollName = snapshot.child(randomKey).child("poll").val();

        // set the text in the span to the Question Name
        $("#PollName").text(pollName);
        // reset the choices
        $('#radioButtons').empty();
        // add each radio choice option
        snapshot.child(randomKey).child("Choices").forEach(function(childSnapshot) {
          $('<div>').addClass("radio").prepend(
            $('<label>').prepend(
              '<input type="radio" name="choice" value="' + childSnapshot.key() + '">' + childSnapshot.key())).appendTo($('#radioButtons'));
        });
      });
    };
     // Show All Polls 
    function showAllPolls() {
      $("#PollNew").hide();
      $("#PollList").show();
      $("#viewVote").hide();
      $('.lead').css({
        'color': '#000',
        'font-weight': '300'
      })
    }
  </script>

  <!-- ADD NEW CHOICE -->
  <script type="text/javascript">
    var choiceNum = 4;
    $("#addChoice").click(function() {
      if (choiceNum < 13) {
        $('<div>').prepend('<input type="text" class="form-control" placeholder="Enter choice ' + choiceNum + ' text"><br>').appendTo($('#choices'));
      } else {
        $('.Max_Error').show();
      }

      choiceNum++;
    });
  </script>


  <script type="text/javascript">
    // CLICK Add NEW POLL / Check to see if Poll has Name & least 2 responses
    $("#PollCreate").click(function add() {
      var name = $('#pollQuestion').val();
      var text = $('#text1').val();
      var text2 = $('#text2').val();
      if (name != '' && text != '' && text2 != '') {
        var newPostRef = myDataRef.push();
        newPostRef.set({
          poll: name
        });


        $("#choices :input").each(function() {
          var input = $(this).val();
          // check if added choices are Null
          if (input != '') {
            newPostRef.child("Choices").child(input).set({
              vote_count: 0
            });
            //console.log(input);
          }
          $(this).val('');
        });
        $('#pollQuestion').val('');
        showAllPolls();
      } else {
        $('.input_Error').show();
      }
    });

     // START OF WEBSITE
     // SHOW ALL THE POLLS IN THE DATABASE - MAIN PAGE
    myDataRef.on('child_added', function(snapshot) {
      $('#NoPolls').remove();
      message = snapshot.val();
      //console.log(message.poll);

      $('#Polls_UL').append('<li><a href="#' + snapshot.key() + '">' + message.poll + '</a></li>');
    });

    /*
    Do you like pina coladas?
    Do you like getting caught in the rain?
    Do you like making love at Midnight?
    */
  </script>

  <!-- Angular Material requires Angular.js Libraries -->
  <!--  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> -->

  <!-- Angular Material Library -->
  <!-- <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> -->
</body>
</html>
&#13;
&#13;
&#13;