dimanche 3 mai 2015

Formula Calculation using javaScript

I am trying to do the below using HTML, CSS and JavaScript:

  1. Category (Coffee Appliance) drop down

  2. product (Kurig Coffe Maker) drop down

  3. Wattage : 1500kWh (pre polulated using Local Storage)

  4. Daily Energy Consumption (1,500 W × 1) ÷ 1,000 = 1.5 kWh

  5. Annual energy consumption: User enters no of Days used.(365) 1.5 kWh × 365 = 547.5 kWh

  6. Annual cost: The utility rate is 11 cents per kWh. (User enters utility rate as per his geography) 547.5 kWh × $0.11/kWh = $60.23/year

ALSO : Please find my attempt at writing the PSEUDO CODE in the JS file as comments. Can you please guide me if I am on the the right path.

What is working :Dropdowns

function configureDropDownLists(category, products) {
  var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS');
  var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana');

<!-- begin snippet: js hide: false -->
#leftColumn {

  width: 500px;

  float: left;

}

.placeholderText {

  font: bold 12px/30px Georgia, serif;

}

body {

  padding-left: 45px;

}

#annualEnergyConsumption {

  font: bold 25px arial, sans-serif;

  color: #00ff00;

}

#annualCostOperation {

  font: bold 40px arial, sans-serif;

  color: #00ff00;

}

.dailyButInline {

  display: inline;

}

/* mouse over link */

button:hover {

  background-color: #00ff00;

}

/* selected link */

button:active {

  background-color: #00ff00;

}
<h2>Annual Energy Consumption and Cost Calculator</h2>

<form id="costForm">

  <div id="leftColumn">

    <div>





      <span class="placeholderText">Choose Category</span>
      </br>
      <span>
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('products'))">
<option value="">Select a Category</option>
<option value="refrigerators">Refrigerators</option>
<option value="dishWasher">DishWasher</option>
</select>
        </span>
      </br>
      </br>
    </div>

    <div>
      <span class="placeholderText">Select a Product</span>
      </br>
      <span>
        <select id="products">
                        <option selected>--------------------------</option>
        </select>
        </span>
      </br>
      </br>
    </div>



    <div>
      <span class="placeholderText">Wattage</span>
      </br>
      <span id="wattage">1500</span>
      </br>
      </br>
    </div>

    <div id="buttonBoundary">
      <div class="placeholderText">Estimated Daily Use</div>

      <div class="dailyButInline">
        <button id="h1">Not a Lot</br>1 hour per day</button>
      </div>
      <div class="dailyButInline">
        <button id="h3">Average</br>3 hour per day</button>
      </div>
      <div class="dailyButInline">
        <button id="h6">A Lot</br>6 hour per day</button>
      </div>
      <div class="dailyButInline">
        <button id="h24">Always On</br>24 hours per day</button>
      </div>

      </br>
      </br>

    </div>
    <div>
      <span class="placeholderText">Daily Energy Consumption</span>
      </br>
      <div id="annualEnergyConsumption">0.268 kWh</div>
      </br>
    </div>


    <div>
      <span class="placeholderText">Approximate Days used per year</span>
      </br>
      <div id="daysUsed">
        <input type="number" id="hour" maxlength="2" min="1">
        </br>
        <input type="checkbox" id="allYear" />
        <label for="allYear">All year</label>
      </div>
      </br>
    </div>

    <div>
      <span class="placeholderText">Annual Energy Consumption</span>
      </br>
      <div id="annualEnergyConsumption">547.5 kWh</div>
      </br>
    </div>




  </div>


  <div id="right">


    <div>
      <span class="placeholderText">Enter your Utility Rate per Kw/h</span>
      </br>
      <span><input type="number" id="utilityRate" /></span>
      </br>
      </br>
    </div>


    <div>
      <span class="placeholderText"><button id="annualCost">Annual Cost to Operate</button></span>
      </br>
      <span id="annualCostOperation" /></span>
    </div>

  </div>

</form>

</body>
  switch (category.value) {
    case 'refrigerators':
      products.options.length = 0;
      for (i = 0; i < refrigerators.length; i++) {
        createOption(products, refrigerators[i], refrigerators[i]);
      }
      break;
    case 'dishWasher':
      products.options.length = 0;
      for (i = 0; i < dishWasher.length; i++) {
        createOption(products, dishWasher[i], dishWasher[i]);
      }
      break;
    default:
      products.options.length = 0;
      break;
  }

}

function createOption(ddl, text, value) {
  var opt = document.createElement('option');
  opt.value = value;
  opt.text = text;
  ddl.options.add(opt);
}

/*  

    dailyEnergyConsumption = function() 

initialize dailyEnergyConsumption = null; Check what the user has selected from the products drop down and display that unique wattage. Wattage is stored is stored in Local Storage. it will be called based on what product is selected.

Store and Call the selected wattage as we need that to calculate Daily Energy Consumption

Track the 4 buttons with an Event Listener (Estimated Daily Use)

Based on the above pass wattage to the formula (1,500 W × 1) ÷ 1,000 = 1.5 kWh Display and store 1.5 Kwh Make sure the Category and Products drop down don’t get reset. }

annualEnergyConsumption = function() { take the variable from dailyEnergyConsumption and multiply that by no of days the user enters 1.5 kWh × 365 (days) = 547.5 kWh Store it do not display this Pass it to annual Cost function }

annualCost = function() { take 547.5 Kwh from annualEnergyConsumption function capture what the user enters in Utility Rate textbox (11 cents per K Wh) So ( Calculate 547.5 kWh × $0.11/kWh = $60.23/year) Display 60.23 /year }

*/

#leftColumn {

  width: 500px;

  float: left;

}

.placeholderText {

  font: bold 12px/30px Georgia, serif;

}

body {

  padding-left: 45px;

}

#annualEnergyConsumption {

  font: bold 25px arial, sans-serif;

  color: #00ff00;

}

#annualCostOperation {

  font: bold 40px arial, sans-serif;

  color: #00ff00;

}

.dailyButInline {

  display: inline;

}

/* mouse over link */

button:hover {

  background-color: #00ff00;

}

/* selected link */

button:active {

  background-color: #00ff00;

}

<h2>Annual Energy Consumption and Cost Calculator</h2>

<form>

  <div id="leftColumn">

    <div>





      <span class="placeholderText">Choose Category</span>
      </br>
      <span>
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('products'))">
<option value="">Select a Category</option>
<option value="refrigerators">Refrigerators</option>
<option value="dishWasher">DishWasher</option>
</select>
    </span>
      </br>
      </br>
    </div>

    <div>
      <span class="placeholderText">Select a Product</span>
      </br>
      <span>
    <select id="products">
            <option selected>--------------------------</option>
    </select>
    </span>
      </br>
      </br>
    </div>



    <div>
      <span class="placeholderText">Wattage</span>
      </br>
      <span id="wattage">1500</span>
      </br>
      </br>
    </div>

    <div id="buttonBoundary">
      <div class="placeholderText">Estimated Daily Use</div>

      <div class="dailyButInline">
        <button id="h1">Not a Lot</br>1 hour per day</button>
      </div>
      <div class="dailyButInline">
        <button id="h3">Average</br>3 hour per day</button>
      </div>
      <div class="dailyButInline">
        <button id="h6">A Lot</br>6 hour per day</button>
      </div>
      <div class="dailyButInline">
        <button id="h24">Always On</br>24 hours per day</button>
      </div>

      </br>
      </br>

    </div>



    <div>
      <span class="placeholderText">Approximate Days used per year</span>
      </br>
      <div id="daysUsed">
        <input type="number" id="hour" maxlength="2" min="1">
        </br>
        <input type="checkbox" id="allYear" />
        <label for="allYear">All year</label>
      </div>
      </br>
    </div>

    <div>
      <span class="placeholderText">Enter your Utility Rate per Kw/h</span>
      </br>
      <span><input type="number" id="utilityRate" /></span>
      </br>
      </br>
    </div>


  </div>


  <div id="right">



    <div>
      <span class="placeholderText">Annual Energy Consumption</span>
      </br>
      <div id="annualEnergyConsumption">547.5 kWh</div>
      </br>
    </div>


    <div>
      <span class="placeholderText">Annual Cost to Operate</span>
      </br>
      <span id="annualCostOperation" />$10.76 / year</span>
    </div>

  </div>

</form>

Mongoose create conflict after one document saved to database

I can't for the life of me figure out what simple thing I'm doing wrong here. I've widdled the user schema down to one property, name. When i post the first one to the database all is well and it is saved. When I try to save another one with a different name I get CONFLICT. It must be something super simple I'm missing but I need an extra set of eyes to check it out.

Here's my schema (user.js)

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
  name: {
    type: String
  }
});

var User = mongoose.model('User', userSchema);

module.exports = userSchema;

Here's my my post request (index.js)

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var app = express();

// db connection and models
var conn = require('./db');
var User = conn.model('User');

// middleware
app.use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json

// POST - create a user

app.post('/api/user', function (req, res) {
  console.log(req.body);
  User.create(req.body, function (err, user) {
    if (err) {
      if (err.code === 11000) {
        return res.sendStatus(409); // conflict
      } else {
        return res.sendStatus(500); // server error
      }
    }
    res.sendStatus(200); // ok - user created
  });  
});

app.listen(3000);
console.log('Listening...');

AngularJS: won't present data in separated file on ng-select

I am using AngularJS for creating web app. This is the link which present my full code (example with b.0001.html). AngularJS example

How can I get value ($scope.confirmed in $scope.change function) in controller when user select option data from form? The main problem is that everything works fine if I create one file, but with separated file it won't work, that means if you have one file which include another file with form (using routing in AngularJS).

The form is, which I include in main file with routing mechanism

< select ng-model="confirmed" ng-change="change()" id="ng-change-example1">
< option > 11 < /option>
< option > 12 < /option>
< option > 13 < /option>
< option > 14 < /option>

< input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
< label for="ng-change-example2">Confirmed</label><br />
< tt>debug = {{confirmed}}</tt><br/>
< tt>counter = {{counter}}</tt><br/>

<tt>onchange_var_url = {{myurl}}</tt><br/>

< ul>
  < li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  < /li>
< /ul>

Variable myurl should get value from user option select, but it doesn't. This is controler

angular.module('changeExample', [])
.controller('ExampleController', ['$scope','$http', function($scope,$http) {

$scope.counter = 0;

$scope.myurl = 'result from confirmed on change on load: ' + $scope.confirmed;

$scope.change = function() {
    $scope.counter++;

    $scope.myurl = 'result from confirmed on change: ' + $scope.confirmed;

    $http.get("angularjs-data/json-data-0001.json?var=" + $scope.confirmed)
        .success(function (response) {
            $scope.names = response.records;
        });
};

}]);

In Sails js how to load alternative templates within the front page (all screens)

In Sails js we design a main template where our app replaces (in turn, on click) nested templates within, in place of the initial nested app template.

We may not use any library or framework on top of Sails, unless necessary.

The question is : in Sails js what is the most efficient way to display alternative templates within the front page template ?

Do header and footer combined with ejs-locals run/render well on smartphones ?

Submitting form and success message on same page?

So right now I have a basic contact.html with a php script set to email me if someone on my website contacts me. When they click submit, it takes them to contact_sent.php, which is a blank page. I want it so that when they click the submit, it keeps them on the same page, as well as display a success message from SweetAlert, and then clear the form so they can't spam the "Send Message" button.

<?php
if($_POST['submit']) {
    $name=$_POST['name'];
    $email=$_POST['email'];
    $subject=$_POST['subject'];
    $message=$_POST['msg'];
    $to_add="***********@gmail.com";
    $from_add="form@***********.net";

    $email_message="<br /><br /><b>Name:</b><br />$name <br />";
    $email_message.="<br /><br /><b>Reply Email:</b><br />$email <br />";
    $email_message.="<br /><br /><b>Regarding:</b><br />$subject <br />";
    $email_message.="<br /><br /><b>Message:</b><br />$message <br />";

    $headers="From: $from_add \r\n";
    $headers.="Reply-To: $from_add \r\n";
    $headers.="Return-Path: $from_add\r\n";
    $headers.="X-Mailer: PHP \r\n";
    $headers.="MIME-Version: 1.0\r\n";
    $headers.="Content-Type: text/html;\r\n";

    mail($to_add,$subject,$email_message,$headers);
}
alert("Sent!");
?>

Edit: The alert at the end doesn't work.

Can't force page to scroll to top on refresh on chrome

i'm trying to force the page to scroll to top on refresh with something similar to this

$(window).scrollTop(0);

But it seems to happen before the automatic scroll down on refresh. My script runs and then the browser restores its last position.

I'm running the code in several places like this

        $(function(){
            $(window).scrollTop(0);
        });

        $(window).scrollTop(0);

        $(document).ready(function(){
            $(window).scrollTop(0);
        });

        $(window).on('load',function(){
            $(window).scrollTop(0);
        });

BUt the same happens all the time. Do I have to put this code somewhere else? Load the JS in a specific part of the HTML? Is there anything else on pure JS or jQuery that could help me with this issue?

@Edit

I tried with $(html, body).scrollTo(0) and couldnt make it work

I tried without jQuery and nothing happened

window.scrollTo(0,0)

I disabled everything I had written with Javascript and put only this piece of code and nothing happens.

@edit2

I've had this problem before and I'm sure i 'solved' this with a setTimeout, as suggested by @raam86. The problem is that I do some math when page loads and this must be done before the user starts scrolling up and down

How not to match a certain regexp in javascript?

I want to check if a variable do not match this regexp:

DEMO

So this is the pattern that match the regexp in my code:

rxAfterPrint = new RegExp(/^ *\+ *("(?:[^"]*)"|(?:[a-zA-Z]\w*)) *(.*)$/);

and in this way I check for matching:

var t2 = t[2].match(rxAfterPrint); and now I want to create e varible t3 that dont match this pattern

How can I do this? can you please help me?

update Html.TextBoxFor "readonly" attribute on and off

I'm srugelling with this, Working on MVC, upon change on Html.TextBoxFor value I want to change a readonly attribute of another Html.TextBoxFor. I tried several ways-using IE it does not work. here some code:

@Html.TextBoxFor(x => x.NumberOfQuestion, new { id = "ExamOptions", onchange = "javascript:ReadOnlyHandle();" })

<script>
    function ReadOnlyHandle() {
        //document.getElementById("NoDiffNum").readOnly = true;
        var startHSelect = document.getElementById("NoDiffNum");
        debugger;
        startHSelect.setAttribute("readonly", "true");
    }
    debugger;
</script>

and the row in a table I would like to change:

<td id="NoDiffNum">@Html.TextBoxFor(model => model.Topics[i].NumberOfNoDifficulltySet)</td>

the readonly attribute did not changed - any help is most welcome!

How can I save the result of this javascript into mySQL?

Hee is my code, however how can I save the result into mySQL DB?

var d1 = new Date();
var fp = new Fingerprint2();

fp.get(function(result) {
  var d2 = new Date();
  console.log("Time took to calculate the fingerprint: " + (d2 - d1) + "ms");
  console.log(result);
  document.getElementById("fp").innerHTML = result;

});

How to prevent: A potentially dangerous Request.Form value was detected from the client

asp.net C# 4.5 application

page level validation disable not working since 4+ event validation is targeted

So i need to encode textbox content before submitting the form

However my try failed

   function encodeTextBox() {
           <%
    txtNewsBody.Text = System.Web.HttpUtility.HtmlEncode(txtNewsBody.Text);
         %>
       }


          <asp:Button ID="btnAddNews" OnClientClick="encodeTextBox(); return true;" runat="server" Text="add_news" OnClick="btnAddNews_Click" />

Passing parameters from one django view to another using JSON/AJAX

I'm trying to pass the category variable that a user has selected into the "category_id" variable in the BudgetJson view. The BudgetJson view is being called via a javascript AJAX call that's inside the expenses/detail.html template.

This is the view that renders when a user selects what expense they want more details on:

class ExpenseDetail(
    braces.PrefetchRelatedMixin,
    generic.DetailView
):
    model = models.ExpenseCategory
    prefetch_related = ('expenseCategory',)
    http_method_names = ['get']
    template_name = 'expenses/detail.html'


    def get(self, request, *args, **kwargs):
        self.object = self.get_object(kwargs.get('pk'))
        self.category = self.object.category
        self.category_id = self.object.expenseCategory.get_queryset.im_self.values()[0]['category_id']
        return super(ExpenseDetail, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ExpenseDetail, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        queryset = super(ExpenseDetail, self).get_queryset()
        return queryset

This is the javascript in the template to fetch the data (a JSON object)

$(document).ready(function() {
        $('#expenses').DataTable( {
            "ajax": '{% url "property:budget:budget_json" %}'
    });
});        

This is the view that the AJAX url calls to get the JSON object. What I want to know how is to get the category_id from the first view into this view (what is currently set to 1)

def BudgetJson(request)
    out_list = []
    category_id = 1
    resultset = models.Expense.objects.filter(category_id=category_id)
    for model in resultset:
        temp_dict = {'expense_period': model.expensePeriod, 'expense_name':model.expenseName, 'expense_amount':model.expenseAmount }
        out_list.append(temp_dict)
    data = {'data' : out_list }
    return JsonResponse(data)

Model binding not working in Angular UI Bootstrap modal

I have simple example using Angular UI Bootstrap modal service. In this example I don't understand why model binding is not working. Instead of seeing "Doing something..." on modal dialog I see "{{message}}". What I need to change?

Example is here: http://ift.tt/1GSzNbt

modal html looks like this:

<div ng-app="myModule">
    <div ng-controller="modalInstanceController" class="modal-body">
        <div>{{message}}</div>
    </div>
</div>

And definition of module and controllers:

var myAppModule = angular.module('myModule', ['ui.bootstrap']);

myAppModule.controller('modalInstanceController', function ($scope, $modalInstance, message) {
    var vm = this;
    vm.message = message;
});

myAppModule.controller('myController', function ($scope, $modal) {


        $scope.open = function open() {

            var modalInstance = $modal.open({
                templateUrl: 'modal.html',
                backdrop: 'static',
                //windowClass: 'custom-modal-wait',
                dialogFade: false,
                keyboard: false,
                controller: 'modalInstanceController',
                resolve: {
                    message: function () {
                        return "Doing something ...";
                    }
                }
            });

            setTimeout(function(){
                modalInstance.close('close');
                },5000);
        }

});

JavaScript Weirdness - typeof [] === typeof {} evaluates to 'true'

I know the strict equals in JS evaluates two things: equality and like-typedness

Object.is() is the closest comparison I could find to gather further insight and it offered little further in my investigation.

Can anyone who groks the innards of JS better explain this? Is an array a very very strange implementation of an object? So they are empty and evaluate the same here?

I'm quite perplexed and just curious.

ReCaptcha 2.0: enable Submit button on callback if recaptcha successful

I have a very simple form as follows. I want to make it so that the Submit button is disabled, and only enabled after the user has successfully completed the ReCaptcha.

I'm assuming I'm going to need some Javascript / jQuery to do this.

Google's documentation on ReCaptcha 2.0 seems really sparse and dense (to me, anyway). I'd appreciate some pointers:

<form action="something.php" method="post">

Name: <input type="text" size="40" name="name">
<br>
<br>

<div class="g-recaptcha" data-sitekey="############-#####"></div>

<input type="submit" value="Submit" >

</form>

D3 barchart not populating.

I am trying to create a bar-chart using D3. However, the bar chart is not populating. The following is my code:

 var data = [Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()]

var height = 900 
var width = 600 

var x = d3.scale.linear()
    .range([0, width])
    .domain([0, d3.max(data)])

var y = d3.scale.linear()
    .range([height, 0])
    .domain([0, 500])

var svg = d3.select(".barchart").append('svg')
    .attr("height", height)
    .attr("width", width)    

var rect = svg.selectAll('rects')
    .data(data)
    .enter()
    .append('rects')
    .attr("height", function(d, i) { return height - y(d) })
    .attr("width", function (d, i) { return x(d) })
    .attr("x", function(d, i) { return x(i) })
    .attr("y", function(d, i) { return y(d) })
    .attr("fill", "blue")

Get return value from Javascript in Android

I want to get a return value from a JavaScript function that will be run after the URL changes (after login).

I followed this link. However I never get to onJsAlert method.

This is my javascript code:

if (typeof document.getElementById('infoContainer') !== 'undefined') {
document.getElementById('infoContainer')
.getElementsByClassName('gamerStat')[0].getElementsByTagName('a')[0].innerHTML }

If I put this code in:

webView.loadUrl("javascript:alert(my_code)");

I get error: uncaught syntaxerror: unexpected token if...

If you need additional info feel free to ask.

how to go about making a two player online game using python [on hold]

It will be a two player snake game. The longest snake after 20 apples are eaten wins.

can you give me a rough blueprint for this? Which libraries to use, do I need to use javascript...

How do I send input to the server and how do I send back the game state to the client?

thanks

edit: we are trying to get a group together on reddit to do this. see: http://ift.tt/1HUEa8N to join

How to pass a Console output to show as a pop up box in browser

I have a java code which outputs an Alert if it meet some condition. I am setting that value as below.

message = "Alert, Net Usage greater than or equal to threshold";
System.out.println(message);
request.setAttribute("message",message);
 RequestDispatcher dispatcher = request.getRequestDispatcher("jsppage.jsp");
 dispatcher.forward(request, response);

I want to display the "message" in a pop up in the browser. Please help.

Sinon spy on WebSocket

I am trying to spy on WebSocket construction using sinon.js with this code (requirebin):

sinon = require('sinon');

sinon.spy(window, 'WebSocket');
// throws an error (see console)
new window.WebSocket("ws://example.com");

In Chrome it fails with Uncaught TypeError: Failed to construct 'WebSocket': Please use the 'new' operator, this DOM object constructor cannot be called as a function. In Safari or PhantomJs it fails with TypeError: Attempted to wrap object property WebSocket as function

What am I doing wrong?

Loading dynamic url using ajax .load?

How do I make a ajax call that will work with multiple urls?

I used jQuery ajax .load but the problem is the nextLink variable will not be updated since it is already loaded in the js file.

var url = "http://ift.tt/1EZWtsU"
var pageNum = 1;
var nextLink =url+pageNum;

 $('.content-'+ pageNum).load(nextLink + ' .each-block',
    function() {
        pageNum++;
    }
);

Load ajax data while page scroll is being done in Django python

I'm trying to load data from database table upon page scroll down using Ajax in DJango 1.7 and Python27, it loads everything during initial load itself.. Please help me to fix this issue.

Views.py :

def table_row(request, start=0, count=35): #set count here for how many ticket to load each call. Set it so it loads slightly more than enough to fill a page. 
if request.method == 'POST':
     filter =  request.POST.get('category', False)
if filter:
     tickets = Ticket.objects.filter(category=filter)
else:
     tickets = Ticket.objects.all()
start = int(start)
return render_to_response('table-view.html',
     {
             'tickets':tickets[start:start+count], #slices the index of tickets to return
     }, RequestContext(request))

table-view.html :

<script type="text/javascript">
var processing;
function loadTickets(){
 //the ajax call to load more tickets into the table
 var ticket_count= $('tr.ticket').length; //grabs the number of data results returned
 $.ajax({
      type:'post',
      url:'{% url 'app.views.table_row' %}'+ticket_count+'/'+,
      data:{
           'csrfmiddlewaretoken':getCookie('csrftoken'), //This is the ajax csrf protection function 
      },
      success:function(data){
           $('#text-loading').toggleClass('hidden',true); //hides the loading animation when ajax call returns tickets
           $('#table-body').append(data); //adds data to the end of the table
           processing = false; // the processing variable prevents multiple ajax calls when scrolling
      }
 });

}

$(document).ready(function(){
loadTickets(); //initial ticket load
 $('#main-window').scroll(function(e){
      if (processing){
          return false;
      }
      if ($('#content-window').scrollTop() >= ($('#full-table').height() -$(#'content-window').height())){
          processing = true; //prevent multiple scrolls once first is hit
          $('#text-loading').toggleClass('hidden', false); //show the loading animation
          loadTickets();
      } 
 });

});

In the same file, I'm populating the data using below :

<td>{{ ticket.id }}</td>
<td>{{ ticket.title }}</td>
</tr>
{% endfor %}
<!--The loading animation. Appears on first page load and every time the   scrolling reaches the bottom -->
 <div id='text-loading'> We are loading more tickets

I'm suspecting $('tr.ticket').length in ajax function which I'm not sure about.. what it is.. may be I need to find someway to use django convention in assigning number of data results? please help me on this.. Thanks

Documentation on Angular Material $mdDialog.finally?

From the documentation, dialog boxes in Angular Material have a signature like so:

function showAlert() {
  alert = $mdDialog.alert()
    .title('Attention, ' + $scope.userName)
    .content('This is an example of how easy dialogs can be!')
    .ok('Close');
  $mdDialog
      .show( alert )
      .finally(function() {
        alert = undefined;
      });
}

I can't seem to find any documentation on .finally. It appears to be a callback function from what I can gather, though the documentation is oddly lacking any info.

Should I assume it is a normal callback function—and why is the documentation on it lacking—is this simply such standard directive syntax that this is assumed to be the way to deal with callbacks, like .then?

Thanks for any information.

React: Rendering a list in reverse order

I'm building an app with React and Reflux, and I am trying to render a list of items in a specific order.

The items are custom Post components that are rendered in reverse chronological order, so the newest post is at the top of the list.

I am using Khan Academy's TimeoutTransitionGroup to have the list items fade in and out.

The problem I'm seeing is that when I add a new post and the component gets the updated list via new props, the transition happens on the last element in the list rather than the first. I would like to have it so that the first element fades in, since that's the position of the new item that was added.


Post 2 <- This post was newly added


Post 1 <- This post fades in


Is there a way to specify the same order of items, but render them in the reverse order, or something similar?

This is my component's render function:

    if (!(this.props.posts && this.props.ordering)) return false;
    var posts = this.props.ordering.map(function(postId, index) {
        return <Post key={index} post={this.props.posts[postId]}/>;
    }, this);
    return (
        <div className="post-collection">
            <TimeoutTransitionGroup 
                enterTimeout={500}
                leaveTimeout={500}  
                transitionName="postTransition">
                {posts}
            </TimeoutTransitionGroup>
        </div>
    );

This is the CSS transition:

.postTransition-enter {
    opacity: 0;
    transition: opacity .25s ease-in;
}

.postTransition-enter.postTransition-enter-active {
    opacity: 1;
}

.postTransition-leave {
    opacity: 1;
    transition: opacity .25s ease-in;
}

.postTransition-leave.postTransition-leave-active {
    opacity: 0;
}

Any help will be much appreciated!

JQuery Mobile and Scala.js: How to call functions like "navbar()" or "toolbar()"?

In JQuery mobile, to make persistent headers, footers and nabbers work as expected, you have to do something like this:

$(function() {
    $( "[data-role='navbar']" ).navbar();
    $( "[data-role='header'], [data-role='footer']" ).toolbar();
});

What is the equivalent in Scala.js?

Providing Lapsed Time on "Social Network" Post

jsFiddle.

I have created a little javascript snippet that can take two inputs and make a sort of "post" using those. In those posts, it says something like:

Hi!

Posted by Random Person _ minutes ago.

but without the underscore, it should say the lapsed time between now and the time posted. I am having difficulty thinking of how to do this, but this is what I am currently using:

$('#b').click(function () {
    var v = $('#type').val();
    var u = $('#input').val();
    if (v !== "" && u !== "") {
        var time = new Date();
        var currentime = Date.now();
        var x = currentime - time;
        $("ul").prepend("<li>" + v + "<br />Posted by " + u + " " + x + " minutes ago  </li>");
        $('#type, #input').css('border', '');
    } else if (v == "" && u == "") {
        $('#type, #input').css('border', '1px solid red');
    } else if (v == "") {
        $('#type').css('border', '1px solid red');
        $('#input').css('border', '');
    } else {
        $('#input').css('border', '1px solid red');
        $('#type').css('border', '');
    }
});
#type, #input {
    border-radius: 10px;
    background: #dadae3;
    color: #59ACFF;
    border: 1px solid #dadae3;
}
#type {
    border-bottom-right-radius: 0;
}
#type:hover, #input:hover {
    background: #c4c4cc;
    color: #488CCF;
    border: 1px solid #c4c4cc;
}
#type:hover::-webkit-input-placeholder {
    color: #59ACFF
}
#input:hover::-webkit-input-placeholder {
    color: #59ACFF
}
#type:focus, #input:focus {
    border: 1px solid #59ACFF;
    outline: 0;
}
button {
    height: 30px;
    background: #dadae3;
    border-radius: 10px;
    border: 1px solid #dadae3;
    color: #59ACFF;
    cursor: pointer;
}
button:hover {
    background: #c4c4cc;
    color: #488CCF;
    border: 1px solid #c4c4cc;
}
button:focus {
    outline: 0;
}
<script src="http://ift.tt/Zv5K7g"></script>
<link href="http://ift.tt/1FHelXo" rel="stylesheet"/>
<link href="http://ift.tt/18QXBAt" rel="stylesheet"/>
<br />
<textarea id='type'></textarea>
<br />
<br />
<input id='input'>
<br />
<br />
<button id='b'><span class='fa fa-plus-square-o fa-2x'></span>

</button>
<ul id='ul'></ul>

I realize that this is wrong, but I cannot think of other ways to do this.

Thank you. :)

Custom Angular directive broadcasting an event but not to nested children?

I have created an accordian directive in Angular which can be nested, so an accordian can have child accordians inside them.

I want to broadast an event when the accordian opens and closes so that other directives can listen for it (e.g. a menu inside an accordian panel might reveal itself when the accordian it's inside is opened).

The thing is that if there is a nested inner accordian inside the outer one I don't want the event to be broadcast to the inner accordian's child elements because the inner accordian hasn't broadcast an open/close event.

Just in case that makes no sense, to put it another way an element inside a nested accordian should be able to listen to an open/close event broadcast by the accordian it is in, not the one further up the DOM tree.

Hopefully there is a simple solution to this.

Is it possible to add new data/text value that is not in the data in Google Chart?

How can I add some text or values in my graphic that isn't in my data array, like in d3js? Something like:

.append('text').text(...

Is there a way to get full 2D mouse precision with JavaScript

High performance 2D Mice these days have 1000Hz sampling rate and 10000+ DPI. Inferring mouse input by checking what pixel the pointer is on isn't receiving the maximum precision of these 2D Mice. Is there a way that JavaScript can tap into the full precision?

While it wouldn't be practical for JavaScript itself to collect all 1000 samples every second, the browser could collect them all. Then when JavaScript queries, say every 16ms, the browser could give it the average of the last 16 samples. Like GamePad API it could give axis data directly without having to infer.

Why? WebGL games and simulations could really take advantage of it.

public ActionResult UpdateBDDNBR(int? id)
{
    BillingDropDownNBReason billingDropDownNbReason = db.BillingDropDownNBReasons.Find(id);

    ViewBag.ListKey = new SelectList
        (db.BillingDropDownNBReasons.Where(x => x.Active == true),
        "ListKey", "ListValue");

    BillingDropDownNBReasonDataTablesViewModel billingDropDownNbReasonBDDNBRvm =
                new BillingDropDownNBReasonDataTablesViewModel();

    return View(billingDropDownNbReasonBDDNBRvm);
}


public ActionResult SecondUpdateBDDNBR(int? ListKeyid)
{
    if (ListKeyid == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    BillingDropDownNBReason billingDropDownNbReason = db.BillingDropDownNBReasons.Find(ListKeyid);
    BillingDropDownNBReasonDataTablesViewModel billingDropDownNbReasonBDDNBRvm = 
                new BillingDropDownNBReasonDataTablesViewModel();

    billingDropDownNbReasonBDDNBRvm.ListKey = billingDropDownNbReason.Listkey;
    billingDropDownNbReasonBDDNBRvm.ListValue = billingDropDownNbReason.ListValue;
    billingDropDownNbReasonBDDNBRvm.Description = billingDropDownNbReason.Description;
    billingDropDownNbReasonBDDNBRvm.Active = (bool) billingDropDownNbReason.Active;
    billingDropDownNbReasonBDDNBRvm.StartDate = billingDropDownNbReason.StartDate;
    billingDropDownNbReasonBDDNBRvm.EndDate = billingDropDownNbReason.EndDate;

    if (billingDropDownNbReasonBDDNBRvm == null)
    {
        return HttpNotFound();
    }
    return View(billingDropDownNbReasonBDDNBRvm);
}

I am receiving the following error:

System.Int32' but must be of type 'IEnumerable'

newcomber to MVC.

I have a table looks Like:

ListKey, int, NonNull
ListValue, int, NonNull
Desc, String, Null
Active, Bool, Null
StartDate, DateTime
EndDate, DateTime

On button click i hit action UpdateBDDNBR() but I have no ListKey Id yet. So I send View bag back to view. Loads fine I use .js to hit the next action SecondUpdateBDDNBR() error occurs at this point. I am trying to return the values associated with the ListKet ID to a set of bound @html Helpers for update and eventually also a create area. Why do I get the error and how to write code with proper IEnumerable.

$(document).ready(function () {
    $("#ListKey").change(function () {
        alert($(this).val());
        document.location.href = '/IOTDBBillingAdmin/SecondUpdateBDDNBR?ListKeyid=' + $(this).val();
    });
});

@Html.DropDownList("ListKey", Model.ListItems, ("--Select Reason--"), new { @class = "form-control", @id = "ListKey"})

Model

[Key]
public int? ListKey { get; set; }

[Required(ErrorMessage = "List Value is Required")]
[StringLength(250, ErrorMessage = "250 Charactors Max")]
public string ListValue { get; set; }

public IEnumerable<SelectListItem> ListItems { get; set; }

public int? ListKeyid { get; set; }

[Required(ErrorMessage = "Description is Required")]
[StringLength(500, ErrorMessage = "500 Charactors Max")]
public string Description { get; set; }

[Bindable(true)]
[SettingsBindableAttribute(true)]
public bool Active { get; set; }

[DataType(DataType.DateTime)]
public Nullable<System.DateTime> StartDate { get; set; }

[DataType(DataType.DateTime)]
public Nullable<System.DateTime> EndDate { get; set; }

public int RadioGroup { get; set; }

Using setAttribute on a selected option

I am new to Javascript and I cannot figure out how to use setAttribute on a selected option.

I have a select element in my html with id = employee (adding options using javascript)

<select name="employee" id="employee"></select>

Now, using javascript (or jquery) I am trying to add a "dept" attribute to the selected option dynamically.

However, below code doesn't work. What I am doing wrong here?

var sel = document.getElementById("employee");
var selected = sel.options[sel.selectedIndex];
selected.setAttribute("data-dept", Support);

I also tried:

$("#employee option:selected").setAttribute("data-dept", "Support");  

That also didn't work. Can you help me please?

Ideas for a password protected zip file

I need to implement a solution for protecting a .zip file on a web server, using only javascript... Unfortunately, I can't use PHP, ASPX or any other server-side solution. Here's the idea I had, I'd like your feedback or other ideas. The encrypted information is not confidential, but we still need minimal protection.

I had the idea to upload an encrypted version of the file. Then I would use the MD5 result of a password as a key to decrypt the file for the user.

I saw the JSZip framework that could help me. Any thoughts on this idea or other possible solutions?

Higher order javascript functions

can someone explain to me what is going on in the following code. The function is receiving n as parameter, so where is the m coming from? The whole code is confusing.. if someone can explain?

  function greaterThan(n) {
  return function(m) { return m > n; };
  }
   var greaterThan10 = greaterThan(10);
   console.log(greaterThan10(11));
   // → true

How to apply DRY to a series of HTML files that have an almost identical block?

I have a chain of pages that each contain this HTML

  <div class ="container">
    <h3>PROVIDER ENROLLMENT APPLICATION</h3>
  </div>

  <div class ="tabs">
     <a href="tabsA.html"><span>Sec A</span></a>
     <a href="tabsB.html"><span>Sec B</span></a>
     <a href="tabsC.html"><span>Sec C</span></a>
     <a href="tabsD.html"><span>Sec D</span></a>
     <a href="tabsE.html"><span>Sec E</span></a>
     <a href="tabsF.html"><span class="active">Sec F</span></a>
     <a href="tabsG.html"><span>Sec G</span></a>
     <a href="tabsH.html"><span>Sec H</span></a>
     <a href="tabsI.html"><span>Sec I</span></a>
     <a href="tabsJ.html"><span>Sec J</span></a>
     <a href="tabsK.html"><span>Sec K</span></a>
     <a href="tabsL.html"><span>Sec L</span></a>
     <a href="tabsM.html"><span>Sec M</span></a>
  </div

Excepting each page has only it's own href attribute displayed as "active", this being the page for tab F. Is there a way to have this block of code used only once activating the selected pages href attributes when selected?

Detect if a key should be treated as a style or attribute

I have the following function :

var applyStyling = function (element, object) {
    return _.each(object, function (value, key) {
       // determine whether the key should be treated as an attribute or style 
         if(style)
            element.style.key = value
         element.setAttribute(key, value)
    })
}

An example use would be something like

applyStyling('some dom element', {'id' : 'someID', 'zIndex' : 10})

How can I detect if the key should be treated as a style or attribute? I could only find how to check if attribute/style has been set on an element.

AngularJs, how to call function in service?

I want to AngularJS Change Path Without Reloading, my user case is to change URL that contain the some id, so user can share/send this url to friends. I looked AngularJS UI Router - change url without reloading state

in core.js:

'use strict';
angular.module('App', ['ngRoute'])
  .service('$locationEx', ['$location', '$route', '$rootScope',
    function($location, $route, $rootScope) {
      $location.skipReload = function() {
        var lastRoute = $route.current;
        var un = $rootScope.$on('$locationChangeSuccess', function() {
          $route.current = lastRoute;
          un();
        });
        return $location;
      };
      return $location;
    }
  ]);

In controller:

angular.module('App')
  .controller('DetailController', ['$scope', '$locationEx',
      function($scope, $locationEx) {
        $scope.changeURL = function() {
          console.log("IN changeURL");
          $locationEx.skipReload().path("sdfasdfasdfsadf").replace();
        };

If invoke changeURL, it will occur error:TypeError: $locationEx.skipReload is not a function

Can somebody help me? Thanks!

ScrollTop stops .animate halfway thru animation on IOS

I want the scrollup function to execute after the animation completes. I keep getting random occurrences of the mobileNavclick function stopping almost imediatly after its fired.

This works fine everywhere expect on IOS mobile device

//Click Event for Mobile Nav

$("#navContainer ul li a").on('click',function () {
    mobileNavClick();
    checkSize();
    //scrollUp();
});
$("#menu").on('click',function (){
    mobileNavClick();
    checkSize();
});

//Mobile Nav Function

function mobileNavClick() {  
        var mobileMatch = window.matchMedia('(max-width: 600px)');
        var nav = $('#navContainer');
        var navFoot = $('#navFooter');
        var navLeftCSS = nav.css('left');
        if (mobileMatch.matches) {

            animateNav();
         }
         else {
            animateNavRight();
         }

         function animateNav() {
             var navWindowWidth = '-' + $(window).width();
             if ($('#navContainer').css('left') == '0px') {
             nav.animate ({left: navWindowWidth});
             navFoot.animate ({left: navWindowWidth});
             }
         }
         function animateNavRight() {
             var navWindowWidth = $(window).width();
             if ($('#navContainer').css('left') == navWindowWidth) {
             nav.animate ({right: navWindowWidth});
             navFoot.animate ({right: navWindowWidth});
             }  
         }   
}

//Return Scroll to 0px

function scrollUp() {
    var wrapperScrollPosition = $('#navContainer').scrollTop();
    var mobileMatch = window.matchMedia('(max-width: 600px)');
    $('#wrapper').scrollTop(wrapperScrollPosition);
        //If on mobile device body scrolls to 0
        if (mobileMatch.matches) {
            $('body').scrollTop('0');
        }
}

Web Audio synthesis: how to handle changing the filter cutoff during the attack or release phase?

I'm building an emulation of the Roland Juno-106 synthesizer using WebAudio.

I'm hung up on how to handle altering some parameters while the envelope is in progress.

I have the amp envelope modeled to my satisfaction. I use timeouts to keep track of which stage of the envelope I'm in and respond appropriately. That code is found here.

And I think I'm also good with updating the filter if the envelope values are changed during the attack or release phase.

But I'm hung up on how to deal with updating the filter if the cutoff frequency or envelope modulation amount are changed during the attack or release while the filter is simultaneously being modulated by the envelope. That code is located around here. The current implementation doesn't respond the way an analog synth would, but I can't quite figure out how to calculate it.

On a real synth the filter changes immediately as determined by the frequency cutoff, envelope modulation amount, and current stage in the envelope, but the ramp up or down also continues smoothly.

How would I model this behavior?

Removing extra spaces in Google Charts

chart

You can notice that there are many unwanted space (in the left,top and bottom too) in the chart. How to clear them ?

var options = {
                     'width':500,
                     'height':400

          };

Change CSS property on click on buttons?

Hy, Please can any one help me to do this task. i really need it so much.

i want to change the class style of the button (witch is a link) by clicking on it. The buttons are contained on a dynamic child div witch will change every time. the name of the dynamic child div will stay the same every time.

Note: Only one single child div will displayed in the parent div.

This is the style code:

.btn_child              {display:block;  margin:-1px; border:1px solid; background-color:#428bca; border-color:#357ebd; text-align:left; padding-left:15px;  line-height:30px; }
.btn_child:hover        {background-color:#3276b1; border-color:#285e8e; }
.btn_child_selected     {background-color:#3276b1; border-color:#285e8e; }

This is the html code:

<div id="parent" class="parent_class"> 
<!--this is a dynamic content and the ID will change. only the name will still the same-->
<div id="dynamic_child1" name="child">
<a class="btn_child" target="_blank" href="" > link1        </a>
<a class="btn_child" target="_blank" href="" > link2        </a>
<a class="btn_child" target="_blank" href="" > link3        </a>
</div>
</div>

IMPORTANT: By clicking on the next button, the old one will return to default style and the new one style will be changed.

This is a link. it may explain more: http://ift.tt/1GJ8nCd

Adding Browser History and Navigation To JavaScript DOM Page Change Function

I am using JavaScript to change the pages of my website, but I am running into the issue where I can't use browser navigation to go back or forwards through the history once I have changed pages.

I have tried adding a /#pagename to the URL for each page, and a few other things, but I can't seem to find something that works. I need to be able to make sure that the browser is saving the history of the page changes I make, so it can navigate those pages with the forward and back buttons.

// Change Page Function

function ChangeContent (page) {

var pages={"homepage":{title: "homepage"},"servicespage":{title: "servicespage"}};


//Show home page
for(var homepage in pages) {

    if(page!==homepage) {

        document.getElementById(homepage).style.display='none';
    }

    else {

        document.getElementById(homepage).style.display='block';
        window.scrollTo(0,0);
    }
}

//Show services page
for(var servicespage in pages) {

    if(page!==servicespage) {

        document.getElementById(servicespage).style.display='none';
    }

    else {

        document.getElementById(servicespage).style.display='block';
        window.scrollTo(0,0);
    }
}
}

How can I animate the drawing of text on a web page?

I want to have a web page which has one centered word. I want this word to be drawn with an animation, such that the page "writes" the word out the same way that we would, i.e. it starts at one point and draws lines and curves over time such that the end result is a glyph. I do not care if this is done with <canvas> or the DOM, and I don't care whether it's done with JavaScript or CSS. The absence of JQuery would be nice, but not required.

How can I do this? I've searched exhaustively with no luck.

jQuery add $(this) to callback

How can I add $(this) to the following code in the callback? I don't have access to $(this) in the callback function if i simply try adding it.

$('.example').myPlugin({
    option1: hello, 
    option2: world,
    callback: function () {
      // use $(this)
    }
 });

Edit: How can I add for example var $this = $(this) inside $('.example').myPlugin({... }) before the callback?

Part of plugin with callback:

var base = this;

// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;

base.pluginName = function () {
...
// Callback
if (typeof base.options.callback === 'function') {
  base.options.callback.call(el);
}
...
}

Communicate between JavaScript webpage (in browser) and local (client-side) Python-script

I'm trying to get a webpage to receive signals from a MIDI keyboard.

WebMIDI is some way off, so I'm looking at other solutions.

In the past I've used a Python script to convert MIDI signals into UDP packets (which I've then picked up in Unity3D).

This was my Python script:

#!/usr/bin/python

# http://ift.tt/1hASrLP
import rtmidi_python as rtmidi

import time

import socket

def callback( data, time_stamp ):
    event, note, vel = data

    if event == 144: # note on/off
        endpoint = ( "127.0.0.1", 6500 )

        MESSAGE = "%d, %f" % ( note, float(vel) / 127.0 )

        print MESSAGE

        udp_socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )

        udp_socket.sendto( 
            MESSAGE, 
            endpoint
            )

def main( ):
    midi_in = rtmidi.MidiIn( )

    midi_in.callback = callback

    midi_in.open_port( 0 )

    # do something else here (but don't quit)
    while True: 
        time.sleep( 0.001 )

if __name__ == '__main__': 
    main()

It appears to be impossible to write JavaScript code that listens for UDP signals.

The only relevant questions I can find are:

Socket communication between Android app and web browser

Communication between a desktop app and a browser

It looks as though I must crank up a localhost server, but (1) how to integrate my Python script, and (2) how to write JavaScript that will pick up the signals.

I only require unidirectional communication.

Dynamically adding an attribute Directive to a transclude Directive in AngularJS

I'm attempting to dynamically add an attribute Directive to a transclude directive.

For example, the template would start off as follows:

<div class="container">
  <div ng-transclude></div>
</div>

After an event takes place (eg. a click), it would then have an attribute Directive added, such as:

<div class="container" some-directive>
  <div ng-transclude></div>
</div>

I'm using the following JavaScript to do this:

div = angular.element("#demoParentDirective .container").clone();
div.attr('some-directive','');
div = $compile(div)($scope);
angular.element("#demoParentDirective .container").replaceWith(div);

However, this results in:

Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div ng-transclude="">

I've created a stripped down demo of what I'm trying to do in Plunker to show how I'm doing it:

http://ift.tt/1I5SSZi

Any help would be appreciated. Thanks.

If I trigger an HTML5 element via a button, to make it play, I have the problem that, when I hit the button again, the sample will not be played again (since it's already playing).

If I use: n.pause() n.currentTime = 0 n.play()

it will be cut of which is also not very nice.

Is there an easy way (I'm kind of a beginner) to create a new audio element and destroy it after it has ended, or even another possibility I might can't think of atm?

get dynamic property defined in prototype during JSON.stringify

I've defined an enumerable property in the prototype object and would like it to appear when I convert a prototyped object to JSON.

My first idea was to set it in toJSON but because I don't really want to keep it in the object afterwards I'll have to more or less clone the whole object in the function and set the necessary property.

Redefining the property in the target object and just proxying with the context of the current object doesn't seem to be an option as well, since I can't really use apply or call when getting dynamic properties.

Working solutions I could come up with so far seem to require quite an amount of code and aren't flexible and concise enough, so I'm wondering if there are any best practices of solving this task.

Here is an example which could seem a bit synthetic but still, I believe, conveys the idea:

function ProjectFolder() {
  this.files = [];
  Object.defineProperty(this, 'size', {enumerable: true, get: function() {
    return this.files.length;
  }});
}

function GithubProjectFolder() {
  this.files = ['.gitignore', 'README.md'];
}
GithubProjectFolder.prototype = new ProjectFolder();

var project1 = new ProjectFolder();
JSON.stringify(project1);
// output:  {"files":[],"size":0}
// size is present

var project = new GithubProjectFolder();    
JSON.stringify(project);
// output:  {"files":[".gitignore","README.md"]}
// size is absent

Django Ajax not entrering in the function

When i press the link the program should go to the ajax function to update the database without reloading the page. the problem is when the link is pressed doesnt enter in the JS function (doesnt show the alert)

 <a href="#" onclick="xpto2()" >Remind later</a>
<script>    
function xpto2(){
     alert("hello");
     $.ajax({
        url: 'update-notify-status-noshow',
        data: { postdata1: {{ n.id }} }, 
        dataType: 'html', 
        type: 'get', )
        success: function(output) {
        alert(output); 
        }
    });
   </script>

rendering form in partial with ajax, form does not function (ROR)

I'm fairly new to using ajax so I'm really hoping there is any easy fix to this. Currently what happens is I click 'New Schedule Entry' and a form gets appended to the table (see _form.html.erb). The issue is that the form does not work. Submit doesn't work, the date_picker/time_picker doesn't show up, the HTML5 validation doesn't pop up. I feel like there is a simple solution to this that I am missing.

Relevant gems

  • gem 'turbolinks'
  • gem 'jquery-turbolinks' <--added because I was hoping this would fix the issue
  • gem 'jquery-rails'

new.js.erb

$('#schedule-table-tbody').prepend("<%= j(render partial: 'form') %>");

relevant part of index.html.erb

<%= link_to 'New Schedule Entry', new_schedule_path, remote: true %>
<div class="table-responsive">
  <table id="schedule-table" class="table table-hover table-striped table-condensed">
    <thead>
    <tr>
      <th class="col-xs-2">Date</th>
      <th class="col-xs-2">Start Time</th>
      <th class="col-xs-2">End Time</th>
      <th class="col-xs-6">Details</th>
    </tr>
    </thead>
    <tbody id="schedule-table-tbody">

schedules_controller.rb

class SchedulesController < ApplicationController
  respond_to :html, :js

  def index
    @schedules = Schedule.page(params[:page]).per(20)
  end

  def show
    @schedule = Schedule.find(params[:id])
  end

  def new
    @schedule = Schedule.new
  end

  def create
    @schedule = Schedule.new(schedule_params)
    if (@schedule.save)
      flash['main|success'] = 'Successfully created schedule entry.'
      redirect_to schedules_path
    else
      render 'index'
    end
  end

  private

  def schedule_params
    params.require(:schedule).permit(:name, :date, :start_time, :end_time)
  end
end

_form.html.erb

<tr>
  <%= simple_form_for @schedule do |f| %>
      <td>
        <%= f.input_field :date, :as => :date_picker, label: false %>
      </td>
      <td>
        <%= f.input_field :start_time, :as => :time_picker, label: false %>
      </td>
      <td>
        <%= f.input_field :end_time, :as => :time_picker, label: false %>
      </td>
      <td>
        <%= f.input_field :name, label: false %>
      </td>
      <td>
        <%= f.button :button, class: "btn btn-primary" do %>
            <span class='glyphicon glyphicon-ok'></span> Save
        <% end %>
      </td>
  <% end %>
</tr>

How to create a Javascript Table Lens

I'm needing to create a view for data in Table Lens format, my idea is to use the d3js.org library because I need it to be done in javascript. I wonder if someone has already developed something and can help.

This link shows a Table Lens example: http://ift.tt/1K4qrd0 (in this paper http://ift.tt/1I5Pfm6)

How do one scrollbar with CSS,Javascript and HTML?

I am trying to create an scrollbar like from radio station with the numbers and with the scrollbar that you can move for the sides,and the canvas go together with the scrollbar as he moves.

But i don't have some much idea how to do.True is i don't know from where start to create,so guys,if you help me,i will thanks you guys. If someone can post some codes for help me,i will appreciate. And sorry for the bad english.