mardi 4 août 2015

How to write a good Caps Lock detection solution in JavaScript?

EDIT: Figured it out on my own

For whom it may concern, a solution for caps detection in vanilla JavaScript. The problem with most of the solutions floating around on the internet is they only show/hide an alert/popup when the user starts typing in the input field. This is not optimal because the "Caps Lock is on" notification is still visible after the user has turned Caps Lock off, and remains so until they resume typing. This is long and unwieldy, and I still don't quite understand it myself. But I recommend it all the same.

function capsDetect() {
  var body = document.getElementsByTagName('body')[0];
  var isShiftPressed = false;
  var isCapsOn = null;
  var capsWarning = document.getElementById('caps-lock-warning');
  body.addEventListener('keydown', function(e) {
  var keyCode = e.keyCode ? e.keyCode : e.which;
  if (keyCode = 16){
   isShiftPressed = true;
}
});
body.addEventListener('keyup', function(e) {
 var keyCode = e.keyCode ? e.keyCode : e.which;
 if(keyCode == 16) {
   isShiftPressed = false;
}
 if(keyCode == 20) {
  if(isCapsOn == true) {
   isCapsOn = false;
   capsWarning.style.visibility = 'hidden';
} else if (isCapsOn == false) {
  isCapsOn = true;
  capsWarning.style.visibility = 'visible';
}
}
});
body.addEventListener('keypress', function(e) {
  var keyCode = e.keyCode ? e.keyCode : e.which;
  if(keyCode >= 65 && keyCode <= 90 && !isShiftPressed) {
    isCapsOn = true;
    capsWarning.style.visibility = 'visible';
} else {
    capsWarning.style.visibility = 'hidden';
}
});
}
shiftCaps();



via Chebli Mohamed

Modifying values of existing layer in OpenLayers 3

I am adding a marker on the map using ol3 by calling the following function

function addmarker(lat, long, flag) {

            iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.transform([+long, +lat], 'EPSG:4326', 'EPSG:3857')),
                name: 'NULL'
            });

            iconStyle = new ol.style.Style({

                fill: new ol.style.Fill({
                    color: '#008000'
                }),
                stroke: new ol.style.Stroke({
                    color: '#008000',
                    width: 3
                }),
                image: new ol.style.Circle({
                    radius: 6,
                    fill: new ol.style.Fill({
                        color: '#008000'
                    })
                })

            });

            iconFeature.setStyle(iconStyle);

            vectorSource[flag] = new ol.source.Vector({
                features: [iconFeature]
            });

            vectorLayer[flag] = new ol.layer.Vector({
                source: vectorSource[flag]
            });

            map.addLayer(vectorLayer[flag]);

        }

And to change the marker position, I am removing the layer and adding a new layer again

 function changemarker(lat, long, flag) {

             vectorSource[flag].clear();

            map.removeLayer(vectorLayer[flag]);

            addmarker(lat, long, flag);

        }

I am facing performance issues as I am changing the marker that is calling the changemarker method every 500 milliseconds. Can a layer be modified without removing it or is there a better approach that can be followed.

Please help.



via Chebli Mohamed

How to pass unknown children of Polymer component into component's DOM

I want to create a component which I can pass other components to and create DOM structures.

<test-component>
    <img/>
    <div/>
    <foo/>
</test-component>

In trying to get that working:

<dom-module name="test-component">
    <template>
        <h1>Title</h1>
        <ul>
            <template is="dom-repeat" items="{{nodes}}">
                <li>element:</li>
                <li>{{item}}</li>
            </template>
        </ul>

        <content id="contentelement"></content>
    </template>
</dom-module>

<script type="text/javascript">
    Polymer({
        is: "test-component",
        ready: function() {
            this.nodes = (function(that) {
                var nodeList = that.$.contentelement._distributedNodes,
                    nodeMap = [];
                for(var i = 0; i < nodeList.length; i++) {
                    if(nodeList[i].nodeType === 1) {
                        nodeMap.push(nodeList[i].outerHTML);
                    }
                }
                return nodeMap
            }(this));
        }
    });
</script>

I used a function to build this.nodes because this.nodes = this.$.contentelement.getDistributedNodes(); returns null, not sure why.

I know you can't just drop an element's outerHTML into the page but can a random set of HTML/components be passed into a template like this?



via Chebli Mohamed

Javscript is not hiding div & input element

I've got a div & input that needs to be hidden on the page load. It is a other specify, so if one of the other fields is selected "other" then the div should show. But the input element is not hiding on page load. As soon as I take out the input element from the div it hides, but as soon as I put the input element back it does not hide, what am I doing wrong?

<head>
<script>
function hideother() {
    document.getElementById("otherdiv").style.visibility = "hidden";
    document.getElementById("others").style.visibility = "hidden";
}
</script>
</head>

<body onLoad="hideother()">
    <!-- 2A OTHER SPECIFY -->
    <div class="otherdiv">
    <label for="otherspecify">Please specify other:</label>
    <label id="error-2" style="text-transform:capitalize; color:red">&nbsp;</label>
    <br>
<input maxlength="30" name="others" id="others" type="text" class="form-control" placeholder="Other Specify" autocomplete="off" style="width:300px" />
    </div>
</body>



via Chebli Mohamed

AngularJS service parent separate reference

I'm using an AngularJS service to store data from multiple pages, to be submitted together. See the code below.

In my Chrome console if I observe checkoutData.shipping, I get back the correct object with data. If I observe checkoutData.data I get an empty object, where it's shipping property is blank.

These should be pointing at the same object, right? Why would it work with .shipping and not using .data? The reason it's set up this way is that the shipping page only cares about .shipping, while the final page needs everything in .data.

(function() {
    angular.module('app').factory('checkoutData', [function() {
        var data = {
            carrierId: null,
            serviceTypeId: null,
            shippingCost: {},
            billingOptionId: null,
            shipping: {},
            billing: {},
            cart: null
        };
        var inputForms = {};
        var options = {
            shippingOptions: null,
            billingOptions: null,
            selectedShippingOption: null
        };
        var staticContent = {
            billing: {},
            cart: {},
            shipping: {}
        };
        return {
            data: data,
            shipping: data.shipping,
            inputForms: inputForms,
            cart: data.cart,
            billingOptionId: data.billingOptionId,
            billingOptions: options.billingOptions,
            carrierId: data.carrierId,
            serviceTypeId: data.serviceTypeId,
            shippingOptions: options.shippingOptions,
            staticContentBilling: staticContent.billing,
            staticContentCart: staticContent.cart,
            staticContentShipping: staticContent.shipping,
            selectedShippingOption: options.selectedShippingOption,
            setValid: function(formName, valid) {
                inputForms[formName].valid = valid;
            },
            initializeForm: function(formName) {
                inputForms[formName] = {};
            },
            formInitialized: function (formName) {
                return inputForms[formName] != null;
            }
        }
    }]);
})();



via Chebli Mohamed

i have two fields.today sale and yesterday sale.i want to change the image when sale valuew change how can i change that?

I found this script: http://ift.tt/1gHeQZi Unfortunately I can't login. I had a look at the code but can't figure out what is wrong. When starting this script the user has to type ...



via Chebli Mohamed

XPathEvaluator in Firefox addon

I am attempting to follow this article to evaluate an XPath expression. My code is copy/pasted from the article:

// Evaluate an XPath expression aExpression against a given DOM node
// or Document object (aNode), returning the results as an array
// thanks wanderingstan at morethanwarm dot mail dot com for the
// initial work.
function evaluateXPath(aNode, aExpr) {
  var xpe = new XPathEvaluator();
  var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ?
    aNode.documentElement : aNode.ownerDocument.documentElement);
  var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
  var found = [];
  var res;
  while (res = result.iterateNext())
    found.push(res);
  return found;
}

However, I'm getting this error:

Message: ReferenceError: XPathEvaluator is not defined

Is Mozilla's article out of date, perhaps? Is there a more up-to-date article available on parsing XML in an SDK add-on?

Edit. When I tried it this way:

var {Cc, Ci} = require("chrome");
var domXPathEvaluator = Cc["@http://ift.tt/1II9uXP"].createInstance(Ci.nsIDOMXPathEvaluator);

I got a long error message:

- message = Component returned failure code: 0x80570019 (NS_ERROR_XPC_CANT_CREATE_WN) [nsIJSCID.createInstance]
- fileName = undefined
- lineNumber = 14
- stack = @undefined:14:undefined|@http://resourcehelloworld-addon/index.js:14:25|run@resourcegre/modules/commonjs/sdk/addon/runner.js:145:19|startup/</<@resourcegre/modules/commonjs/sdk/addon/runner.js:86:7|Handler.prototype.process@resourcegre/modules/Promise-backend.js:920:23|this.PromiseWalker.walkerLoop@resourcegre/modules/Promise-backend.js:799:7|this.PromiseWalker.scheduleWalkerLoop/<@resourcegre/modules/Promise-backend.js:738:39|Promise*this.PromiseWalker.scheduleWalkerLoop@resourcegre/modules/Promise-backend.js:738:7|this.PromiseWalker.schedulePromise@resourcegre/modules/Promise-backend.js:762:7|this.PromiseWalker.completePromise@resourcegre/modules/Promise-backend.js:705:7|handler@resourcegre/modules/commonjs/sdk/addon/window.js:56:3|
- toString = function () /* use strict */ toString



via Chebli Mohamed

Callback not executing in javascript

I wrote a method that is supposed to execute a callback, but the callback isnt being executed:

buildTable('lt', 'viewltDetails', commonTireColumns, function(error) {
if(error) {
    console.log(error);
} else {
    console.log('calculating');
    calculatedPricing();
}
});

The buildTable function works fine, but it's not executing the console.log('calculating') and calculatePricing() commands, although the function isn't throwing any errors.

My calculatePricing function looks like:

calculatedPricing: function() {
    var price = 300;
    return price;
};

Can someone help? Thanks!!



via Chebli Mohamed

how to pass variables though javascript to ajax using jquery-tabledit?

I am currently using the jquery plugin Tabledit and when i use an inline edit as in example 3 it calls my php page. I have no idea how to pass the changes I made in the edit to the new php page so i can change it in the database. it changes when you hit enter. (im guessing on enter it calls the edittask.php)

html here is one section of the table. it changes on hitting enter after you type in new text.

<td class="tabledit-view-mode"> <span class=" tabledit-span ">header text</span>
    <input class="tabledit-input form-control input-sm" type="text" name="description" value=" " style="display: none;" disabled="" />
</td>

javascript

$('#thetable').Tabledit({
    url: 'editTask.php',
    editButton: false,
    deleteButton: false,
    columns: {
        identifier: [0, 'id'],
        editable: [
            [1, 'Header'],
            [2, 'Description']
        ]
    }
});



via Chebli Mohamed

jquery - click on table row to append value in checkboxes

JS

$(document).ready(function() {

  $('.tg tr.data-list-row[name=data-list-row]').click(function() {
    var currentId = $(this).closest('tr').attr('id');
    $.getJSON('<%=request.getContextPath()%>/ws/booking/getpriceinput_by_id/' + currentId, function(data) {
      $("#current_typetarif_id").val(data.id);
      $("#inputName").val(data.libelle);
      $("#inputCode").val(data.code);
      $("#inputTarif").val(data.montantTarifDefaut);
    });
  });

  

});
<div class="table-responsive">
  <table class="table tg" style="table-layout: fixed; width: 745px">
    <colgroup>
      <col style="width: 249px">
        <col style="width: 249px">
          <col style="width: 249px">

    </colgroup>

    <thead>
      <tr>
        <th class="tg-s6z2 bdleft">NOM</th>
        <th class="tg-s6z2">CODE</th>
        <th class="tg-s6z2">PRIX PAR DEFAUT</th>
      </tr>
    </thead>
    <tfoot>
    </tfoot>
    <tbody>
      <tr>
        <td colspan="5">
          <div class="scrollit">
            <table class="table tg" style="table-layout: fixed;">
              <colgroup>
                <col style="width: 220px">
                  <col style="width: 240px">
                    <col style="width: 240px">
              </colgroup>


              <c:forEach items="${type_tarif_list}" var="type_tarif" varStatus="loop">
                <tr class="data-list-row" name="data-list-row" id="${type_tarif.id}" style="cursor: pointer;">
                  <td class="tg-s6z2 bdleft">${type_tarif.libelle}</td>
                  <td class="tg-s6z2">${type_tarif.code}</td>
                  <td class="tg-s6z2">${type_tarif.montantTarifDefaut}</td>
                  <td class="deleterow bdryt" id="${type_tarif.id}" name="del_button">
                    <div class="glyphicon glyphicon-remove" title="Supprimer"></div>
                  </td>
                </tr>
              </c:forEach>
            </table>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>

<form class="form-horizontal" style="margin: 0 auto; width: 150px;" id="scrollit" name="thisForm">
  <c:forEach items="${option_tarif_list}" var="option_tarif" varStatus="loop">
    <div class="checkbox1">
      <label>
        <input type="checkbox" name="tarif_inclue" value="${option_tarif.libelle}" class="checkboxchk" id="option_tarif_chk_${option_tarif.id}">${option_tarif.libelle}
      </label>
    </div>
  </c:forEach>

</form>

JSON value extracted from database

{
  "id": 1,
  "code": "0001",
  "libelle": "TARIF PUBLIC",
  "montantTarifDefaut": 10.00,
  "tarifTypeList": [
    {
      "chambreTypeId": 1,
      "tarifTypeId": 1
    }
  ],
  "tarifTypeOptionList": [
    {
      "typeTarifId": 1,
      "tarifOptionId": 1
    },
    {
      "typeTarifId": 1,
      "tarifOptionId": 2
    },
    {
      "typeTarifId": 1,
      "tarifOptionId": 3
    }
  ]
}

Hi.

This block of code below make a select in the table row to display values into the texts fields.

    $(document).ready(function() {

  $('.tg tr.data-list-row[name=data-list-row]').click(function() {
    var currentId = $(this).closest('tr').attr('id');
    $.getJSON('<%=request.getContextPath()%>/ws/booking/getpriceinput_by_id/' + currentId, function(data) {
      $("#current_typetarif_id").val(data.id);
      $("#inputName").val(data.libelle);
      $("#inputCode").val(data.code);
      $("#inputTarif").val(data.montantTarifDefaut);
    });
  });



});

On clicking on the table row, i need to display the checked values in the checkbox. According to the id selected in the rows, specific values will be checked in the checkboxes. Those values are being extracted from a database through a JSON file. I should extract it using the value (data.tarifOptionId)

I think is should be put it in a loop, so that the id value is incremented when each table row is clicked. The id of the input is #option_tarif_chk_, and it is embeded in a cforeach loop.

I have written something like this below:

            $.each(data, function(i, item) {
                alert(item.tarifTypeOptionList[0].tarifOptionId);
            });

But it is not working. The alert returns Uncaught TypeError: Cannot read property '0' of undefined

Any help will be much appreciated.

Thank you



via Chebli Mohamed

what are the best approach to convert the existing backboneJS app into angularJS app

I am trying to convert existing backbonejs application into angularjs. What is the best approach to convert backbone app into angular app. How should I divide and conquer the codes without breaking the app



via Chebli Mohamed

How to make table cells square for any amount of text in it when table is overflow?

A Simple Problem: When table is wider than screen and if we add a bigger text in any cell or <td>.

It will increase the height for whole row unnecessary extra


Case 1 (no problem) (only table overflow): (http://ift.tt/1gHeQIA)

Case 2 (no problem) (only a cell with more text): (http://ift.tt/1P3HfDX)

Case 3 (PROBLEMATIC) (overflow + a cell with more text): (http://ift.tt/1gHeQIG)


Solution I Think (i tried javascript but fail) : If we somehow just add 1 property to be square shaped to all table cells (in case we add larger text, it will resize but keep square shape), because square shape will make table to take least area possible.

I know some people will help so thanks in advance for help...



via Chebli Mohamed

GUIDrawTexture, image does not resize when I resize the game window

The title probably makes no sense But I did not know how else to explain it... I can better explain here.

I'm making a 3D game and I have the hud set to the bottom left corner and it will resize and adjust when I resize the Window/Pick a different resolution, but the Health/thirst bar stays in one area and does not adjust with it and stay on top of the hud...

In example if The hud is in the Bottom left and when I resize and change the resolution the health thirst bar stay one the left side but they go way up in the middle of the screen Hope that makes sense and stuff like that here is my code thanks in advance :)!

var hudSize : Vector2 = new Vector2(244, 500);
var size : Vector2 = new Vector2(240, 40);
var thirstSize : Vector2 = new Vector2(244,60);

var healthPos : Vector2 = new Vector2(20, 20);
var healthBarDisplay : float = 1;
var healthBarFull : Texture2D;



var hungerPos : Vector2 = new Vector2(20, 60);
var hungerBarDisplay : float = 1;
var hungerBarFull : Texture2D;

var thirstPos : Vector2 = new Vector2(20, 100);
var thirstBarDisplay : float = 1;
var thirstBarFull : Texture2D;

var healthFallRate : int = 150;
var hungerFallRate : int = 150;
var thirstFallRate : int = 100;

var hudPos : Vector2 = new Vector2(0, 0);
var hudDisplay : Texture2D;

var canJump : boolean = false;
var jumpTimer : float = 0.7;


function Start()
{
onMotor = GetComponent(CharacterController);
controller = GetComponent(CharacterController);
}

//OnScreenDrawing Textures
function OnGUI()
{


GUI.DrawTexture(new Rect (0, Screen.height - 125,244,125), hudDisplay);                  


//HealthBar
GUI.BeginGroup(new Rect (healthPos.x, healthPos.y, size.x, size.y));    
GUI.BeginGroup(new Rect (0, 0, size.x * healthBarDisplay, size.y));
GUI.DrawTexture(Rect(0, 0, size.x, size.y), healthBarFull);

GUI.EndGroup();
GUI.EndGroup();

//ThirstBar
GUI.BeginGroup(new Rect (thirstPos.x, thirstPos.y, size.x, size.y));
GUI.BeginGroup(new Rect (0, 0, thirstSize.x * thirstBarDisplay, thirstSize.y));
GUI.DrawTexture(Rect(0, 0, thirstSize.x, thirstSize.y), thirstBarFull);


GUI.EndGroup();
GUI.EndGroup();


}


function Update()
{

if(hungerBarDisplay <= 100)
{
    healthBarDisplay -= Time.deltaTime / healthFallRate * 2;
    thirstBarDisplay -= Time.deltaTime / thirstFallRate * 5;
}



}



via Chebli Mohamed

Referencing data in a geoJSON file

JS novice. This statement appears not to be working:

if (kcdfp_parcel[i].InActive == 0)

The data is a geoJSON file with the variable "kcdfp_parcel".

This is a little of the file:

kcdfp_parcel = [{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "properties": { "MAJOR": "000440", "MINOR": "0018", "PIN": "0004400018", "FarmID": 3101.000000, "LastName": "Codiga", "Acres": 62.940000, "Cooperativ": null, "InActive": 0, "ParcelNumb": "0004400018", "Shape_Leng": 0.024319, "Shape_Area": 0.000030 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -122.254601971999989,

Am I referencing the LastName field properly (e.g. do I need to use kcdfp_parcel.features.InActive)?

Or, is my IF statement wrong?



via Chebli Mohamed

Bootstrap Carousel Loading, Not Scrolling

I'm setting up a Bootstrap Carousel working from a Django-powered image database. I have no errors in the console log, jQuery is loading, etc., so I'm definitely missing something painfully obvious. It does not transition to other slides, and the controls are not working either. I have tried loading the carousel library separately, and nothing seems to work. I'm using jQuery 1.11.0 loaded via CDN from Google.

ETA:

I am loading bootstrap.min.js after jQuery. I normally have some custom JS running, but I've removed that script for testing.

Here's the Django code generating the carousel:

<div id="mycarousel" class="carousel slide" data-interval="7000" data-ride="carousel">
    <ol class="carousel-indicators">
        {% for image in index_carousel %}
            {% if forloop.first %}
                <li data-target='#mycarousel' class='active' data-slide-to='{{ forloop.counter }}'></li>
            {% else %}  
                <li data-target='#mycarousel' data-slide-to='{{ forloop.counter }}'></li>
            {% endif %} 
        {% endfor %}
    </ol>
    <div class="carousel-inner">
        {% for image in index_carousel %}
            {% if forloop.first %}
                <div class="item active">
            {% else %}
                <div class="item">
            {% endif %}
            <img class="img-responsive" src="{{ image.carousel_image.url }}" alt="Carousel Slide - {{ image.alt_text }}">
            </div>
        {% endfor %}
    </div>
    <!-- Controls -->
    <a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
    </a>
    <a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
    </a>
</div> <!-- Carousel -->

Here's the generated HTML:

<div id="mycarousel" class="carousel slide" data-interval="7000" data-ride="carousel">
    <ol class="carousel-indicators">
        <li data-target='#mycarousel' class='active' data-slide-to='1'></li>
        <li data-target='#mycarousel' data-slide-to='2'></li>
        <li data-target='#mycarousel' data-slide-to='3'></li>
    </ol>
    <div class="carousel-inner">
        <div class="item active">
            <img class="img-responsive" src="/media/carousel_images/staff_blogs.png" alt="Carousel Slide - ">
        </div>
        <div class="item">
            <img class="img-responsive" src="/media/carousel_images/aarp-tax-help-slide_ZznUFS2.png" alt="Carousel Slide - ">
        </div>
        <div class="item">
            <img class="img-responsive" src="/media/carousel_images/august_book_sale_new.png" alt="Carousel Slide - ">
        </div>
    </div>
    <!-- Controls -->
    <a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
    </a>
    <a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
    </a>
</div> <!-- Carousel -->

Edit, 13:40UTC:

I removed the "data-ride" and "data-interval" attributes and tried loading the carousel manually with:

<script>
    $(document).ready(function() {
        $('#mycarousel').carousel();
    })
</script>

I placed this at the bottom of the page, after the jQuery and bootstrap.min.js were loaded. Still no console errors, and still no functionality.

EDIT 13:55UTC:

Checked my bootstrap.min.js to make sure it wasn't corrupted and contained the carousel function.



via Chebli Mohamed

Give a specific value to a variable based on url content

I have a site with a core domain with something like this:

www.example.com/de-e
www.example.com/us-e

If I start the navigation to site and go to different pages I have urls like this:

http://ift.tt/1P3HdMx

I want to store give to a variable named vde the value de if the url have the value de-e and us if the url have the value us-e.With JQuery I could possible use the contains() with simple JS how can I make it?



via Chebli Mohamed

Centerize canvas text at all time, even if resized?

I am currently trying to work on this script, which was created by someone else. Yes, I grabbed it, yes I will give credits.

The problem I am having, is trying to center the text even if the window has been resized. When you move the cursor on the text, it explodes randomly. When I resize the window, I need that same text (and those exploded characters) to move. I can easily just put new text in using fillText(), but then I replace the exploded characters.

Obviously I have tried this in my example:

window.onresize = function(event) {
    reload(canvas_id);
}

var reload = function(canvas_id) {
    canvas = document.getElementById(canvas_id);
    context = canvas.getContext("2d");

    canvas.width = window.innerWidth;
}

This resizes the canvas perfectly, but the text won't be centered anymore. To center the text when I place it, I do this:

(window.innerWidth / 2) - (Math.round(bgContext.measureText(keyword).width/2))

bgContext being the canvas.getContext("2d"); obviously.

Here's a JSFiddle showing this issue: http://ift.tt/1gHeNwD



via Chebli Mohamed

Form won't submit when showing certain fields

I am trying to create a drop down menu that allows a user to select which area they would like to login to. Currently, the drop down feature works and hides whichever areas the user is not logging into and shows only the area that they have selected. Using just the form without the dropdown works great and opens a new window while also logging the user in to the system. However, when I add the dropdown menu and surround the form in tags, it allows me to enter the data but does not process the data.

If possible I would also like to have the form open a new tab in the current browser window(not in a completely new window).

-I cannot change the forms at all besides things that won't matter because they have been given to me from an external source.

Here is my code:

$(document).ready(function() {
  toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
  //this will call our toggleFields function every time the selection value of our repository field changes
  $("#member").change(function() {
    toggleFields();
  });

});
//this toggles the visibility of the 3 different forms depending on which repository the user is logging into.
function toggleFields() {
  if ($("#member").val() == 1)
    $("#depo").show();
  else
    $("#depo").hide();
  if ($("#member").val() == 2)
    $("#records").show();
  else
    $("#records").hide();
  if ($("#member").val() == 3)
    $("#reporter").show();
  else
    $("#reporter").hide();
}
<script src="http://ift.tt/1qRgvOJ"></script>

<select id="member" name="member">
  <option value="0">---</option>
  <option value="1">Deposition Repository</option>
  <option value="2">Records Repository</option>
  <option value="3">Reporter Area</option>
</select>

<div id="depo">
  <p>Login to Access your Deposition Repository</p>
  <p>
    <script type="text/javascript" src="http://ift.tt/1P3HeQs"></script>
    <form name="frmrbwebattorney" method="post" action="http://ift.tt/1P3Hdw0">
      User ID:
      <input type="text" name="rbwebuserid" style="width:130px;" value="" maxlength=30>Password:
      <input type="password" name="rbwebpassword" style="width:130px;" value="" maxlength=65 onkeypress="javascript:if(event.keyCode ==13) login(document.frmrbwebattorney,1);">
      <INPUT type="button" value="Log In" style="font-size:11px;" style="width:64px" onclick="javascript:login(document.frmrbwebattorney,1);" id=btnptarbweb name=btnptarbweb>
      <INPUT type="hidden" name="appname" value="">
      <INPUT type="hidden" name="os" value="">
    </form>
  </p>
</div>

<div id="records">
  <p>Login to Access your Records Repository.</p>
  <p>
    <script type="text/javascript" src="http://ift.tt/1gHeNwv"></script>
    <form name="frmrbwebattorney" method="post" action="http://ift.tt/1P3HeQu">
      User ID:
      <input type="text" name="rbwebuserid" style="width:130px;" value="" maxlength=16>Password:
      <input type="password" name="rbwebpassword" style="width:130px;" value="" maxlength=65 onkeypress="javascript:if(event.keyCode ==13) login(document.frmrbwebattorney,1);">
      <INPUT type="button" value="Log In" style="font-size:11px;" style="width:64px" onclick="javascript:login(document.frmrbwebattorney,1);" id=btnptarbweb name=btnptarbweb>
      <INPUT type="hidden" name="appname" value="">
      <INPUT type="hidden" name="os" value="">
    </form>
  </p>
</div>

<div id="reporter">
  <p>Login to the Reporter Area.</p>
  <p>
    <script type="text/javascript" src="http://ift.tt/1P3HeQs"></script>
    <form name="frmrbwebreporter" method="post" action="http://ift.tt/1gHeNwx">
      User ID:
      <input type="text" name="rbwebuserid" style="width:130px;" value="" maxlength=16>Password:
      <input type="password" name="rbwebpassword" style="width:130px;" value="" maxlength=65 onkeypress="javascript:if(event.keyCode ==13) login(document.frmrbwebreporter,1);">
      <INPUT type="button" value="Log In" style="font-size:11px;" style="width:64px" onclick="javascript:login(document.frmrbwebreporter,1);" id=btnptarbweb name=btnptarbweb>
      <INPUT type="hidden" name="appname" value="">
      <INPUT type="hidden" name="os" value="">
    </form>
  </p>
</div>

Any help will be greatly appreciated!



via Chebli Mohamed

JavaScript button on click navigate to another HTML page

I was having some problem with the HTML and JavaScript validation. So basically I got multiple fields and I will perform a validation before moving to another HTML page. Here is the code:

<fieldset>
    Name* <input id="name" type="text" name="name"> </input>
    NRIC/Passport No* <input id="nric" type="text" name="nric" > </input>
    <input id="btnSubmit" type="submit" value="Pay now!" onclick="validate()"/> 
</fieldset>

My Javascript:

function validate(){
var name = document.getElementById('name').value;
var nric = document.getElementById('nric').value;
var submit = document.getElementById('btnSubmit').value;

if(name == null || name == ""){
    alert('Please enter your name. Do not leave it blank before proceed to the next field.');
}
else if(nric == null || nric == ""){
    alert('Please enter your NRIC. Do not leave it blank before proceed to the next field.');
}else{
    window.location.href = '../successful.html';
}
}

I tried to perform a validation before moving to successful.html. The validation works, however, when I tried to navigate to another page, it was telling me the web page is not found. Any ideas how to solve this?

Thanks in advance.



via Chebli Mohamed

Have got some problems with sorting and rendering data with backbone.js

Have got some problems with sorting and rendering data with backbone.js There is sorting by 'title' in comparator. This.model.collection has models after sorting by title, but when rendering starts models views after sorting by order.

    var TodoList = Backbone.Collection.extend({

    model: Todo,

    comparator: function(todo) {
        return todo.get('title');
    }

    });

    var TodoView = Backbone.View.extend({

    tagName:  "li",

    template: _.template($('#item-template').html()),

    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
    });



via Chebli Mohamed

CSS or jQuery hover effect to increase a fixed box and show absolute position larger version

does anyone know how i can make my colour boxes increase in size (in same position, guessing absolute position so it does not effect the other positions of colours) when you hover will show a larger version of the colour when you hover... maybe background image size? dont know.

I have added a image for a test on the red one.

#product_color_select li {
        display: inline-block;
        width: 30px;
        height: 25px;
        text-indent: -999999em;
        cursor: pointer;
}
/* interior colours */
#product_color_select li.eco-weave {
        background-color: #beaaaa;
}
#product_color_select li.aubergine-dream {
        background-color: #382643;
}
#product_color_select li.lime-citrus {
        background-color: #99a366;
}
#product_color_select li.blue-jazz {
        background-color: #435fa1;
}
#product_color_select li.sakura-pink {
        background-color: #bf3253;
}
#product_color_select li.hot-chocolate {
        background-color: #3b2b28;
}
#product_color_select li.tundra-spring {
        background-color: #c5c1d0;
}
#product_color_select li.black-sapphire {
        background-color: #131114;
}
#product_color_select li.luscious-grey {
        background-color: #7a6772;
}
#product_color_select li.wildberry-deluxe {
        background-image: url('http://ift.tt/1gHeNg4');
}
<ul class="fabric-select" id="product_color_select">
    <li class=" eco-weave" data-value="742" title="Eco Weave">Eco Weave</li>
    <li class=" blue-jazz" data-value="749" title="Blue Jazz">Blue Jazz</li>
    <li class=" sakura-pink" data-value="743" title="Sakura Pink">Sakura Pink</li>
    <li class="selected luscious-grey" data-value="744" title="Luscious Grey">Luscious Grey</li>
    <li class=" lime-citrus" data-value="748" title="Lime Citrus">Lime Citrus</li>
    <li class=" hot-chocolate" data-value="741" title="Hot Chocolate">Hot Chocolate</li>
    <li class=" black-sapphire" data-value="746" title="Black Sapphire">Black Sapphire</li>
    <li class=" wildberry-deluxe" data-value="727" title="Wildberry Deluxe">Wildberry Deluxe</li>
    <li class=" tundra-spring" data-value="747" title="Tundra Spring">Tundra Spring</li>
    <li class=" aubergine-dream" data-value="745" title="Aubergine Dream">Aubergine Dream</li>
</ul>

Thanks in advance



via Chebli Mohamed

setting HTML content in CKEditor

I would like to insert HTML content in CKEDITOR but it needs to be processed and not shown as it is. for example : The input data is '<h2>some title</h2>'. what is shown in the editor 'some title'..

I already tried using ck.insertHtml(html) but this method does not clear the content before adding the new one



via Chebli Mohamed

Can't understand a javascript .call() usage

I'm trying to learn the three.js library by reading the "WebGL Up And Running" book and the problem for me is that the author made his own javascript framework called 'sim.js' which is a "higher-level set of reusable objects build upon three.js that wraps the more repetitive Three.js tasks" as he said but for a beginner like me i'd prefer more experiencing the raw three.js first.. So now i have to understand what his framwork does to understand what happens under the hood.

this is the sim.js

// Sim.js - A Simple Simulator for WebGL (based on Three.js)

Sim = {};

// Sim.Publisher - base class for event publishers
Sim.Publisher = function() {
    this.messageTypes = {};
}

Sim.Publisher.prototype.subscribe = function(message, subscriber, callback) {
    var subscribers = this.messageTypes[message];
    if (subscribers)
    {
        if (this.findSubscriber(subscribers, subscriber) != -1)
        {
            return;
        }
    }
    else
    {
        subscribers = [];
        this.messageTypes[message] = subscribers;
    }

    subscribers.push({ subscriber : subscriber, callback : callback });
}

Sim.Publisher.prototype.unsubscribe =  function(message, subscriber, callback) {
    if (subscriber)
    {
        var subscribers = this.messageTypes[message];

        if (subscribers)
        {
            var i = this.findSubscriber(subscribers, subscriber, callback);
            if (i != -1)
            {
                this.messageTypes[message].splice(i, 1);
            }
        }
    }
    else
    {
        delete this.messageTypes[message];
    }
}

Sim.Publisher.prototype.publish = function(message) {
    var subscribers = this.messageTypes[message];

    if (subscribers)
    {
        for (var i = 0; i < subscribers.length; i++)
        {
            var args = [];
            for (var j = 0; j < arguments.length - 1; j++)
            {
                args.push(arguments[j + 1]);
            }
            subscribers[i].callback.apply(subscribers[i].subscriber, args);
        }
    }
}

Sim.Publisher.prototype.findSubscriber = function (subscribers, subscriber) {
    for (var i = 0; i < subscribers.length; i++)
    {
        if (subscribers[i] == subscriber)
        {
            return i;
        }
    }

    return -1;
}

// Sim.App - application class (singleton)
Sim.App = function()
{
    Sim.Publisher.call(this);

    this.renderer = null;
    this.scene = null;
    this.camera = null;
    this.objects = [];
}

Sim.App.prototype = new Sim.Publisher;

Sim.App.prototype.init = function(param)
{
    param = param || {};    
    var container = param.container;
    var canvas = param.canvas;

    // Create the Three.js renderer, add it to our div
    var renderer = new THREE.WebGLRenderer( { antialias: true, canvas: canvas } );
    renderer.setSize(container.offsetWidth, container.offsetHeight);
    container.appendChild( renderer.domElement );

    // Create a new Three.js scene
    var scene = new THREE.Scene();
    scene.add( new THREE.AmbientLight( 0x505050 ) );
    scene.data = this;

    // Put in a camera at a good default location
    camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 10000 );
    camera.position.set( 0, 0, 3.3333 );

    scene.add(camera);

    // Create a root object to contain all other scene objects
    var root = new THREE.Object3D();
    scene.add(root);

    // Create a projector to handle picking
    var projector = new THREE.Projector();

    // Save away a few things
    this.container = container;
    this.renderer = renderer;
    this.scene = scene;
    this.camera = camera;
    this.projector = projector;
    this.root = root;

    // Set up event handlers
    this.initMouse();
    this.initKeyboard();
    this.addDomHandlers();
}

//Core run loop
Sim.App.prototype.run = function()
{
    this.update();
    this.renderer.render( this.scene, this.camera );
    var that = this;
    requestAnimationFrame(function() { that.run(); });  
}

// Update method - called once per tick
Sim.App.prototype.update = function()
{
    var i, len;
    len = this.objects.length;
    for (i = 0; i < len; i++)
    {
        this.objects[i].update();
    }
}

// Add/remove objects
Sim.App.prototype.addObject = function(obj)
{
    this.objects.push(obj);

    // If this is a renderable object, add it to the root scene
    if (obj.object3D)
    {
        this.root.add(obj.object3D);
    }
}

Sim.App.prototype.removeObject = function(obj)
{
    var index = this.objects.indexOf(obj);
    if (index != -1)
    {
        this.objects.splice(index, 1);
        // If this is a renderable object, remove it from the root scene
        if (obj.object3D)
        {
            this.root.remove(obj.object3D);
        }
    }
}

// Event handling
Sim.App.prototype.initMouse = function()
{
    var dom = this.renderer.domElement;

    var that = this;
    dom.addEventListener( 'mousemove', 
            function(e) { that.onDocumentMouseMove(e); }, false );
    dom.addEventListener( 'mousedown', 
            function(e) { that.onDocumentMouseDown(e); }, false );
    dom.addEventListener( 'mouseup', 
            function(e) { that.onDocumentMouseUp(e); }, false );

    $(dom).mousewheel(
            function(e, delta) {
                that.onDocumentMouseScroll(e, delta);
            }
        );

    this.overObject = null;
    this.clickedObject = null;
}

Sim.App.prototype.initKeyboard = function()
{
    var dom = this.renderer.domElement;

    var that = this;
    dom.addEventListener( 'keydown', 
            function(e) { that.onKeyDown(e); }, false );
    dom.addEventListener( 'keyup', 
            function(e) { that.onKeyUp(e); }, false );
    dom.addEventListener( 'keypress', 
            function(e) { that.onKeyPress(e); }, false );

    // so it can take focus
    dom.setAttribute("tabindex", 1);
    dom.style.outline='none';
}

Sim.App.prototype.addDomHandlers = function()
{
    var that = this;
    window.addEventListener( 'resize', function(event) { that.onWindowResize(event); }, false );
}

Sim.App.prototype.onDocumentMouseMove = function(event)
{
    event.preventDefault();

    if (this.clickedObject && this.clickedObject.handleMouseMove)
    {
        var hitpoint = null, hitnormal = null;
        var intersected = this.objectFromMouse(event.pageX, event.pageY);
        if (intersected.object == this.clickedObject)
        {
            hitpoint = intersected.point;
            hitnormal = intersected.normal;
        }
        this.clickedObject.handleMouseMove(event.pageX, event.pageY, hitpoint, hitnormal);
    }
    else
    {
        var handled = false;

        var oldObj = this.overObject;
        var intersected = this.objectFromMouse(event.pageX, event.pageY);
        this.overObject = intersected.object;

        if (this.overObject != oldObj)
        {
            if (oldObj)
            {
                this.container.style.cursor = 'auto';

                if (oldObj.handleMouseOut)
                {
                    oldObj.handleMouseOut(event.pageX, event.pageY);
                }
            }

            if (this.overObject)
            {
                if (this.overObject.overCursor)
                {
                    this.container.style.cursor = this.overObject.overCursor;
                }

                if (this.overObject.handleMouseOver)
                {
                    this.overObject.handleMouseOver(event.pageX, event.pageY);
                }
            }

            handled = true;
        }

        if (!handled && this.handleMouseMove)
        {
            this.handleMouseMove(event.pageX, event.pageY);
        }
    }
}

Sim.App.prototype.onDocumentMouseDown = function(event)
{
    event.preventDefault();

    var handled = false;

    var intersected = this.objectFromMouse(event.pageX, event.pageY);
    if (intersected.object)
    {
        if (intersected.object.handleMouseDown)
        {
            intersected.object.handleMouseDown(event.pageX, event.pageY, intersected.point, intersected.normal);
            this.clickedObject = intersected.object;
            handled = true;
        }
    }

    if (!handled && this.handleMouseDown)
    {
        this.handleMouseDown(event.pageX, event.pageY);
    }
}

Sim.App.prototype.onDocumentMouseUp = function(event)
{
    event.preventDefault();

    var handled = false;

    var intersected = this.objectFromMouse(event.pageX, event.pageY);
    if (intersected.object)
    {
        if (intersected.object.handleMouseUp)
        {
            intersected.object.handleMouseUp(event.pageX, event.pageY, intersected.point, intersected.normal);
            handled = true;
        }
    }

    if (!handled && this.handleMouseUp)
    {
        this.handleMouseUp(event.pageX, event.pageY);
    }

    this.clickedObject = null;
}

Sim.App.prototype.onDocumentMouseScroll = function(event, delta)
{
    event.preventDefault();

    if (this.handleMouseScroll)
    {
        this.handleMouseScroll(delta);
    }
}

Sim.App.prototype.objectFromMouse = function(pagex, pagey)
{
    // Translate page coords to element coords
    var offset = $(this.renderer.domElement).offset();  
    var eltx = pagex - offset.left;
    var elty = pagey - offset.top;

    // Translate client coords into viewport x,y
    var vpx = ( eltx / this.container.offsetWidth ) * 2 - 1;
    var vpy = - ( elty / this.container.offsetHeight ) * 2 + 1;

    var vector = new THREE.Vector3( vpx, vpy, 0.5 );

    this.projector.unprojectVector( vector, this.camera );

    var ray = new THREE.Ray( this.camera.position, vector.subSelf( this.camera.position ).normalize() );

    var intersects = ray.intersectScene( this.scene );

    if ( intersects.length > 0 ) {      

        var i = 0;
        while(!intersects[i].object.visible)
        {
            i++;
        }

        var intersected = intersects[i];
        var mat = new THREE.Matrix4().getInverse(intersected.object.matrixWorld);
        var point = mat.multiplyVector3(intersected.point);

        return (this.findObjectFromIntersected(intersected.object, intersected.point, intersected.face.normal));                                                 
    }
    else
    {
        return { object : null, point : null, normal : null };
    }
}

Sim.App.prototype.findObjectFromIntersected = function(object, point, normal)
{
    if (object.data)
    {
        return { object: object.data, point: point, normal: normal };
    }
    else if (object.parent)
    {
        return this.findObjectFromIntersected(object.parent, point, normal);
    }
    else
    {
        return { object : null, point : null, normal : null };
    }
}


Sim.App.prototype.onKeyDown = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyDown)
    {
        this.handleKeyDown(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onKeyUp = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyUp)
    {
        this.handleKeyUp(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onKeyPress = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyPress)
    {
        this.handleKeyPress(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onWindowResize = function(event) {

    this.renderer.setSize(this.container.offsetWidth, this.container.offsetHeight);

    this.camera.aspect = this.container.offsetWidth / this.container.offsetHeight;
    this.camera.updateProjectionMatrix();

}

Sim.App.prototype.focus = function()
{
    if (this.renderer && this.renderer.domElement)
    {
        this.renderer.domElement.focus();
    }
}


// Sim.Object - base class for all objects in our simulation
Sim.Object = function()
{
    Sim.Publisher.call(this);

    this.object3D = null;
    this.children = [];
}

Sim.Object.prototype = new Sim.Publisher;

Sim.Object.prototype.init = function()
{
}

Sim.Object.prototype.update = function()
{
    this.updateChildren();
}

// setPosition - move the object to a new position
Sim.Object.prototype.setPosition = function(x, y, z)
{
    if (this.object3D)
    {
        this.object3D.position.set(x, y, z);
    }
}

//setScale - scale the object
Sim.Object.prototype.setScale = function(x, y, z)
{
    if (this.object3D)
    {
        this.object3D.scale.set(x, y, z);
    }
}

//setScale - scale the object
Sim.Object.prototype.setVisible = function(visible)
{
    function setVisible(obj, visible)
    {
        obj.visible = visible;
        var i, len = obj.children.length;
        for (i = 0; i < len; i++)
        {
            setVisible(obj.children[i], visible);
        }
    }

    if (this.object3D)
    {
        setVisible(this.object3D, visible);
    }
}

// updateChildren - update all child objects
Sim.Object.prototype.update = function()
{
    var i, len;
    len = this.children.length;
    for (i = 0; i < len; i++)
    {
        this.children[i].update();
    }
}

Sim.Object.prototype.setObject3D = function(object3D)
{
    object3D.data = this;
    this.object3D = object3D;
}

//Add/remove children
Sim.Object.prototype.addChild = function(child)
{
    this.children.push(child);

    // If this is a renderable object, add its object3D as a child of mine
    if (child.object3D)
    {
        this.object3D.add(child.object3D);
    }
}

Sim.Object.prototype.removeChild = function(child)
{
    var index = this.children.indexOf(child);
    if (index != -1)
    {
        this.children.splice(index, 1);
        // If this is a renderable object, remove its object3D as a child of mine
        if (child.object3D)
        {
            this.object3D.remove(child.object3D);
        }
    }
}

// Some utility methods
Sim.Object.prototype.getScene = function()
{
    var scene = null;
    if (this.object3D)
    {
        var obj = this.object3D;
        while (obj.parent)
        {
            obj = obj.parent;
        }

        scene = obj;
    }

    return scene;
}

Sim.Object.prototype.getApp = function()
{
    var scene = this.getScene();
    return scene ? scene.data : null;
}

// Some constants

/* key codes
37: left
38: up
39: right
40: down
*/
Sim.KeyCodes = {};
Sim.KeyCodes.KEY_LEFT  = 37;
Sim.KeyCodes.KEY_UP  = 38;
Sim.KeyCodes.KEY_RIGHT  = 39;
Sim.KeyCodes.KEY_DOWN  = 40;

in another script he wrote a new class called earth-basic based on the sim class so, the begining of the earth-basic.js script looks as the following :

// Constructor
EarthApp = function()
{
    Sim.App.call(this);
}

// Subclass Sim.App
EarthApp.prototype = new Sim.App();

// Our custom initializer
EarthApp.prototype.init = function(param)
{
    // Call superclass init code to set up scene, renderer, default camera
    Sim.App.prototype.init.call(this, param);

    // Create the Earth and add it to our sim
    var earth = new Earth();
    earth.init();
    this.addObject(earth);
}

// Custom Earth class
Earth = function()
{
    Sim.Object.call(this);
}

Earth.prototype = new Sim.Object();

1) what does the function call in the line "Sim.App.call(this);" written in the constructor (by passing "this" as parameter which i suppose is referring to the EarthApp variable)? all what i can guess is that EarthApp will inherit the Sim.App properties (the renderer, the camera ...). The same "technique" was used inside the "Sim.App" function itself by calling "Sim.Publisher.call(this);"

2) in 1) i supposed he just used the sim.App class as a super-Class but then all of a sudden, i found he added a new instance of sim.App() to the EarthApp's prototype by writting "EarthApp.prototype = new Sim.App();" PLease guys tell me what the heck is going on in there.



via Chebli Mohamed

Google Map API - 'google' not defined - MVC5 javascript

I get JavaScript "google is undefined" error.

I apologize if this question is similar to this but I am using it in a different setting, so this may be an MVC issue.

I use MCV5 website standard template and I put in the head of _layout.chtml main template:

<script src="http://ift.tt/NF9SGx"></script>

This code goes into one of the views, for the account/index action:

<div id="map_canvas"></div>
<span id="result"></span>
<script>
    var map = null;
    var markersArray = [];

    function initialize() {

        var latlng = new google.maps.LatLng(13.73868, 1.07143);

        var settings = {
            zoom: 14,
            center: latlng,
            mapTypeControl: true,
            scaleControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
            },
            navigationControl: true,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.DEFAULT
            },
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            backgroundColor: 'white'
        };

        map = new google.maps.Map(document.getElementById('map_canvas'), settings);
        google.maps.event.addListener(map, 'click', function (event) {
            document.getElementById('result').innerHTML = 'Lat: ' + event.latLng.lat() + ' Lng: ' + event.latLng.lng();
        });
    }

    window.onload = initialize;

</script>

Somehow the linked google js file does not seem to load by the time function initialize() runs and I get JavaScript "google is undefined" error in the first line of initialize() function.

Thanks for your help.



via Chebli Mohamed

JSON encoding array

I have a jQuery graph which builds the x-axis like so:

xaxis: {
  tickColor: 'transparent',
  tickDecimals: 0,
  ticks: [[1,'27/07'],[2,'28/07'],[3,'29/07'],[4,'30/07'],[5,'31/07'],[6,'01/08'],[7,'02/08']]
},

I want the 'ticks' to be generated by a piece of javascipt that loops between 2 variable dates like so:

var i = 1;
var superArray = [];
var subArray = []; 

for (var d = d1; d <= d2; d.setDate(d.getDate() + 1)) {

  var m0 = d.getMonth() + 1;
  var d0 = d.getDate();

  m0 = m0 > 9 ? m0 : "0"+m0;
  d0 = d0 > 9 ? d0 : "0"+d0;

  var x = d0 + '/' + m0;

  subArray.push(i, x);
  superArray.push(subArray.slice(0));

  i++;

}

console.log(JSON.stringify(superArray));

The console.log looks like so:

[[1,"27/07"],[1,"27/07",2,"28/07"],[1,"27/07",2,"28/07",3,"29/07"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07",5,"31/07"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07",5,"31/07",6,"01/08"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07",5,"31/07",6,"01/08",7,"02/08"]]

Which is kinda close to what I want but not quite!

How can I make this:

[[1,"27/07"],[1,"27/07",2,"28/07"],[1,"27/07",2,"28/07",3,"29/07"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07",5,"31/07"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07",5,"31/07",6,"01/08"],[1,"27/07",2,"28/07",3,"29/07",4,"30/07",5,"31/07",6,"01/08",7,"02/08"]]

Look like this:

[[1,'27/07'],[2,'28/07'],[3,'29/07'],[4,'30/07'],[5,'31/07'],[6,'01/08'],[7,'02/08']]



via Chebli Mohamed

Unable to parse JSON response body in JavaScript

I am trying to parse the below response body that I received from my http request.

callback({"processingDurationMillis":29,"authorisedAPI":true,"success":true,"airline":null,"errorMessage":null,"distance":"4,128.4","units":"km"})

I need help in accessing the distance field in the body, but first I am unable to change this JSON into a JS object.

Here's what I'm doing

response = HTTP.call('GET', URL,function(err,result){
        console.log(result.content);
        data = JSON.parse(result.content);

        var extractedData = data['distanceResponse'];
        console.log(extractedData);
    });

I'm able to log result.content but nothing after. Please help? Thanks much appreciated!



via Chebli Mohamed

Is there a way to make a appear when a button is selected and the display is none, using JavaScript or any other language?

I am having some trouble here. I am developing a button that once selected will run a JavaScript function - ShowColumn() - that will make a table column appear. The table column will at first be hidden - "display:none;" - but once the user selects the button the table column that is hidden will then appear/will be visible. Can this be done? And if so please can someone help? Thanks :)

I have included what I have done so far, as follows:

<html>
  <head>
    
    
    <script type="text/Javascript">
      
      function ShowColumn(){
        
            document.getElementById("hiddenColumn").style.display = ""; 
        
        }
      
    </script>
    
    
  </head>
  <body>
    
    <button onClick="ShowColumn()"></button>
    
    <table>
      <tr>
         <td>
           <textarea>Write something here....</textarea>
         </td>
        <td id="hiddenColumn" style="display:none;">
           <textarea>Write something here....</textarea>
         </td>
      </tr>
    </table>  
      
      
  </body>
</html>

I have done a lot of research and I haven't come up with any solution to my problem. Can this be done with JavaScript and HTML alone? Or do I have to incorporate another language into the system in order to make the hidden column visible? Any help would be highly appreciated! Thanks



via Chebli Mohamed

"Fatal error: Unable to find local grunt." on windows7 professional

f I want to start grunt, I get the following message:

c:\repositories\kunde_1\themes-projekt_1\projekt_1-responsive\source>grunt
grunt-cli: The grunt command line interface. (v0.1.13)

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or grunt
hasn't been installed locally to your project. For more information about
installing and configuring grunt, please see the Getting Started guide:

http://ift.tt/ZERd4b

When running grunt you will see:

C:\Users\dev_user>npm install -g grunt-cli
npm http GET http://ift.tt/KacD7J
npm http 304 http://ift.tt/KacD7J
npm http GET http://ift.tt/Zu2t3i
npm http GET http://ift.tt/1eDekak
npm http GET http://ift.tt/1oU5gRI
npm http 304 http://ift.tt/Zu2t3i
npm http 304 http://ift.tt/1eDekak
npm http 304 http://ift.tt/1oU5gRI
npm http GET http://ift.tt/Zu2pAF
npm http GET http://ift.tt/Zu2pAB
npm http GET http://ift.tt/1hnhOy1
npm http 304 http://ift.tt/Zu2pAF
npm http 304 http://ift.tt/Zu2pAB
npm http 304 http://ift.tt/1hnhOy1
npm http GET http://ift.tt/Zu2vbj
npm http GET http://ift.tt/Zu2tjK
npm http 304 http://ift.tt/Zu2vbj
npm http 304 http://ift.tt/Zu2tjK
npm http GET http://ift.tt/Zu2vbn
npm http GET http://ift.tt/Zu2tjQ
npm http 304 http://ift.tt/Zu2vbn
npm http 304 http://ift.tt/Zu2tjQ
C:\Users\dev_user\AppData\Roaming\npm\grunt -> C:\Users\dev_user\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt
grunt-cli@0.1.13 C:\Users\dev_user\AppData\Roaming\npm\node_modules\grunt-cli
+-- nopt@1.0.10 (abbrev@1.0.7)
+-- resolve@0.3.1
+-- findup-sync@0.1.3 (lodash@2.4.2, glob@3.2.11)

Entering grunt in user directory:

C:\Users\dev_user>grunt
grunt-cli: The grunt command line interface. (v0.1.13)

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or grunt
hasn't been installed locally to your project. For more information about
installing and configuring grunt, please see the Getting Started guide:

http://ift.tt/ZERd4b

But the same message comes when I enter the project directory!

operating system: windows 7 Professional
npm -version: 1.3.5
node --version: v0.10.15

C:\Users\dev_user>npm ls -g
C:\Users\dev_user\AppData\Roaming\npm
+-- coffee-script@1.9.3
+-- grunt-cli@0.1.13
  +-- findup-sync@0.1.3
  ¦ +-- glob@3.2.11
  ¦ ¦ +-- inherits@2.0.1
  ¦ ¦ +-- minimatch@0.3.0
  ¦ ¦   +-- lru-cache@2.6.5
  ¦ ¦   +-- sigmund@1.0.1
  ¦ +-- lodash@2.4.2
  +-- nopt@1.0.10
  ¦ +-- abbrev@1.0.7
  +-- resolve@0.3.1

The environment variable I have set:

Name of variable: grunt Path: C:\Users\dev_user\AppData\Roaming\npm\grunt then launched new computer

Does anyone have an idea why the message Fatal error: Unable to find local grunt. coming?



via Chebli Mohamed

Angular: Control that fired ng-change

I have an Angular form that has several input boxes that I want to validate, using a generic JS function but need to know the control that fired the event so certain rules can be applied.

(Simplified code)

<input ng-model="Field1" ..... ng-change="validateMe()" />
.
.
<input ng-model="FieldX" ..... ng-change="validateMe()" />

$scope.validateMe = function() {
   // get the text of the control that fired the event

   // do the validation 

   // update something else if valid value given

}

I know that ng-click has the $event, but how can I do it from an ng-change



via Chebli Mohamed

Set button active when form is filled (Angular)

I have the following controller and directive:

app.controller('controlFormulario', ['$scope', function($scope) {
  var cf = this;
  cf.formulario = [];
  cf.formulario.fecha = new Date();

  if(cf.formulario.texto != null && cf.formulario.titulo != null){
    this.formulario.isDisabled = false;
  }
}]);

app.directive('formulario', [function() {
  return {
    restrict: 'E', // C: class, E: element, M: comments, A: attributes
    templateUrl: 'modules/formulario.html',

  };
}]);

And this is the DOM element of the button, the one I want to enable when there is some text in the title and text fields:

<div class="form-group" ng-init="formCtrl.formulario.isDisabled = true">
  <button class="btn btn-primary" style="height:35px;width:100px;float:right;" id="submit" disabled={{formCtrl.formulario.isDisabled}}>
  Enviar
  </button>
</div>

Currently, the controller function that enables the button, isn't working at all. I've got it instantiated in the main div of the formulary, and it's working properly with the data binding, but it's somehow not enabling the button.

What am I doing wrong?



via Chebli Mohamed

how to hide parent when click anywhere outside the child element

I have this code

<style>

.Parent {width:500px;height:500px;background:#000}
.Parent .Child {width:250px;height:250px;background:#F00}

</style>

<div class="Parent">

   <div class="child"></div>

</div>

<script>

$(document).ready(function() {

     $('.Parent').click(function () {

           $(this).hide()

     });

     /* 
     But if i click on <div class="Child"></div> , 
     <div class="Parent"></div> won't get hidden .
     */ 

});

</script>

I want my code to hide'.parent', When I click on areas in .Parent witch doesn't include .Child elementand if the areas I click was included in '.child' area , it don't do anything .

so what would u guys suggest ?



via Chebli Mohamed

how to control multiple uploads to count 5

I want to upload images for adding property and have some code in which i am able to add more than 5 file uploads. How can stop the uploads at five. here is the sample code i am using

<form enctype="multipart/form-data" action="" method="post">
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>

and the js code for add button is

$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),        
$("<br/><br/>")
));
});

how can i stop add more button can be available for only five.



via Chebli Mohamed

angular bootstrap calendar not displaying

I am trying to use the angular bootstrap calendar in my apache cordova app

HTML:

            <ion-view>
                <ion-content has-header="true" padding="true" ng-app="app" data-ng-controller="calendarController">
                    {{test}}
                    <mwl-calendar view="calendarView"
                      current-day="calendarDay"
                      events="events">
                </mwl-calendar>
                </ion-content>
            </ion-view>

Controller:

.controller('calendarController', ['$scope', '$state', 'moment', function ($scope, $state, moment) {

$scope.test = 'Test the controller';
$scope.calendarView = 'week';
$scope.calendarDay = new Date();
$scope.events = [
 {
     title: 'My event title', // The title of the event
     type: 'info',
     startsAt: new Date(2013, 5, 1, 1),
     endsAt: new Date(2014, 8, 26, 15),
     editable: false,
     deletable: false,
     incrementsBadgeTotal: true
 }
];
}]);

I have included the links to the relevant dependencies including moment.js however I get a message 'the value passed to current day attribute is not set'. I have made sure moment.js is linked before the main app.js file which contains the controller as suggested in a similar question but I still get the same message. I am new to angular and would appreciate any help that anyone can offer.



via Chebli Mohamed

Function for AddRow & Popup not working as expected

I am new to the development field. There are two problem with this code. First when I click button for add_Row then a row gets added on screen but it disappears after 1-2 seconds and same thing happens with group_Create() popup.

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
    <title>Inventory Expert</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="../../Bootstrap-3.3.2-dist/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="../../CSS/ProductMaster/ProductMaster.css"/>
    <link rel="stylesheet" href="../../CSS/ProductMaster/RawMaterialGroup.css"/>
    <script src="../../JAVASCRIPT/ProductMaster/ProductMaster.js"></script>
    <script src="../../JAVASCRIPT/ProductMaster/RawMaterialGroup.js"></script>
    <script src="../../jquery-1.11.2.js"></script>
    <script src="../../jquery-ui-1.11.2.custom/jquery-ui.js"></script>
    <script src="../../jquery-ui-1.11.2.custom/jquery-ui.min.js"></script>
</head>
<body>
    <img id="top" src="../../Images/shaddow_line_top.png" alt=""/>
    <div class="container">
        <h1><a>Product Master</a></h1>
        <form id="productmasterForm">
            <table class="table" id="productmasterTable">
                <tr>
                    <td class="W45">Product Code <input id="productid" type="text"/></td>
                    <td class="W45">Product Name <input id="productname" type="text"/></td>
                    <td class="W10"></td>
                </tr>
                <tr>
                    <td class="W45">Basic Raw Material <input id="basicraw" type="text"/></td>
                    <td class="W45">Group Name <input id="groupname" type="text"/></td>
                    <td class="W10">
                        <div class="btn-group">
                            <button class="btn btn-info btn-sm" id="groupcreate" onclick="group_Create()">C</button>
                            <button class="btn btn-info btn-sm" id="groupedit" onclick="group_Edit()">E</button>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="W40">Raw Material <input id="rm1" type="text"/></td>
                    <td class="W30">Size <input id="s1" type="text"/></td>
                    <td class="W20">Qty. <input id="q1" type="text"/></td>
                    <td class="W10">
                        <div class="btn-group">
                            <button class="btn btn-info btn-sm" onclick="maprawNsize()">C</button>
                            <button class="btn btn-info btn-sm" onclick="maprawNsize_Edit()">E</button>
                            <button class="btn btn-info btn-sm" id="pma" onclick="add_Row()">A</button>
                        </div>
                    </td>
                </tr>                    
                <tr>
                    <td class="W45">VAT Rate <input id="vat" type="text"/></td>
                    <td class="W45">Unit Of Measure <input id="uom" type="text"/></td>
                    <td class="W10"></td>
                </tr>
                <tr>
                    <td class="W45">Manufacturing Cost <input id="menucost" type="text"/></td>
                    <td class="W45">Sale Rate <input id="salerate" type="text"/></td>
                    <td class="W10"></td>
                </tr>
                <tr>
                    <td class="W45">Maximum Retail Price <input id="mrp" type="text"/></td>
                    <td class="W45">Default Discount <input id="defdisc" type="text"/></td>
                    <td class="W10"></td>
                </tr>
                <tr>
                    <td class="W45">Rate List Date <input id="listdate" type="text"/></td>
                    <td class="W45">Kit Reference <input id="kitref" type="text"/></td>
                    <td class="W10"></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>

JavaScript File ProductMaster.js

var rowCount = 1;
var rowPosition = 3;
var id = 2;
function add_Row() {
if (rowCount < 11) {
    var table = document.getElementById("productmasterTable");
    var row = table.insertRow(rowPosition);
    rowPosition++;
    for (i = 0; i < 1; i++) {
        var td1 = document.createElement("td");
        td1.innerHTML = 'Raw Material <input id="rm' + id + '" type="text"/>';
        row.appendChild(td1);
        td1.setAttribute("class", "W40");
    }
    for (i = 0; i < 1; i++) {
        var td2 = document.createElement("td");
        td2.innerHTML = 'Size <input id="s' + id + '" type="text"/>';
        row.appendChild(td2);
        td2.setAttribute("class", "W30");
    }
    for (i = 0; i < 1; i++) {
        var td3 = document.createElement("td");
        td3.innerHTML = 'Qty. <input id="q' + id + '" type="text"/>';
        row.appendChild(td3);
        td3.setAttribute("class", "W20");
    }
    id++;
    rowCount++;
}
else {
    alert("Only 10 Allowed");
}
}

JavaScript File RawMaterialGroup.js

function group_Create(){
document.getElementById('rawgroup').style.display = "block";
}

function group_Hide(){
document.getElementById('rawgroup').style.display = "none";
}

function group_Edit(){
alert("I Am Clicked");
}
var rowCount = 5;
var rowPosition = 7;
var id = 2;
function add_rawMaterial() {
if (rowCount < 16) {
    var table = document.getElementById("groupTable");
    var row = table.insertRow(rowPosition);
    rowPosition++;
    for (i = 0; i < 1; i++) {
        var td1 = document.createElement("td");
        td1.innerHTML = 'Raw Material <input id="rmgrm' + id + '" type="text"/>';
        row.appendChild(td1);
        td1.setAttribute("class", "W40");
    }
    for (i = 0; i < 1; i++) {
        var td2 = document.createElement("td");
        td2.innerHTML = 'Qty. <input id="rmgq' + id + '" type="text"/>';
        row.appendChild(td2);
        td2.setAttribute("class", "W20");
    }
    for (i = 0; i < 1; i++) {
        var td3 = document.createElement("td");
        td3.innerHTML = 'UOM <input id="rmguom' + id + '" type="text"/>';
        row.appendChild(td3);
        td3.setAttribute("class", "W20");
    }
    id++;
rowCount++;
}
else {
    alert("Only 15 Allowed");
}
}

CSS File ProductMaster.css

body{
text-align: center;
overflow: hidden;
}
td{
float: left;
text-align: left
}
#rm1,#rm2,#rm3,#rm4,#rm5,#rm6,#rm7,#rm8,#rm9,#rm10{
width: 250px;
height: 30px
}
#s1,#s2,#s3,#s4,#s5,#s6,#s7,#s8,#s9,#s10{
width: 250px;
height: 30px;
}
#q1,#q2,#q3,#q4,#q5,#q6,#q7,#q8,#q9,#q10{
width: 100px;
height: 30px;
}
.W45{
width: 45%;
}
.W10{
width: 10%;
}
.W15{
width: 15%;
}
.W20{
width: 20%;
}
.W30{
width: 30%;
}
#productid{
width: 100px;
height: 30px;
}
#productname{
width: 300px;
height: 30px;
}
#basicraw{
width: 259px;
height: 30px;
}
#groupname{
width: 315px;
height: 30px;
}
#productmasterForm{
font-size: 20px;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
#vat{
width: 80px;
height: 30px;
}
#uom{
width: 80px;
height: 30px;
}
#menucost{
width: 80px;
height: 30px;
}
#salerate{
width: 80px;
height: 30px;
}
#mrp{
width: 80px;
height: 30px;
}
#defdisc{
width: 80px;
height: 30px;
}
#listdate{
width: 120px;
height: 30px;
}
#kitref{
width: 100px;
height: 30px;
}

CSS File RawMaterialGroup.css

h2 {
background-color:#00a2e2;
padding:20px 20px;
margin:-10px -10px;
text-align:center;
border-radius:10px 10px 0 0;
border: 1px solid #313131;
}
#rawgroup{
width: 100%;
height: 100%;
opacity: 0.95;
top: 0;
bottom: 0;
display: none;
position: fixed;
background-color: #313131;
overflow: hidden;
alignment-adjust: central;
}
div#groupPopup{
position: fixed;
left: 18%;
top: 17%;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
img#close_group{
position: absolute;
right: -7px;
top: -7px;
cursor: pointer;
}
#groupForm{
max-width: 900px;
min-width: 900px;
padding: 10px 10px;
border: 2px solid gray;
border-radius: 10px;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
background-color: #fff;
margin:-10px -11px;
text-align:center;
border-radius:10px 10px 10px 10px;
}
.W40{
width: 40%;
}
.W20{
width: 20%;
}
.W10{
width: 10%;
}
#rmgrm1,#rmgrm2,#rmgrm3,#rmgrm4,#rmgrm5,#rmgrm6,#rmgrm7,#rmgrm8,#rmgrm9,#rmgrm10,#rmgrm11,#rmgrm12,#rmgrm13,#rmgrm14,#rmgrm15{
width: 215px;
height: 30px;
}
#rmgq1,#rmgq2,#rmgq3,#rmgq4,#rmgq5,#rmgq6,#rmgq7,#rmgq8,#rmgq9,#rmgq10,#rmgq11,#rmgq12,#rmgq13,#rmgq14,#rmgq15{
width: 80px;
height: 30px;
}
#rmguom1,#rmguom2,#rmguom3,#rmguom4,#rmguom5,#rmguom6,#rmguom7,#rmguom8,#rmguom9,#rmguom10,#rmguom11,#rmguom12,#rmguom13,#rmguom14,#rmguom15{
width: 50px;
height: 30px;
}
#rmggn{
width: 200px;
height: 30px;
}
#rmggi{
width: 100px;
height: 30px;
}



via Chebli Mohamed

Why is my input tag losing focus immediately after getting it?

By the design, menu container onblur event should be disabled when input gets focus and it should be enabled back when input loses focus (i.e. when user finishes input.

function pauseHiding(hiderId) {
    var hider = document.getElementById(hiderId);
    hider.onblur = null;
}

function resumeHiding(hiderId, timeout) {
    var hider = document.getElementById(hiderId);
    hider.onblur = "setTimeout(function(){hideMenu(hiderId);}, timeout);";
    hider.focus();
}

In fact, input's onfocus event fires normally, but it is followed immediately by onblur event. Moreover, onfocus erases menu container's onblur event, but input's onblur doesn't returns it back. http://ift.tt/1ONfleU



via Chebli Mohamed

How to add elements from a JSON array to a grid using Angular.js

I have a JSON array in a file data.json which is as :

var info = [{
"place": "Turkey",
"username": "jhon"
}, {
"place": "Dubai",
"username": "bruce"
}, {
"place": "Italy",
"username": "Wayne"
}];

I am able to access these using a loop and check with the help of an alert box.. However, I wish to display the contents in the form of a table. I could use JavaScript or as somebody suggested to me I could also use Angular.js. Any idea on what way I could get along with will be easier?



via Chebli Mohamed

How to split jquery source code into multiple files when using the module pattern?

I've got some problems splitting up my jquery source code into more than one file. My real source code is a bit more complicated but the following simple example shows my problem very good. At first I would like to show you a working example with only one javascript file. Afterwards, I will describe what I tried in order to split the javascript into two files.

My html code looks like this ("./jquery" is a symbolic link to my local jquery download):

<html>
  <head>
    <script src="./jquery"></script>
    <script src="./file1.js"></script>
  </head>

  <body>
    <div id="content"></div>
  </body>
</html>

The jquery source code in file1.js looks like this:

$(document).ready(function() {

  var Test = (function() {
    var content = $('#content');

    var init = function() {
      content.html('<p>test</p>');
    };

    return {
      init: init
    }
  })();

  Test.init();
});

After opening the page, "test" is displayed so that this example works as expected.

But now I want to put the whole Test part into another file file2.js. My html is basically the same but gets an additional line:

<script src="./file2.js"></script>

file1.js now contains only the call of the init function:

$(document).ready(function() {
  Test.init();
});

and file2.js contains the definition of Test:

var Test = (function() {
  var content = $('#content');

  var init = function() {
    content.html('<p>test</p>');
  };

  return {
    init: init
  }
})();

When I open the page, "test" is not displayed any more. In order to make sure that the init function is called at all, I added a console.log("test"); to the init function which is working fine. Therefore, I suppose that the function might be called before the DOM is ready, but actually I am pretty clueless. Maybe someone can give me a hint how to make that run.

Best regards and thanks in advance!



via Chebli Mohamed

d3.max() returning a value 10% larger than actual value

I have an issue with d3.max() returning a number 10% higher than the actual largest number in the set.

I'm using d3js and c3js.

CSV

date,count
2003-01-10,4
2002-01-14,5
2001-01-09,6

JavaScript

values: function(d){
    var tickNumber = 3, //Set tick number
        tickValues = [],
        increment = d3.max(d) / tickNumber;
    for (i = 1; i <= tickNumber; i++){
        tickValues.push(
            numeral(increment * i).format('0')
        );
        console.log(d3.max(d));
        // returns 6.6, not 6
    };
    return tickValues;
}

I've made this work for me by changing this line

increment = d3.max(d) / tickNumber;

To

increment = (d3.max(d)-(d3.max(d)/10)) / tickNumber;

It works but it's a hack and I'm not really satisfied with it. Can you please help me understand why d3.max(d) returns 6.6, not 6?



via Chebli Mohamed

How to trigger an event if a group of elements have not been clicked

What way would you be able to trigger an on blur style event, only if a group of elements are not clicked. for example: if you wanted to make a custom drop down after an input, here is a fiddle of what I'm trying to achieve; http://ift.tt/1MKgwxa Clicking on any element that is not in the first list, should cause the list to collapse.

I have tried stopping the blur, however I can't seem to get it to work.

$('ul').hide();
$('input').focus(
    function(){    
        $('ul').show()
    }
);
$('.hidelist').click(
    function(){
        $('ul').hide();
    }

)
$('input').blur(
    function(){
        $('ul').hide();
    }
);
.results{
    background-color:pink;
}
<script src="http://ift.tt/1oMJErh"></script>
<input type="text" />
<div class="results">
    <ul>
        <li><a href="#">I have other functionality and I don't hide the list</a></li>
        <li><a href="#">I have other functionality and I don't hide the list</a></li>
        <li><a href="#">I have other functionality and I don't hide the list</a></li>
    </ul>
    <ul class="hidelist">    
        <li><a href="#"  >I make the list disapear</a></li>
    </ul>
</div>


<div>I am any other element and I make the list disapear</div>

Clicking on any element that is not in the first list, should cause the list to collapse.



via Chebli Mohamed

How do I trigger a JS function from a js.erb executed as a callback on an AJAX call?

I know the title reads a bit funky, but this is what I am doing.

I have a link that looks like this, as defined in my nodes_helper.rb:

    link_to(favorite_node_path(node, node_counter: node_counter), class: "card-favorite-count favorited", method: :post, remote: true,  data: {toggle_href: unfavorite_node_path(node) }) do
      concat(content_tag(:i, "", class: "icon-heart"))
      concat(node.cached_votes_total)
    end

That then ultimately, on success, leads to this /views/nodes/favorites.js.erb being executed:

$("#card-<%= @node_counter %> .card-attr").html('<%= favorites_count(@node, @node_counter) %>');
$("#card-<%= @node_counter %> .card-attr").append('<%= comments_count(@node) %>');

All of that works fine, but what I want to do is add some animation to the class card-favorite-count after the link is pressed. Basically, right before the count gets updated.

My animation is defined in my app/assets/javascripts/nodes.js.coffee like so:

animate_favorite = ($favorite) ->
  $favorite.addClass 'active'
  card = $favorite.parent().parent().parent()
  card_id = card.attr('id')
  setTimeout (->
    $('#' + card_id).find('.card-favorite-count').removeClass 'active'
    return
  ), 1200
  return

$(document).ready ->
  $('.card-favorite-count').click ->
    animate_favorite $(this)
    return
  return

The JS version of the above works in a plain old vanilla HTML/JS interface, but I am trying to hook it up with everything else I have going on - hence the conversion to CoffeeScript.

So, how do I call that animate_favorite function, from within my favorite.js.erb?

Edit 1

Per Ryan's suggestion, I tried this in my favorite.js.erb:

window.animate_favorite($(this));
$("#card-<%= @node_counter %> .card-attr").html('<%= favorites_count(@node, @node_counter) %>');
$("#card-<%= @node_counter %> .card-attr").append('<%= comments_count(@node) %>');

But I get this error in my JS console:

window.animate_favorite($(this));
$("#card-1 .card-attr").html('<a class="card-favorite-count favorited" data-method="post" data-remote="true" data-toggle-href="/nodes/2/favorite" href="/nodes/2/unfavorite?node_counter=1" rel="nofollow"><i class="icon-heart"></i>1</a>');
$("#card-1 .card-attr").append('<span class="card-comment-count"><i class="icon-speech-bubble-1"></i>0</span>');

comments.self.js?body=1:5 parsererror



via Chebli Mohamed

How to ignore some statements in Javascript code coverage when using lcov and istanbul?

How is it possible to make sonarqube take into account directives found in code comments ? There is a page on istanbul describing how to ignore some branches using comments like this

/* istanbul ignore if */ if (hardToReproduceError)) { return callback(hardToReproduceError); }

(see http://ift.tt/1KOO4H6)

It works well into HTML reports generated by istanbul but it does not work with Sonarqube.



via Chebli Mohamed

How do I set an Enviromental Variable in Postman, from an array, within an array?

I am struggling to extract the data from an array within an array to set as a variable. How would I set the variable from the ID, listed within address

{
"user profile":{
"email_address" : "test@test.com",
"addresses" : [
{
"id": 1
},
{
"id": 2
},
]

For a single array I use

var data = JSON.parse(responseBody); 
postman.setEnvironmentVariable("AddressID",data.user_address[data.addresses.length-1].id);

I'm not quite sure how to use the console log as advised yesterday, if that is the answer to this issue.

Many thanks



via Chebli Mohamed

AJAX call not working in android emulator, works everywhere else (Cordova)

I have a cordova app that is acting weird. When I try the source on my browser (tested on both chrome and firefox), it works. Not on my Android emulator (got it from the Android SDK).

The weird part is that I have 2 calls. Only one works. Here's my structure.

var httpClient = null;

function login(..) {

  httpClient = $.ajax({
    type: 'POST',
    ...
    ...
  });

  httpClient.done(function(data) {
    ...
    ...
    secondCall();
  });

  httpClient.fail(...);

}

function secondCall() {

  if (httpClient != null) {
    httpClient.abort();
  }

  httpClient = $.ajax({
    type: 'GET',
    ...
    ...
  });

  httpClient.done(...);

  httpClient.fail(...);

}

The POST works. I added a console.log to test what is being fired. The first call works as it should. It called the secondCall() function, and that AJAX call fails. Is it to do with the Emulator not accepting GET requests?



via Chebli Mohamed

Trigger click with JavaScript in Safari 2015?

I am trying to trigger a click with JavaScript. I get it to work in all browsers but Safari.

I am using this code:

var t = document.getElementById('someidhere');
if (document.dispatchEvent) {
 var o = document.createEvent('MouseEvents');
 o.initMouseEvent('click', true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, t);
 t.dispatchEvent(o)
} else if (document.fireEvent) {
 t.fireEvent('onclick');
} else if (t.click()) {
 t.click()
}

This code is taken from an other StackOverflow question, but it seems to be outdated?



via Chebli Mohamed

Bypass jQuery .on()

I have a java application that talks via websocket with my javascript webinterface. The webinterface consists of basic form elements such as inputs, radio buttons, a jquery slider and so on. The form fields are monitored by the jQuery .on(change)-Function. If a form field changes by user input the on-change-function triggers the websocket-transmission of the changed-data.

Now there is following problem: If a user in a second instance triggers a change the Java-Server will broadcast the information to every client. Now I want that the form element gets refreshed by changing it's value. But this is impossible because the change will trigger the onchange-event again.

So it will be an endless loop. How to solve that? Is there any way to bypass the .on(change)-Function or do I have to change my design (If yes, how to change?)

Websocket-Snipped that gets fired when a other client has changed a value:

exampleSocket.onmessage = function (event) {
    $('#freq11B').prop('checked',true);
};

jQuery Buttonset:

<div id="radioset">
<input type="radio" id="freq11A" name="freq"><label value="216.928" class="tooltip" for="freq11A">11A</label>
<input type="radio" id="freq11B" name="freq"><label value="218.640" class="tooltip" for="freq11B">11B</label>
<input type="radio" id="freq11C" name="freq"><label value="220.352" class="tooltip" for="freq11C">11C</label>
</div>

Send Data to the Server:

$('#radioset').on('change', function() {

    var inputid =   $('input[name="freq"]:checked', '#ventusform').attr("id");
    //FREQUENCY: (value just below):
    if(!(inputid == "freqCustom")){
    var freqvalue = $('label[for='+inputid+']').attr("value");
    }else{
    var freqvalue = $('#customfreq').val(); 
    }
    console.log(freqvalue);
examplesocket.send($('#customfreq').val());


});

The value does change, but the form is not refreshed. Rory McCrossan (comment below) is right! Howto change the value with refreshing the form without firing the onchange-function again?



via Chebli Mohamed

Read value of previously assigned function to onclick event by javascript

I have this code:

document.getElementById(myid).onclick = function() {
    HandleGPIO(val1, val2);
};

if (console) {
    console.log(document.getElementById(myid).getAttribute('onclick'));
}

And I would like to see how function HandleGPIO() was assigned.

how to debug it? getAttribute does not work here and returns null only



via Chebli Mohamed

Jacascript equivalent to $.holdReady()

I need to prevent the document.ready event of my site, without using jQuery.

What is the pure JavaScript equivalent to $.holdReady(); ?



via Chebli Mohamed

How to not enable toggle class at first?

$(document).ready(function(){
  $("#summary").click(function(){
    $(this).toggleClass('clicked');
  });
});
.clicked {
  background-color: red;
}
<script src="http://ift.tt/1g1yFpr"></script>
        
<div id="summary">
  <div class="clicked">111</div>
  <div class="clicked">222</div>
</div>

How to not set beckoned-color to red when html page load.Only change it to red when click on its div?



via Chebli Mohamed

How do I prevent backbone remove() from removing "el" in a view?

I want remove a view before creating a new one. But my requirement is view.remove() should remove the view but not delete the el element. Having said this, I do not want to set tagName as it creates a new element which is unnecessary. Is there any way to remove a view from the memory leaving the el content cleared?



via Chebli Mohamed

Use Javascript to objectify csv file

I'm currently working with CSV files that I whould like to objectify.

The csv format is like:

 "Property, Value1, Value2, ..." Example: 

 "Recipe_Product_Name, Knife, Fork, Spoon". 

I use the split('_') function to get a JSON looking structure, for the example above:

"Recepie-Product-Name: Knife" gives me a nice,

var name = Recepie.Product.Fork.Name

To the problem...

The csv file includes arrays like:

* "Recipe_Product_Connector{0}_Pins, 11, 47, 4" 
* "Recipe_Product_Connector{0}_Brand, Sourai, Harting, Amphenol"
* "Recipe_Product_Connector{1}_Pins, 5, 64, 18" 
* "Recipe_Product_Connector{1}_Brand, Sourai, Harting, Amphenol"

So far, I use this code for the objectification:

    var nest = function (obj, keys, v) {
    var Arr = [];
    if (keys.length === 1) {
        obj[keys[0]] = v;
    } else {
        var key = keys.shift();
        if (key.split('}').length > 1) {
            Arr.push(nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v));
            obj[key] = Arr;
            console.log(Arr);
        } else {
            obj[key] = nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v);
        }
    }
    return obj;
};

It works kind of good, except that I get multiple array structures:

var HartingPins = Recipe.Products.Connector[0][0].Pins

I do not like that, probably something wrong with the recursion. Any Ideas on how to continue?



via Chebli Mohamed

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>