vendredi 29 mai 2015

How to hide Boostrap Dropdown submenu when other menu of dropdown is clicked?

I am displaying bootstrap dropdownmenu and on click of any parent dropdown value i am displaying other child dropdown. when i click on a value in dropdown ,the childmenu opens and when i click on next dropdown value ,the previous chidmenu dropdown is not closed.I want to close the previous childdropdown menu if any other value of parent menu is clicked.How to achieve this?Please help! Thanks in advance

Here is my code:

<div class="dropdown">
    <ul id="ddlTest" class="ddltestdd dropdown-menu" role="menu">
        @foreach (var item in (IEnumerable<SelectListItem>)ViewBag.testresults)
        {
            <li class="dropdown-submenu">
                <span class="dropdown-toggle" data-toggle="dropdown">@item.Text</span>
                <span class="testCaret" aria-hidden="true" style="float:right;margin-top:5px;">
                </span>
                <ul class="ddltestdd dropdown-menu dropup" role="menu" id="testorder_@item.Text">
                    <li>
                        <span class="TestBySubmenu">T1</span>
                    </li>
                    <li>
                        <span class="TestBySubmenu">T2</span>
                    </li>
                </ul>
            </li>
        }
    </ul>
</div>

Jquery:

var testText;
                    $(".dropdown-submenu").click(function () {
                            $(this).find(".dropdown-submenu").removeClass('open');
                    $(".dropdown-submenu:hover > .dropdown-menu").css('display', 'block');
                    testText;= $(this).text();
                    return false;
                });



        $('.dropdown-menu li span').click(function () {

        var Allowpageload = testText;
        if ((Allowpageload == "T1") || (Allowpageload == "T2")) {
          //load page
            $(".dropdown-submenu:hover > .dropdown-menu").css('display', 'none');
            $('[id^="testorder_]').dropdown('toggle');
            $('[data-toggle="dropdown"]').parent().removeClass('open');
            }

Geojson (GetJSON) and remove higlight (mouse out) on Leaflet

I don't manage to remove the highlight on a map since I call the data with $.getJSON. When I use the basic map (http://ift.tt/1Kt8lC1) all works, but when I call a geojson file with Jquery (not a leaflet json template with var = {json}), the highlight doesn't remove.

Example of what doesn't work (you can see it at : http://ift.tt/1G6JiXs) I think it comes from the function resetHighlight(e) but I don't manage to resolve it.

    function styleeurope(feature) {
        return {
            weight: 1.5,
            color: '#222',
            opacity:0.5,
            fillOpacity: 0.7,
            fillColor: getColor(feature.properties.statTOTAL)
        };
    }
    function highlightFeature(e) {
        var layer = e.target;

        layer.setStyle({
            weight: 3,
            color: 'black',
            opacity: 0.7,
            dashArray: '0',
            fillOpacity: 0.5,
            fillColor: '#fff200',
        });


        info.update(layer.feature.properties);
    }

// reset highlight //

function resetHighlight(e) {
        geojson.resetStyle(e.target);
        info.update();
    }

// OnEachFeature

function onEachFeature(feature, layer) {
        layer.on({
            mouseover: highlightFeature,
            mouseout: resetHighlight,       
        });
    }

// GeoJSON call data //

$.getJSON("data/europe_fao.json",function(dataeurope){ var geojson = L.geoJson(dataeurope,{
        style: styleeurope,
        onEachFeature: onEachFeature} ).addTo(map);  });

Thank you so much if you manage to help me !

Json response to ajax

The data is inserted and i receive in console the json response but the page move for the insert php and gives the json response So i start in page A (form) and after submit moves to page B (insert)giving me the json response. I'm having a problem getting the response of the following php into ajax

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {

$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
    trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
if (!$stmt->execute()) {
    echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
} else {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));

This is my ajax

$.ajax({
            url: 'nova_formacaoBD.php',
            dataType: 'json',
            data: data,
            success: function(data) {
                $('#ajaxDivOk').html('Informação: Esta formação foi registada na base de dados');
                if(data.status == "success"){ 
                   $('#ajaxDivOk').append(data.message);
                }
             }
          });

And this is my form

 <form action="nova_formacaoBD.php" method="post" id="formacao" name="formacao" enctype="multipart/form-data">

Place the scrollbar at the bottom of viewport

I'm working on a rather complex layout. There are two regions, red and blue, that must scroll vertically simultaneously but the right region (blue) must be able to scroll horizontally independently of the other region.

I managed to do that, but the scrollbar is always at the bottom of the div and I need the scrollbar always visible at the bottom of the viewport.

Is it possible to achieve this with HTML/CSS? What plain JS or jQuery plugins could help with this?

JSFiddle Demo

Ajax fails to pass html page as parameter to code behind

I am working on a task to convert a webpage to pdf file using SelectPdf. SelectPdf does not support dynamic pages. So I want to use Ajax to pass the webpage as html.

For some reason when I passed ordinary string it works but when I change to use a variable (with html as value) it doesn't. I don't know whether the html content is too large, however I tried with less content and still the same issue. Any help will be appreciated.

The project is language is VB.Net, the page is vbhtml and code behind is a controller.

Please see below the code I have implemented:

VIEW

           var btn = $('#BtnCreateHtmlToPdf');

           btn.click(function () {

            var theHtml = document.documentElement.innerHTML;

            //Just to see there is a value
            alert(theHtml)  

            $(function () {
                $.ajax({
                    type: 'post',
                    url: "/CreatHtmlToPdf/CreatePdf",
                    dataType: "html",
                    data: { HTML: theHtml }
                })
                .done(function (results) {
                    alert("Html data: " + results);
                });
            });
           });

CODE BEHIND

Public Class CreatHtmlToPdfController
    Inherits Controller

    ' GET: CreatHtmlToPdf
    Function Index() As ActionResult

        Return View()
    End Function

    <HttpPost()>
    Function CreatePdf(ByVal HTML As String) As ActionResult

        Dim doc As PdfDocument

        ' read parameters from the webpage
        Dim htmlString As String = HTML

        ' instantiate a html to pdf converter object
        Dim converter As New HtmlToPdf()

        ' create a new pdf document converting an url
        If (HTML <> String.Empty) Then

            doc = converter.ConvertHtmlString(htmlString)


        End If


        ' save pdf document
        Dim pdf As Byte() = doc.Save()

        ' close pdf document
        doc.Close()

        ' return resulted pdf document
        Dim fileResult As FileResult = New FileContentResult(pdf, "application/pdf")
        fileResult.FileDownloadName = "Results_page.pdf"
        Return fileResult

    End Function

    'Declaration
    'Public Property EnablePageMethods As Boolean

End Class

WAI ARIA screenreader not reading dynamically added rows

I've scenario where I am trying to add rows dynamically to a table using Ajax. I've following table structure:

<table class="user-table table" id="usersTable">
    <thead>
      <tr>
        <th class="user-col user-name">Name</th>
        <th class="user-col user-email">Email</th>
        <th class="user-col user-status">Admin</th>
        <th class="user-col user-i-col">Active</th>
        <th class="user-col user-i-col">Actions</th>
      </tr>
    </thead>
</table>

Now I am trying to dynamically add/remove rows to/from table using JavaScript/jQuery. There are basically 2 different ways I am doing this:

  1. looping through JSON data, creating tbody, rows and cell and appending the tbody to target table using JavaScript OR
  2. using $(element).append(HTML) to append the HTML returned by Ajax call.

if I use JavaScript to create tbody, rows and data cells, NVDA correctly reads the added rows Ref: updateTableAsync . So if I add 3 rows to table this way, NVDA will read table with 4 rows and 5 columns, which is correct.

However, if I try to append the returned html directory into table using $.append or $.html, it does not identify the rows that were added dynamically. Ref: updateTableContentAsync

Here is the JSON that is returned:

{"users":[
    {"name":"ABC","email":"ABC@mailcatch.com","admin":true, "active":true,"action":"Remove" },
    {"name":"XYZ","email":"XYZ@mailcatch.com","admin":false, "active":false,"action":"Remove"},
    {"name":"ASDF","email":"ASDF@mailcatch.com","admin":false, "active":true,"action":"Remove"}
    ]
}

(function(global, window, $) {
      'use strict';
      //Accessible Ajax Loading Test
      var AALoadingTest = AALoadingTest || {};
      AALoadingTest.AjaxUtil = (function() {          
          
          
          var makeDataCell = function(row, index, data ) {
            var cell = row.insertCell(index);
            var cellText  = document.createTextNode(data)
            cell.appendChild(cellText);
          };

          var setFocus = function(element, fallbackElement) {
            var focusElement = document.getElementById(element); 
            if(typeof focusElement == 'undefined') {
              focusElement = document.getElementById(fallbackElement);
            }                
            window.setTimeout(function(){
              window.console.log(focusElement);
              focusElement.focus();
            }, 100);
          };

          //Method : 1 Update table content by looping through json data using native Javascript   
          var updateTableAsync = function(url, targetTable, targetContainer, focusContainer, announce) {
            
            //TODO: remove timeout when in prod, need while testing because locally changes are loading too fast
            window.setTimeout( function() {
              $.get(url, function(data){              
                
                var tempTargetTBody = document.getElementById(targetContainer);
                var target = document.getElementById(targetTable);
                var targetTBody = document.createElement('tbody');
                targetTBody.innerHTML = '';
                targetTBody.setAttribute('aria-live', tempTargetTBody.getAttribute('aria-live'));
                // targetTBody.setAttribute('aria-atomic', tempTargetTBody.getAttribute('aria-live'));
                tempTargetTBody.remove();
                targetTBody.setAttribute('id',targetContainer);
                
                $.each(data.users, function(key, value){
                  var row = targetTBody.insertRow(targetTBody.rows.length);
                  makeDataCell(row, 0, value.name);
                  makeDataCell(row, 1, value.email);
                  makeDataCell(row, 2, value.admin ? 'Yes': 'No');
                  makeDataCell(row, 3, value.active ? 'Yes': 'No');
                  makeDataCell(row, 4, value.action);
                });
                target.appendChild(targetTBody);           
              })
            },5000);
          };

          //Method : 2 Update table content by inserting HTML element by looping through JSON returned into table  
          var updateTableHTMLAsync = function(url, targetTable,  targetContainer, focusContainer, announce) {                         
            

            //TODO: remove timeout when in prod, need while testing because locally changes are loading too fast
            window.setTimeout( function() {
              $.get(url, function(data){              
                
                var targetElement = $('#'+targetContainer);
                targetElement.remove();
                targetElement = $('<tbody></tbody>').attr({'aria-live': 'polite', 'id': targetContainer});
                
                $.each(data.users, function(key, value) {
                  window.setTimeout(function() {
                    var row = $("<tr> </tr>");
                      targetElement.append(row);
                      row.append($("<td></td>").text(value.name));
                      row.append($("<td></td>").text(value.email));
                      row.append($("<td></td>").text((value.admin ? 'Yes': 'No')));
                      row.append($("<td></td>").text((value.active ? 'Yes': 'No')));
                      row.append($("<td></td>").text(value.action));
                  },100);
                });      
                $("#"+targetTable).append(targetElement);         
                
              })
            },5000);
          };

          //Method : 3 Update table content by inserting HTML returned into table  
          var updateTableContentAsync = function(url, targetTable,  targetContainer, focusContainer, announce) {                         
            

            //TODO: remove timeout when in prod, need while testing because locally changes are loading too fast
            window.setTimeout( function() {
              $.get(url, function(data){              
                
                var targetElement = $('#'+targetContainer);
                targetElement.remove();
                targetElement = $('<tbody></tbody>').attr({/*'aria-live': 'polite',*/ 'id': targetContainer});
                $("#"+targetTable).append(targetElement);                
                
                targetElement.append($(data));                
              })
            },5000);
          };

          return {
            updateTableAsync: updateTableAsync,
            updateTableHTMLAsync: updateTableHTMLAsync,
            updateTableContentAsync: updateTableContentAsync,
            removeLoader: removeLoader,
            loader: loader
          };
      })();
      
      $("#asyncHTML").on("click", function(e){ 
        e.stopPropagation();
        AALoadingTest.AjaxUtil.updateTableHTMLAsync(
          $(this).attr('data-resource'),
          $(this).attr('data-target-table'),
          $(this).attr('data-target-element'),
          $(this).attr('data-focus-element'),
          true
        );       
        return false;
      });

      $("#asyncJSON").on("click", function(e){ 
        e.stopPropagation();
        AALoadingTest.AjaxUtil.updateTableAsync(
          $(this).attr('data-resource'),
          $(this).attr('data-target-table'),
          $(this).attr('data-target-element'),
          $(this).attr('data-focus-element'),
          true
        );       
        return false;
      });

      $("#asyncHTMLContent").on("click", function(e){ 
          e.stopPropagation();
          AALoadingTest.AjaxUtil.updateTableContentAsync(
            $(this).attr('href'),
            $(this).attr('data-target-table'),
            $(this).attr('data-target-element'),
            $(this).attr('data-focus-element'),
            true
          );       
          return false;
      });


      })(this, window,jQuery);
<link href="http://ift.tt/1mDOveJ" rel="stylesheet"/>
<script src="http://ift.tt/1qRgvOJ"></script>
<script src="http://ift.tt/1h4yM0u"></script>
<main>
      <div class="container">     
        <div class="container-fluid">         
          
          <h1>Dynamic Tables</h1>        
          <p> Load JSON using Ajax get, use JavaScript to create tbody, rows and data cell and append the tbody to table using appendChild</p>
          <br>
            <a class="btn btn-primary async" id="asyncJSON" data-target-table="usersTableJSON"
                role="button" data-target-element="userTableBodyJSON" data-focus-element="asyncContentJSON" 
                href="javascript:;" data-resource="data/users.json">
                Load Users <span class="sr-only">Load json Data</span>
            </a>
          <br>
          <br>
          <div class="panel" id="asyncContentJSON">
            <table class="user-table table" id="usersTableJSON">
            <thead>
              <tr>
                <th class="user-col user-name">Name</th>
                <th class="user-col user-email">Email</th>
                <th class="user-col user-status">Admin</th>
                <th class="user-col user-i-col">Active</th>
                <th class="user-col user-i-col">Actions</th>
              </tr>
            </thead>
            <tbody id="userTableBodyJSON" aria-live="polite"></tbody>            
          </table>
          </div>

          <br>
          <p> Load JSON using Ajax get, use jQuery to create tbody, rows and data cell and append the tbody to table using $.append</p>
          <br>
            <a class="btn btn-primary async2" id="asyncHTML"
                role="button" data-target-element="userTableBodyHTML" data-target-table="usersTableHTML" data-focus-element="asyncContentHTML" 
                href="data/rows.html" data-resource="data/users.json">
                Load Users<span class="sr-only">Load HTML Data</span>
            </a>
          <br>

          <br>
          <div class="panel" id="asyncContentHTML">
            <table class="user-table table" id="usersTableHTML">
            <thead>
              <tr>
                <th class="user-col user-name">Name</th>
                <th class="user-col user-email">Email</th>
                <th class="user-col user-status">Admin</th>
                <th class="user-col user-i-col">Active</th>
                <th class="user-col user-i-col">Actions</th>
              </tr>
            </thead>
            <tbody id="userTableBodyHTML" aria-live="polite"></tbody>
          </table>
          </div>

          <br>
          <p> Load JSON using Ajax get, use JavaScript to create tbody, rows and data cell and append the tbody to table using $.html</p>
          <br>
            <a class="btn btn-primary async2" id="asyncHTMLContent"
                role="button" data-target-element="userTableBodyHTMLContent" data-target-table="usersTableHTMLContent" data-focus-element="asyncContentHTMLContent" 
                href="data/rows.html" data-resource="">
                Load Users<span class="sr-only">Load HTML View</span>
            </a>
          <br>
          <br>
          <div class="panel" id="asyncContentHTMLContent">
            <table class="user-table table" id="usersTableHTMLContent">
            <thead>
              <tr>
                <th class="user-col user-name">Name</th>
                <th class="user-col user-email">Email</th>
                <th class="user-col user-status">Admin</th>
                <th class="user-col user-i-col">Active</th>
                <th class="user-col user-i-col">Actions</th>
              </tr>
            </thead>
            <tbody id="userTableBodyHTMLContent" aria-live="polite"></tbody>
          </table>
          </div>
        </div>        
      </div>
      <div id="overlay" class="hidden">          
        <span class="visuallyHidden" id="loadingMessage" role="status" aria-hidden="true"></span>
      </div>        
    </main>

One thing that I suspect here is: when I manually add rows one by one, NVDA is aware of individual DOM change, however, when I update the innerHTML all it know is "one update in DOM". Please let me know if someone has faced similar issue and how you fixed that.

Thanks

Using ':hidden' selector to find hidden elements in jquery

In jQuery, I can use $(':hidden') to find hidden elements, but I don't want to include the 0 size elements (width=0 and height=0).

How to achieve this?

I can't just judge if it is 0 size, because if one of its parents is hidden, I also want to select it.

For example:

<img id="e1" width="0" height="0" />
<div style="display:none;">
    <img id="e2" width="0" height="0" />
</div>

I want to select "e2",but not "e1".

AngularJS/jQuery - Update Scope

I am working on a legacy system that uses jQuery and had to add AngularJS for a particular feature, however im having issues updating the scope.

Basically, we have a dropdown and when you select an option, we're firing an Ajax call to get an array or objects. This array of objects is then being stored in a global variable, say var myObjs. Basically using the ng-repeat service from Angular, I need to loop through these and render a list.

I am new to Angular, so i'm not sure if this is the way to be done. What I am doing is setting the scope in this way:

$scope.myObjs= myObjs;

However, by doing so, the scope is not changing at all.

Can someone tell me how this can be done? I tried to look around but am finding it a bit hacky having a hybrid of AngularJS & jQuery on the same page.

EDIT: adding sample snippet. Basically on change of the dropdown im firing an ajax call, and store the response (which is an array of objects) in myObjs variable. Then I am trying to set the scope to the value of this variable. Regarding the way I am bootstrapping Angular, this is due to a limitation of the legacy system, which is over 8 years old.

var myObjs = null;


$(function() {
  $("#myHeader").on("change", "#mySelect", function() {
    // perform Ajax Call
  });

});

function ajaxCallback(data) {
  myObjs = data;
}

var myModule = angular.module("GetObjsModule", []);
myModule.controller("MyController", function($scope) {
  $scope.objs = myObjs;
});

angular.element(document).ready(function() {
  var myDiv = $("#myDiv");
  angular.bootstrap(myDiv, ["GetObjsModule"]);
});
<script src="http://ift.tt/1mQ03rn"></script>
<script src="http://ift.tt/Sw98cH">
</script>

<div id="myHeader">
  <select id="mySelect">
    <option value="1">Value 1</option>
    <option value="2">Value 2</option>
    <option value="3">Value 3</option>
  </select>
</div>

<div id="myDiv">
  <ul ng-controller="MyController">
    <li ng-repeat="x in objs">
      <div>
        {{x.name}} {{x.surname}}: {{x.tel}}
      </div>
      <div>
        <p>
          Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut odio. Curabitur malesuada. Vestibulum
          a velit eu ante scelerisque vulputate.
        </p>
      </div>
    </li>
  </ul>
</div>

trigger is not working in angular js

trigger is not working in angular js

 $http({
     method: 'POST',
     url: partial_path + '/test.php',
     data: 'action=create&d=' + localStorage.getItem('lastid'),
     headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
     }
 }).success(function(data) {
     if (data != "error") {
         var url = partial_path + '/' + data;
         //alert(url);
         $("#hreflink").attr("href", url);
         $('#hreflink').trigger('click');
     }
 });

Hi i am new to angular js

Trigger event is not working in angular js ajax loaded template

Please help to fix this issue

Updated

window.open(url, '_blank');

window.open is working but its ask popup browser alert

Codebehind function not being called by Ajax POST

My Ajax post is not running my code behind method and thus not returning any data.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="AspTest.Test" %>

Test.aspx (Ajax script)

    <script>
                $(".avatarThumb").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "Test.aspx/MyMethod",
                        //data: {"s": "Some data passed through" },
                        //contentType: 'application/json; charset=utf-8',
                        //dataType: 'json',
                        success: function (response) {
                            alert(response.d); //Returns "undefined"
                        },
                        failure: function(response) {
                            alert(response);
                        }
                    });
                });
            </script>

Removing contentType and dataType does reach success but does not run the codeBehind method. With contentType and/or dataType active it will not reach success nor failure. FF firebug does not display any errors.

*Test.aspx.cs CodeBehind method

        [System.Web.Services.WebMethod]
        public static string MyMethod()
        {
(*)         Debug.WriteLine("MyMethod called!"); // (*) Breakpoint never reached

            return "Method called!";
        }

extract vimeo video id from the url

Though this question is available on SO, I am facing a little problem.I failed to extract the vimeo id using vimeo regex used here: Vimeo Regex

My codes I,m using now:

function vimeoProcess(url){
   var vimeoReg = /https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/;
   var match = url.match(vimeoReg);
   if (match){
      console.log(match[3]);
   }else{
      return "<span class='error'>error</span>";
   }
}

It does not consoles any thing. Can any one help?

change img size inside iframe with jquery

I'm using an adserver on my website. All adds are using iframe, and I'm trying to target the img (the first one with width = 728 & height = 90) inside the iframe to change its size (width & height). I've been able to target the body (changing its background color to test), but I can't target the image to change its size. here is the iframe code, I need to target the iframe object, and not the iframe class, because the class changes every time.

<div class="insert_pub">
<iframe id="a0811af3" width="" height="90" frameborder="0" scrolling="no" src="/www/delivery/afr.php?zoneid=3&cb=INSERT_RANDOM_NUMBER_HERE" name="a0811af3">
#document
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html lang="en" xml:lang="en" xmlns="http://ift.tt/lH0Osb">
<head></head>
<body>
<a href="/www/delivery/ck.php?oaparams=2__bannerid=212__zoneid=3__cb=9b2dbdb22f__oadest=http%3A%2F%2Fthebayfestival.fr%2F" target="_blank">
    <img src="/www/images/c34d3222b19118f97aa99e76310c70fe.jpg" alt="" title="" height="90" border="0" width="728">
</a>
<div id="beacon_9b2dbdb22f" style="position: absolute; left: 0px; top: 0px; visibility: hidden;">
    <img src="/www/delivery/lg.php?bannerid=212&amp;campaignid=176&amp;zoneid=3&amp;loc=http%3A%2F%2Fwww.mmdwc.com%2Fmagazine%2F&amp;cb=9b2dbdb22f" alt="" style="width: 0px; height: 0px;" height="0" width="0">
</div>
</body>
</html>
</html>
</iframe>
</div>

here is what I've tried, but it's not working :

function iframe_insert_size() {
  $(".insert_pub iframe").contents().find("img").css({"width":624, "height" : 77});
}

can anybody help me with this ?

thanks a lot,

Submitting post between ajax and php

I'm a newbie in the world of php and I was trying to learn it with a simple page. I've created an html form and I want to send data using ajax but it still POST http://localhost/Home.php 500 (Internal Server Error)

In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)

This is my form (Home.php)

<div id="displayForm">

<form method="post" id="selectForm">
        <?php
        include ("Database.php");

        $Database = new Database( "localhost", "root", "1234");
        $Database->connectToServer();
        $Database->connectToDatabase("test");
        $Tables = $Database->countTable();
        foreach($Tables as $column) {
            echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " .  $column;
        }
        ?>
    <input type="submit" class="submit" name="createSelect">
</form> </div>

The php in the form is only for create the button with the name of the tables.

In the same file (Home.php)

<?php
 include 'ChromePhp.php';
 ChromePhp::log("corretto");
echo "ok";
?>

In the file Home.php, in the head section I've included all jquery library and the js file

<script src='jquery-1.10.2.min.js'></script>
<script src='Script.js'></script>

And this is my ajax file

$(document).ready(
    function() {
        $("#createTable").click(goCreate);
        $("#displayTable").click(goDisplay);
        $('#selectForm').submit(goSelect);
        $("#createForm").hide();
        $("#displayForm").hide();
    }
);

function goCreate(data) {
    $("#createForm").show();
    $("#functions").hide();
}

function goDisplay(data) {
    $("#displayForm").show();
    $("#functions").hide();
}

function goSelect() {
    var selectedTable = $("#selectQuery:checked").val();
    console.log($("#selectQuery:checked").val());


    $.ajax({
        url: "Home.php",
        type: "POST",
        dataType: "html",
        data: {
            'select': 'display',
            'table': selectedTable
        },
        success: function(msg) {
            console.log(msg);
        },
        error: function(xhr, desc, err) {
            console.log("error");
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }

    }); // end ajax call
    return false;
};

How do I update the location field when I chnge the latitude, longitude coordinates manually?

I am using jquery location picker plugin to take the entry of user's location through a map.

The problem that I 'm facing is that when I change the lat, long coodinates manually, the location field does not shift accordingly to the correct position however the marker does.

What is the solution?

Here is the map that I'm using http://ift.tt/1HAeglQ

JQgrid file upload with form edit

I have JQgrid with form edit.

 jQuery("#tblPriceListUpload").jqGrid({
        url: $('#tblPriceListUpload').attr("RequestUrl"),
        postData: { PriceListType: SelectedPriceListType },
        datatype: "json",
        mtype: "Get",
        hoverrows: false,
        ajaxGridOptions: { timeout: 30000 },
        colNames: PriceListColName,
        colModel: PriceListColModel,
        cmTemplate: { editable: true },
        rowNum: 10,
        hidegrid: false,
        rownumbers: true,
        pager: '#PriceListGridPager',
        viewrecords: true,
        caption: "Price List ",
        height: 'auto',
        scrollOffset: 0,
        gridview: true,
        shrinkToFit: true,
        autoencode: true,
        loadonce: true,
        ignoreCase: true,
        enableClear: true,
        width: '1000',
        beforeRequest: function () {

            //responsive_jqgrid($(".jqGrid"));
        }
    });

    $('#tblPriceListUpload').jqGrid('filterToolbar', { searchOnEnter: false, enableClear: false, defaultSearch: "cn", stringResult: true });

For Form Add

  $("#tblPriceListUpload").jqGrid('navGrid', '#PriceListGridPager',
           { edit: true, add: true, del: true, refresh: true, view: false, search: false },
           { //Edit Code here
               }, {

               caption: "",
               title: "Add Attachment",
               id: "add_Attachment",
               buttonicon: "ui-icon-plus",
               position: "first",
               url: 'AddPriceList',
               recreateForm: true,
               onclickSubmit: function (response, postdata) {
                   debugger;
                   if (jqXHRData) {
                       //jqXHRData.submit();
                       $("#Form").submit();
                       $("#FormError").remove();

                   }
               },
               beforeShowForm: function (form) {
                   $("#PriceListType").val(SelectedPriceListType);
                   $("#tr_PriceListType").hide();
                   $('#FileName').fileupload({
                       replaceFileInput: false,
                       dataType: 'json',
                       url: 'AddPriceList',
                       change: function (e, data) { },
                       add: function (e, data) {
                           jqXHRData = data
                       },
                       done: function (event, data) {

                           alert(data.result.message)
                           $("#cData").trigger('click');
                           $("#tblPriceListUpload").setGridParam({ datatype: 'json', page: 1 }).trigger("reloadGrid");
                           jqXHRData = null;
                       },
                       fail: function (event, data) {

                           if (data.files[0].error) {
                               alert(data.files[0].error);
                           }
                       }
                   });
               }

           }, {});

And Col Model Below

     var PriceListColModel = [{ name: 'DisplayDescription', index: 'DisplayDescription', align: 'center', editable: true, },
           {
               name: 'Header', index: 'Header', width: 95, align: 'center', formatter: 'select', editable: true,
               edittype: 'select', editoptions: { value: HeaderList, defaultValue: 'HP Oct 12 - GOs' },
               stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + HeaderList }
           },

    {
        name: 'OneSeriesPerPage', index: 'OneSeriesPerPage', align: 'center', formatter: 'checkbox', edittype: 'checkbox',
        editoptions: { value: "true:false", defaultValue: "true" }, editable: true
    },
{
    name: 'EnvironmentCode', index: 'EnvironmentCode', search: true, editable: true,
    edittype: 'select', editoptions: { value: EnvList, defaultValue: 'AFI' },
    stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + EnvList }
},
{
    name: 'FileName', index: 'FileName', edittype: 'file', editable: true,
    edittype: 'file',
    editoptions: {
        enctype: "multipart/form-data"
    }, search: true
},
    {
        name: 'PriceListType', index: 'PriceListType', align: 'center', hidden: true, editrules: {
            required: true,
            edithidden: true
        }
    }];

In "OnclickSubmit" event of "AddPriceList" if i am posting jqXHRData.submit(); If Check Box column is false it is not sending the data to controller. If true, it is sending the data to controller.

If i am posting the form $("#Form").submit(); I am not getting the file in Controller.

Please help on this issue.

Chomsky Normal Form using JavaScript : Stuck

I have been trying to implement a web application that converts the given context free grammar into its Chomsky Normal Form (CNF). The CodePen link to the same is http://ift.tt/1HAeeud

The only region where I am stuck is breaking down the rules of form S -> aAb into further nonterminals and terminals. Can anyone help me with an implementation algorithm regarding the same?

jquery function for getting div inside row Table

I have a Datalist with three columns or fields: Column1: Some data Column2: Linkbutton Update Column3: div "divCheck", by default it's hide.

<asp:DataList ID="MyDataList" runat="server" EnableViewState="True">
      <HeaderTemplate>
      </HeaderTemplate>
      <ItemTemplate>
          <table width="100%">
              <tr id="ItemRow" runat="server">
                  <td >
                      <%# DataBinder.Eval(Container.DataItem, "some_data")%>
                  </td>
                  <td >
                      <asp:LinkButton Text="Update" class="lnk_showCheck" CommandName="update" Runat="server" ID="update"   />
                  </td>
                  <td >
                      <div id="divCheck" style="display: none">Check</div>

                  </td>
              </tr>
          </table>
      </ItemTemplate>

</asp:DataList>

The idea is that when clicking linkbutton on any row, it has to trigger a server side function and call jquery function ShowCheck.

Protected Sub MyDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles MyDataList.ItemCommand

        If e.CommandName = "update" Then
            Dim script As String = "<script language='javascript'> ShowCheck();</script>"
            Page.ClientScript.RegisterStartupScript(Me.[GetType](), "ShowCheck", script, False)

        End If

    End Sub

Jquery ShowCheck() has to show divCheck in that row.

<script type="text/javascript">

        function ShowCheck() {

            //alert($(this).get(0).tagName);
            $('div', $(this).closest("td").next()).show();
            };

    </script>

Problem is that $(this) is passed as an undefined object. It should be passed as a LinkButton object inside DataList.

Is that possible? How could jquery find divCheck in Table row when is triggered from server side function?

Track JS CSS Asset Errors on page load

Is it possible to track the number of errors and warning thrown by a browser on page load using javascript?

For example CSS Assets missing or images missing or js script errors? I don't need a detailed log but maybe a count of each type of error.

Like a count of CSS, Assets missing and JS Errors?

This needs to be tracked using JS.

How to fix Foundation.js moving reveal modal html from backbone view

I'm developing a website with backbone.js, and foundation.js. I create a backbone parent view, and append a backbone child view to it.

    this.myProfileModalView = new MyApp.Views.MyProfileModalView();
    this.$el.append(this.myProfileModalView.render().el);

This child view contains the html for foundation reveal modal.

<div id="profileModal" class="reveal-modal medium" data-options="close_on_background_click:false;" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog" >

When the site loads the modal is correctly appended in the html as a child. However, when I click on the open modal button, the modal html suddenly gets placed just before the tag. This is making backbone events to not function, and also this.$el comes up null.

How can I fix this issue so that the appended view stays at the same location?

Fade in and Fade Out Text in DIV - Remove Loop

I have created a DIV with 3 different quotes fade in and fade out. I am using below JQuery code for the same.

(function() {
var quotes = $(".changetxt");
var quoteIndex = -1;
function showNextQuote() {
    ++quoteIndex;
    quotes.eq(quoteIndex % quotes.length)
        .fadeIn(1000)
        .delay(4000)
        .fadeOut(500, showNextQuote);
}
showNextQuote();
})();

HTML CODE

<div class="toptext">
    <div class="changetxt">
        ”The simple act of paying positive attention to<br> 
        people has a great deal to do with productivity”
        <p>- Tom Peters</p>
    </div>

    <div class="changetxt">
        ”If you deprive yourself of outsourcing and your competitors<br> do not, you are putting yourself out of business”
        <p>- Lee Kuan Yew</p>
    </div>

    <div class="changetxt">
        ”Focus on being  PRODUCTIVE<br>
        instead of busy”
        <p>- Tim Ferris</p>
    </div>
</div>

It is working perfect but I don't want to loop, There are 3 quotes, so as soon as it shows last (third) quote it should stop animation and no loop.

How can I achieve this?

row header and column header for a particular cell in table

How to take corresponding row header and column header for a particular cell in table? I have table and i wanted to take the corresponding column header and row header of that cell when clicked

Timing and speed of multiple sliding divs

Please see this fiddle I have set up.

You are first confronted by three links. Each link triggers divs to slide out.

  1. The link 'john smith' slides out and in at the speed we want. When it slides out the first line slides out then when that is completed the second line slides down as though coming from the first. When it slides back it does the same motion at the same speed but reverse i.e.. the second line slide back up first and then when that is completed the first line slides back to the left.

  2. When you click on the work link and menu slides out in the same manner as the bio. Also there is a sub menu that slides out when on clicks on item 2.

  3. When the user clicks on the contact link one line slides out.

What we need to achieve is this; when any div is open and another link is clicked on, the visible div slides back in reverse to how they slid in. We have almost achieve this, however, the code is not quite right as the divs are not sliding back in at the same speed and in the right order, they simply slide back fast. For example, if one has clicked on 'work' and the 'item 2' link, and then you select 'contact' the opened div slide back very quickly. What I need to achieve is that they slide back in reverse to how they slid out.

I know this sounds very complicated and if I can answer any questions to make it clearer I will.

Thanks

$('#bio-line-1').animate({width: 'hide'});
$('#contact-info').animate({right: 'hide'});
$('#bio-line-2').slideUp("fast");
$('#black-div, #black-credits, #igna-1-div, #igna-1-credits, #igna-2- div, #igna-2-credits, #fatal-div, #fatal-credits').fadeOut('100');

});

Ajax call onSubmit not working

I have a log-in form. Before do the log-in I would like to make sure that username and password are true.. I am trying to achieve this with ajax, but so far it is not working..

in my form I am calling the function check_user onSubmit. This is my code.

    function check_user(e){
        var username = $('#username').val();
        var password = $('#password').val();

        if(username.length>1 && password.length>1){
        e.preventDefault(); // I added this but still it is not working
        alert('alive'); // this is working          

                jQuery.ajax({
                    type : "POST",
                    url : "check_user.php",
                    data : 'username=' + username +"&password=" + password,
                    cache : false,
                    success : function(response) {
                        if (response == 1) {
                        return true;                    
                        } else {        
                        $('#username').css('border', '2px red solid');
                        document.getElementById("username").placeholder = "Wrong username or password";
                        $('#password').css('border', '2px red solid');
                        document.getElementById("password").placeholder = "Wrong username or password";                     
                        return false;                   
                        }
                    }
                });     
        }else{
//this is working
            $('#username').css('border', '2px red solid');
            document.getElementById("username").placeholder = "Wrong username or password";
            $('#password').css('border', '2px red solid');
            document.getElementById("password").placeholder = "Wrong username or password";
            return false;   
        }
    }

In my PHP file check_user.php I have also this code:

$fp = fopen("debug.txt", "a") or die("Couldn't open log file for writing.");
        fwrite($fp, PHP_EOL ."inside");
        fflush($fp);
        fclose($fp);

No debug.txt is created so I assume that the ajax call never happens..

I use the same ajax code when doing the registration to check if the username or email already exists in the database, and the ajax there is working ok. In my example the ajax call never happens and it goes straight to the action="login.php"

understanding the usage of e inside carasoul.js

hey guys i was just going through the code of carousel.js and i am a little bit confused , now we it comes to attaching events i ofte see code as follows ::

$('a').click(fuction(e){
    if(e.target.targetNode == $(this)[0])
   //do something
});

I am still a bit confused , who is passing the e ? WHO really is passing that e inside the function ?

also in the plugin code i see things like the below :

Carousel.prototype.keydown = function (e) {
  if (/input|textarea/i.test(e.target.tagName)) return
  switch (e.which) {
    case 37: this.prev(); break
    case 39: this.next(); break
    default: return
  }

an event handler is attached like so :

  this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))

another example is here :

  Carousel.prototype.pause = function (e) {
    e || (this.paused = true)

    if (this.$element.find('.next, .prev').length && $.support.transition) {
      this.$element.trigger($.support.transition.end)
    }
    this.interval = clearInterval(this.interval)
    return this
  }

Who is passing e inside these functions , from where is it coming from ? i have absolutly no clue , i have been using JS for a while now , but this still baffles me . can somebody really clear this doubt for me once and for all ?

P.S. I have seen this answer on SO , but it does't answer the questions i have asked . I understand that e is in a way a object with differentv properties that we can access.

fade in and move down

I have an animation set on my homepage headline using css to make it fade in when the page loads. I have seen on other sites a really impressive animation that will fade in the title and move it down slightly. How would i have to alter my code to be able to achieve this?

<div class="homepage">
    <div class="headline">
        <h1><span>WELCOME</span></h1>
    </div>
    <div class="subheadline">
        <h1>
            <span>To the home of</span>
        </h1>
    </div>
    <div class="subheadline">
        <h1>
            <span>Multimedia Journalist</span>
        </h1>
    </div>
    <div class="subheadline">
        <h1>
            <span>Dan Morris</span>
        </h1>
    </div>

    <a href="#contact" class="smoothScroll" id="contactlink">Let's talk</a>
    <div class="down-link">
        <a class="w-downlink" href="#about">
            <i class="fa fa-chevron-down"></i>
        </a>
    </div>
</div>

.headline {
    height: auto;
    width: 75%;
    margin-left: 78px;
    margin-top: 120px;
    margin-right: auto;
    font: 200 18px/1.3 'Roboto', 'Helvetica Neue', 'Segoe UI Light', sans-serif;
    font-size: 12px;
    font-weight: 200;
    color: #676767;
    text-align: left;
    opacity: 0;
}

@-webkit-keyframes fadeIn {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

@keyframes fadeIn {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

.fadeIn {
    -webkit-animation: fadeIn 1s ease-in .5s both;
    animation: fadeIn .1s ease-in .5s both;
}

Exclude Select Click via Jquery

Im trying to trigger an action when I click anywhere on a tr with a class of parent. Excluding when I click on one of the dropdown boxes.

$('tr.parent')
    .css("cursor", "pointer")
    .click(function (e) {
        if($(e.target).not('select')){
            // do something
    }

Im trying the following but this is not working.

http://ift.tt/1dBzsAz

Getting row id in Jquery

I have a data table which I retrieved from MySQL table. Before begin delete action for each row I want to give alert when delete button is pressed after selection of row. this is my java script code.

$(function() {
    $('#dataTables-example tbody').on('click', 'tr', function() {
        var name = $('td', this).eq(0).text();
        $('#btnDeleteRow').click(function(e) {
            alert('You are going to delete ' + name + '\'s row');
        });
    });
});

It works. But the problem is I want only the last clicked row id to alert. My code gives all the row ids' i have clicked before I refresh the page. As I am new to jQuery please help me. Thanks.

ZendX_JQuery_Form_Element_DatePicker doesn´t work

My datepicker doesn't work. I don't get any errors and instead of the datepicker appearing, my field looks like a dropdown and shows the formerly used dates.

I added to my bootstrap:

protected function _InitAutoload()
    {
        $view= new Zend_View();
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $view->addHelperPath(’ZendX/JQuery/View/Helper/’, ‘ZendX_JQuery_View_Helper’);
        $viewRenderer->setView($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
    }

I changed my datefield in my formclass like follows:

$datum= new ZendX_JQuery_Form_Element_DatePicker("datum", '',
                    array('defaultDate' => date('Y/m/d', time()))); 

My formclass extends ZendX_JQuery_Form.

In my layout.phtml I added:

$this->jQuery()->setLocalPath('http://localhost/zend/js/jquery/jquery-1.2.6.js')
 ->addStylesheet('http://localhost/zend/js/jquery/themes/ui.datepicker.css');
echo $this->jQuery();

Where is my error? Is there something missing somewhere?

slick slider not initializing in Internet Explorer 8

This is the code I have, any reason why this might be? It's just not initalising.

<div class="slider-banner slick-slider">
    <div class="slide1 slide slick-slide">
        ...
    </div> 
    <div class="slide2 slide slick-slide"></div> 
    ...

    <script src="http://ift.tt/1h847p1"></script>
    <script src="../scripts/slick.min.js"></script>

$('.slider-banner').slick({ 
    dots: false,
    infinite: true,
    speed: 600,
    mobileFirst: true,
    slidesToShow: 3,
    slidesToScroll: 3,        
    onInit: function() {
        $('.slider-banner').addClass("loaded");
    },
    responsive: [{
        breakpoint: 1280,
        settings: {
            slidesToShow: 5,
            slidesToScroll: 1,
        }
    }, {
        breakpoint: 1600,
        settings: {
            slidesToShow: 7,
            slidesToScroll: 1,
        }
    }]
});

jQuery check if select field changed

I would like to make a jQuery check if a select field was changed. If it changes, set an alert message (has changed), if returned to default, set another alert message (default value).

$('select').on('change',function () {
    var isDirty = false;

    $('select').each(function () { 
        var $e = $(this);      
        if (!$e[0].options[$e[0].selectedIndex].defaultSelected) {
        isDirty = true;
        }    
    });

    if(isDirty == true) { 
        alert("has changed");
    } else {
        alert("default value");          
    }
});

Please advise if this is the proper way.

Cordova - (Phonegap) get Device DPI and Density Pixels

I am developing a phonegap (cordova) project and I want to get the DPI of the device. Is this possible?

In Android native JAVA API there is a Class named DisplayMetrics which provides getDisplayMetrics().xdpi/ydpi method to get device DPI.

Is there any method to get device DPI in Cordova or Phonegap ?

Loop over json list generated by oracle procedure

I'm trying to run a loop over a json list generated by oracle procedure:

Control:

  public JsonResult GetLOVDivCount()
        {
            return Json(SearchRep.GetDivCount(), JsonRequestBehavior.AllowGet);
        }

Model:

        public static GetLovListModel GetDivCount()
        {
            var p = new OracleDynamicParameters();
            p.Add("p_output", dbType: OracleDbType.RefCursor, direction: ParameterDirection.Output);
            string spName = "p_get_div_count";
            GetLovListModel glist = new GetLovListModel();
            using (var grid = DB.GetMultiGrid(spName, p: p))
            {
                glist.GetDivCount = grid.Read<GetDivCount>().ToList();
            }
            return glist;
        }

View:

$.ajax(
         {
             url: '@Url.Action("GetLOVDivCount")',
             type: 'GET',
             datatype: 'json',
             success: function (result) {
                 **jQuery.each(result, function(key,val){
                     $("#tDivCount").last().append("<tr><td>" + result + "</td><td>New row</td><td>New row</td></tr>");**
                 })
                 
             }
         });

But the table is showing only null data!? Please advise.

Get all child attributes using parent id jquery

how do i get all child attributes by parent id and return an array of object example

I want a result like this:

pat_101 = adm_01-adm01, adm_01-adm02, adm_01-adm03
pat_102 = adm_04-adm04, adm_05-adm05, adm_06-adm06
pat_103 = adm_07-adm07, adm_08-adm08, adm_09-adm09

From this html:

<div>
   <ul>
     <li id="pat_101">
       <ul>
         <li id ="adm_01" title="adm101"></li>
         <li id ="adm_02" title="adm102"></li>
         <li id ="adm_03" title="adm103"></li>
       </ul>
     </li>
     <li id="pat_102">
       <ul>
         <li id ="adm_04" title="adm104"></li>
         <li id ="adm_05" title="adm105"></li>
         <li id ="adm_06" title="adm106"></li>
       </ul>
     </li>
     <li id="pat_103">
       <ul>
         <li id ="adm_07" title="adm107"></li>
         <li id ="adm_08" title="adm108"></li>
         <li id ="adm_09" title="adm109"></li>
       </ul>
     </li>
   </ul>    
<div>

Thank you

Jquery change animation effect under 767

How can I make an animation effect change under 767 screen width? I have a div what contains some regional information, but it is not fit under 767. I changed the absolute div to relative with css. It works good, but looks ugly with the fadein effect. I'd like to change it to SlideDown.

Is there any good solution for this?

Thanks all help!

Here is my code:

$(window).resize(function() {
      if ($(window).width() < 767) {
        $('#regio-settings').click(function() {
            $('#regiobox').slideDown(300, "linear");
            return false;
        });
        $('#regiobox-close').click(function() {
            $('#regiobox').slideUp(300, "linear");
            return false;
        });


    } else {
         $('#regio-settings').click(function() {
            $('#regiobox').fadeIn(300, "linear");
            return false;
        });
        $('#regiobox-close').click(function() {
            $('#regiobox').fadeOut(300, "linear");
            return false;
        });
    }



    });

Fullcalendar returning epoch time values to the database

I am using fullcalendar jquery plugin for my page.When i'm inserting new events using the fullcalendar plugin.., its returning me epoch time values instead of UTC timedate values.

Below is the code that inserts new data into the database on clicking a date.

    calendar.fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar
        drop: function() {
            // is the "remove after drop" checkbox checked?
            if ($('#drop-remove').is(':checked')) {
                // if so, remove the element from the "Draggable Events" list
                $(this).remove();
            }
        },

        eventSources: [

            {

                url: '/v1/calendar/',
                type: 'GET',
                dataType:'json',


            },
           calendar.fullCalendar( 'addEventSource', response )
        ],

        selectable: true,
        selectHelper: true,
        select: function(start, end, allDay) {

            bootbox.prompt("New Event Title:", function(title) {
                var people_id=1;
                //var title=event.title;
                //var start=event.start;
                //var end=event.end;

                if (title !== null) {
                    calendar.fullCalendar('renderEvent',
                            {
                                people_id:people_id,
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },

                    true // make the event "stick"


                            );






                            $.ajax({
                                 url: '/v1/calendar',
                                 data: 'people_id='+people_id+'&title='+title+'&start='+start+'&end='+end,

                                 type: 'POST',
                                 dataType: 'json',
                                 success: function(response){
                                     bootbox.alert("Event Created!");

                                   console.log(response);
                                 },
                                 error: function(e){
                                   console.log(e.responseText);
                                 }
                               });  

                }
            });

The event is successfully added into the database...but the time is in epoch format.

the console response I'm getting is given below:

     {people_id: "1", evt_description: "testing", date1: "1431388800000", date2: "1431475200000", event_id: 4}

I'm using laravel framework at the backend I'm attaching my CalendarController below:

    <?php

class CalendarController extends \BaseController {

/**
 * Display a listing of calendar
 *
 * @return Response
 */
public function index()
{
    $event = DB::table('events')

    ->leftJoin('people','people.people_id','=','events.people_id')  
    ->leftJoin('people_roles','people_roles.people_id','=','events.people_id')      
    ->get(array('events.people_id','events.event_id','events.evt_description','events.date1','events.date2','events.time'));    
    //return View::make('people.show', compact('address'));
    //return Response::json($event);
    $id=array();
    $title=array();
    $start=array();
    $end=array();
    $i=0;
    foreach ($event as $events)
        {

            $id[$i]=$events->event_id;
            $title[$i]=$events->evt_description;
            $start[$i]=$events->date1;
            $end[$i]=$events->date2;
            $i++;           
        }
    return Response::json(array('id'=>$id,'title'=>$title,'start'=>$start,'end'=>$end));
}

/**
 * Show the form for creating a new calendar
 *
 * @return Response
 */
public function create()
{
    return View::make('calendar.create');
}

/**
 * Store a newly created calendar in storage.
 *
 * @return Response
 */
public function store()
{
    $events= Input::get('type');
    $events= new Events;
    $events->people_id = Input::get('people_id');
    $events->evt_description =Input::get('title');
    $events->date1 =Input::get('start');
    $events->date2 =Input::get('end');
    //$events->time =Input::get('time');

    $events->save();


    return Response::json($events);
    //return Redirect::route('calendar.index');
}

/**
 * Display the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $calendar = Calendar::findOrFail($id);

    return View::make('calendar.show', compact('calendar'));
}

/**
 * Show the form for editing the specified calendar.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $calendar = Calendar::find($id);

    return View::make('calendar.edit', compact('calendar'));
}

/**
 * Update the specified calendar in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    //$type=Input::get('type');
    $event_id= Input::get('event_id');
    $title= Input::get('title');
    $roles = DB::table('events')
                ->where('event_id','=',$event_id )
                ->update(array('evt_description' => $title));
    return Response::json(array('id'=>$event_id,'title'=>$title));



}

/**
 * Remove the specified calendar from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy()
{
//  Calendar::destroy($id);
$event_id= Input::get('eventid');
DB::table('events')->where('event_id','=',$event_id)->delete();

return Response::json($event_id);

//  return Redirect::route('calendar.index');
}

}

How to add another statement in IF with JQUERY [duplicate]

This question already has an answer here:

I combine primefaces with SVG and onclick. If I write just the first part "if($(window).width()>800){PF('dlg_p').show();}" there is no problem, but if I want to add another restriction don't work.

<svg width="200" height="210" onclick="if($(window).width()>600)&&($(window).height()>600){PF('dlg_s').show();}">

But the console gives me an error I can't solve:

Error Traced [line 313] The entity name must appear immediately after '&' in the entity reference.

jQuery - Help to define invalid date in age gate

I'm setting up an age gate for a clients page that contains alcohol. The visitor must fill in day, month and birthyear and also country. The form is connected to minimum purchase ages in different countries.

I've managed to get the form to redirect to startpage if they are old enough or display "Sorry, you're not old enough to enter this site" if they are too young. So far so good.

But I also need the form to display "Please enter a valid date of birth" if they put in something that isn't an actual date.

Is there a way to define var invalidDate =

invalidDate could be if they enter letters instead of numbers, but also much appreciated would be if invalid for Day is anything that isn't between number 1-31, for month anything that isn't number 1-12 and for year anything that doesn't start with 19XX or 20XX.

Sorry if I'm being unclear...

The form as it is right now (most countries removed because the list was so long):

<script type="text/javascript">

var 
$ = $||jQuery;
countries = {
    "Sweden": 20,
    "Denmark": 18,
    "Other": 21,
}

$(document).ready(function() {
    $("form").submit(function(e) {
        e.preventDefault();
        var day = parseInt($("input[name=day-796]").val());
        var month = parseInt($("input[name=month-664]").val() - 1);
        var year = parseInt($("input[name=year-262]").val());
        var dateOfBirth = new Date(year, month, day, 0, 0, 0, 0);
        var ageDifMs = Date.now() - dateOfBirth.getTime();
        var ageDate = new Date(ageDifMs); 
        var age = Math.abs(ageDate.getUTCFullYear() - 1970);
        var country = $("select").val();
        var hasAccess = age >= countries[country];
        var noAccess = age <= countries[country];
        if (hasAccess) {
            window.location.href = "www.startpageURL.com";
        } else if (noAccess) {
            document.getElementById("warning_output").innerHTML = "Sorry, you're not old enough to enter this site.";
        }
    })
})
</script>

Any suggestions would be much appreciated!

Cannot set the focus on an iframe after load with jQuery

I am having a button in my page and when I click it I want an iframe to load and set the focus on it. So after loading the iframe I want to be able to push the keyboard arrows and move inside the iframe and not on the whole page.

I have the iframe on html like this:

 <iframe id="myiframe" width="1280" height="720" data-src="" src="about:blank" </iframe>

then on css:

 iframe#myiframe{
    width: 100%;  
    position: absolute;
    top: 0;
 }

and then I am using this jQuery

 var iframe = $("#myiframe");
 $(document).bind('click', function(e) {
      iframe.fadeIn();
      iframe.attr("src", iframe.data("src")); 

      setTimeout(function(){
            iframe[0].contentWindow.focus();
            iframe.contents().find("body").focus(); 
        }, 100);
 });

It loads just fine but when I am using the keyboard the whole page starts moving. The only way I managed to fix it is to set the position to fixed for the whole body.

 $("body").css("position","fixed");

But if possible I would prefer another way that that. Thanks in advance.

Javascript Hover and Toggle

My navigation is hidden and hover is showing but disappearing immediately, I want the navigation to show on hover and display: none on mouse out of the element

$(document).ready(function(){
    $("#nav-holder").hover(function () {
        $("nav").animate({height: 'toggle'});
    });
});

Collapse row on mouse click

I found one very good example of Collapsible Content on Internet but unfinished.

                          <div class="container faq_wrapper">
                                    <div class="row">
                                        <div class="span10 offset1">
                                            <p>
                                                &nbsp;</p>
                                            <div class="faq-all-actions">
                                                <a class="faq-expand" onclick="jQuery('.answer-wrapper').css('display','block');">Expand All</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a class="faq-collapse" onclick="jQuery('.answer-wrapper').css('display','none');">Collapse All</a></div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="span10 offset1">
                                            <div class="question-wrapper">
                                                <div class="arrow">
                                                    &nbsp;</div>
                                                <div class="big-q">
                                                    Q</div>
                                                <div class="question">
                                                    <h6>Can I try the software before I buy it?</div></h6>
                                                <div class="answer-wrapper">
                                                    <div class="big-a">
                                                        A</div>
                                                    <div class="answer">
                                                        Yes! Simply <a href="/trial">download a free trial</a> and you&#39;ll have instant access to all features for 30 days, absolutely free. We don&#39;t require your credit card details or any commitment.</div>
                                                </div>
                                            </div>    
                                        </div>
                                    </div>
                                </div>

How I can expand or hide the answer from example when i click on the row?

Jquery datepicker create 2 separate classes for different category (beforeShowDay)

I am trying to figure out how I can highlight specific dates on my datepicker with different colours.

I have managed to create the function to highlight dates I want, but I have two categories; confirmed and pending and would prefer to include both if possible. I tried simply copy and pasting the function with different names but it doesnt seem to work.

<script>
jQuery(document).ready(function() {
var eventDates = {};
<?php 
    $events = DB::getInstance()->query("SELECT statement FROM table WHERE criteria");
    if(!$events->count()){
    }else{
        foreach ($events->results() as $events){
            $begin = new DateTime( $events->check_in );
            $end = new DateTime( $events->check_out );
            $end = $end->modify( '+1 day' );
            $interval = DateInterval::createFromDateString('1 day');
            $period = new DatePeriod($begin, $interval, $end);
            foreach ( $period as $dt ){
                $eventDate = $dt->format( "m/d/Y" );
                echo "eventDates[ new Date( '" . $eventDate . "' )] = new Date( '" . $eventDate . "' );";
            }
        }
    }
?>  
jQuery('#calendar').datepicker({
    beforeShowDay: function( date ) {
        var highlight = eventDates[date];
        if( highlight ) {
             return [true, "event", "Booking blocked"];
        } else {
             return [true, '', ''];
        }
     }
});
});
</script>

But what I would like to achieve is to run two queries from my DB giving two sets of results and then create two classes for two colour output on the datepicker. I hope this makes sense, if anyone has a solution please let me know.

The above code works for one class. below is what I have tried to do to get two classes but it just doesnt work.

<script>
jQuery(document).ready(function() {
var eventDates = {};
var eventDatesConf = {};
<?php 
    $events = DB::getInstance()->query("SELECT statement FROM table WHERE criteria");
    if(!$events->count()){
    }else{
        foreach ($events->results() as $events){
            $begin = new DateTime( $events->check_in );
            $end = new DateTime( $events->check_out );
            $end = $end->modify( '+1 day' );
            $interval = DateInterval::createFromDateString('1 day');
            $period = new DatePeriod($begin, $interval, $end);
            foreach ( $period as $dt ){
                $eventDate = $dt->format( "m/d/Y" );
                echo "eventDates[ new Date( '" . $eventDate . "' )] = new Date( '" . $eventDate . "' );";
            }
        }
    }
    $eventsConf = DB::getInstance()->query("SELECT statement FROM table WHERE criteria");
    if(!$eventsConf->count()){
    }else{
        foreach ($eventsConf->results() as $events){
            $begin = new DateTime( $events->check_in );
            $end = new DateTime( $events->check_out );
            $end = $end->modify( '+1 day' );
            $interval = DateInterval::createFromDateString('1 day');
            $period = new DatePeriod($begin, $interval, $end);
            foreach ( $period as $dt ){
                $eventDate = $dt->format( "m/d/Y" );
                echo "eventDatesConf[ new Date( '" . $eventDate . "' )] = new Date( '" . $eventDate . "' );";
            }
        }
    }
?>  
jQuery('#calendar').datepicker({
    numberOfMonths: 2,
    beforeShowDay: function( date ) {
        var highlight = eventDates[date];
        var highlight2 = eventDatesConf[date];
        if( highlight ) {
             return [true, "event", "Booking blocked"];
        } else {
             return [true, '', ''];
        }
        if( highlight2 ) {
             return [true, "event2", "Booking"];
        } else {
             return [true, '', ''];
        }
     }
});
});
</script>

Many thanks in advance.

Highchart: add link to each segment of stacked bar chart

I want to put specific link on each segment of stacked 100% bar chart..

Demo of stacked bar chart : http://ift.tt/1rIB92i

Please update me with jquery or function to add llink to each segment of bar chart.

Cannot deselect all optionsof a multi-select if the option "All" is selected

Example Fiddle

I am having this problem(the dropdown is using chosen pluggin)

I am calling a jquery function. The issue is, there is a multiselect with the first option being "All" and all the other options are present

When the "All" will be selected, then all the other options will be deselected.

Here's my multi-select:

    <select id="risk_mitigator_offer_1" name="risk_mitigator_offer_1[]" 
       class="input_field criteria_risk" style="width:302px;" 
       multiple onchange="checkAll(this)">
       <option value="All">All</option>
       <?php
       $offers_off = array();
       $_sql_off = mysql_query( 'SELECT * FROM mt_offers WHERE camp_id=' . $mysql['camp_id'] . ' AND deleted = "0" ORDER BY offer_id' );
       if ($_sql_off) 
       {
         while ($_data_off = mysql_fetch_assoc( $_sql_off )) 
         {?>
            <option value="<?php echo $_data_off['offer_id']?>"><?php echo $_data_off['offer_name'];?></option>
   <?php  }
       } ?>  
    </select>

And here's is the jquery function:

function checkAll(obj)
{
    var values = $(obj).val();
    if (values) 
    {
        for (var i = 0; i < values.length; i++) 
        {
            if(values[i] == "All")
            {
                $(obj+" option[value!=All]").removeAttr("selected");
            }
        }
    }
}

Now the problem is that,I am getting the following jquery error:

Error: Syntax error, unrecognized expression: [object HTMLSelectElement] option[value!=All]


throw new Error( "Syntax error, unrecognized expression: " + msg );

How can I fix this issue?

I know it may be a silly one,the issue is in this line of code:

$(obj+" option[value!=All]").removeAttr("selected");

How to collect user data by asking questions in web application? [on hold]

For my web application I need to collect user data. However this has to be like LINKEDIN way. Once user login to website , linkedin ask questions in small windows or panels. In the same way I too want to implement. How to do this?? Any help is greatly appreciated. Im using PHP and Mysql to develop website. Thanks in Advance.

Unable to save data in Database through ajax in CakePhp after passing my own array variable in save function?

This is my view ctp page ....

<h1>Add Post</h1>
<?php echo $this->form->create(null,array('url'=>array('controller'=>'posts','action'=>'ajaxAdd'),'id'=>'saveForm'));
echo $this->form->input('ajaxtitle');
echo $this->form->input('ajaxbody',array('rows'=>'3'));
echo $this->form->end('Save Post');
?>

<script>
    $(document).ready(function(){
    $("#saveForm").submit(function(){       
        var formData = $(this).serialize();
        var formUrl = $(this).attr('action');
        $.ajax({

            type:'POST',
            url:formUrl,
            data:formData,
            success: function(data,textStatus,xhr){
                alert(data);                                       
                }

        });
        return false;
    });
});
</script>

This is my PostsController function

class PostsController extends AppController
{

        public $name = 'Posts';
        public $helpers = array('Html', 'Form', 'Session');
        public $components  = array('RequestHandler');
public function ajaxAdd()
    {
        $this->autoRender=false;
          if($this->RequestHandler->isAjax()){
             Configure::write('debug', 0);
          }
            if(!empty($this->data)){
                $inputData = array();
                $inputData['Post']['title'] = $this->data['Post']['ajaxtitle'];
                $inputData['Post']['body'] = $this->data['Post']['ajaxbody'];
                $data = $this->Post->findByTitle($inputData['Post']['title']);
                $this->Post->create();
               if(empty($data))
               {                   
                  if($this->Post->save($inputData))
                      return "success"; 
                }else
                {
                 return "error";
               }
            }
        }
}

With array as $inputData in save , whenever i click over the submit button nothing is being saved in the database ,,

But when i pass $this->data in save function, columns like id,created and modified are filled but the title and body column are left blank.

My posts databse contains columns id,title,body,created,modified

Check if value exists in object and if not push it

I need to check if value exists in object and if not add the value in object. Eg:My Object is and I want to check on UserId parameter.

var myObj= [{'UserId':123,'Username':'abc'},{'UserId':567,'Username':'xyz'},{'UserId':890,'Username':'pqr'}];

Now suppose I want to add new element {'UserId':223,'Username':'mln'} , I should be allowed to , however if I try to add an element {'UserId':123,'Username':'hij'} I should be not.

It will check it dynamically for a number of elements and not just the example provided above.

How should do this with jquery/javascript.

jqueyr datetimepicker set to date depand on from date

I am using jQuery "datetimepicker" and I want to set the "to date" value depend on the "from date" value and the Select box value which contains following values.

1- Weekly (7+ days)
2- Monthly (30+ days)
3- Half Yearly (6+ months)
3- Yearly (1+ Year)

Example:

1- Select From Date: 2015-05-29
2- Duration Monthly
3- To date should be 2015-06-29

I am using following code to select date start date.

jQuery('#start_date').datetimepicker({
    format:'m/d/Y',
    closeOnDateSelect:true,
    timepicker:false
});

Please suggest.

Thanks

Firefox extension that interacts with DOM

I'm developing a firefox extension with a panel of options to interact with de current tab DOM. When you select an option, all elements in the DOM of the active tab are highlited when the mouse is over and when you click in one element I want to fire different actions depending on the option chosen in the panel. I've made it work, but when you choose an option and then choose other the content script "opt" variable has both of the values.

main.js

panel.port.on('select', function(sel){
 attachScript(sel);
 panel.hide();
});

function attachScript(selected)
{
  var worker = tabs.activeTab.attach({
   contentScriptFile: [self.data.url("js/jquery-1.11.3.min.js"), self.data.url("js/content.js")]   
  });

  worker.port.emit('option', selected);
}

content.js

var opt = '';

self.port.on('option', function(option){
 $('body').off('click', '.activelem',controlClick);
 if (option)
 {
  $('body').on('click', '.activelem', controlClick);
  opt = option;      
  window.addEventListener('mousemove', handler);    
 }
});

My questions:

  • Every time than I get the panel option selected and execute the attachScript function, the scripts are injected, or just de first time?
  • Do I need to set a port.once to inject the scripts and then use a normal port.on? If this is the way, how do I communicate with the content script every time?
  • How can I remove the listener in the content script every time than the ActionButton is pressed, so every time the panel is opened its a fresh start.

How can i select all the check boxes on single click while every check box has unique name using java script please provide code

![enter image description here][1]


  [1]: http://ift.tt/1J7M6Er
How can i select all the check boxes on single click while every check box has unique name using java script please provide code
How can i select all the check boxes on single click while every check box has unique name using java script please provide code

How can i select all the check boxes on single click while every check box has unique name using java script please provide code How can i select all the check boxes on single click while every check box has unique name using java script please provide code

 </div><!-- /.box-header -->
                <div class="box-body">
                 <form name="permissionfrm" method="post" id="permissionfrm">
                 <input type="hidden" name="permission" id="permission" value="assignpermission" />
                  <table id="example1" class="table table-bordered table-striped">
                    <thead>
                     <tr>
                      <th>Give All Permissions
                      </th><td><input type="checkbox" name="addadmin" id="addadmin" value="Check All" onClick="this.value=check(this.form.list)"/></td>
                      </tr>
                      <tr>
                        <th>Add</th>
                        <th>Edit</th>
                        <th>View</th>
                        <th>Delete</th>
                      </tr>
                     </thead>
                    <tbody>

How to set color manually in colorpicker eyecon?

I am using colorpicker eyecon in my project and i want to set the color manually but when i do that it is set to black color (#000000)

I use .colorpicker('setValue', value) method

This is the documentation of this plugin http://ift.tt/1AenZgP

That's my try :

$("#button-color").colorpicker();

$("#button-color").colorpicker("setValue", "#ad4747");

mercredi 6 mai 2015

Error parsing regex pattern in php

I want to split a string such as the following (by a divider like '~@@' (and only that)):

to=enquiry@test.com~@@subject=test~@@text=this is body/text~@@date=date/this isn't camptured after the slash

into an array containing e.g.:

to => enquiry@test.com
subject => test
text => this is body/text
date => date 

I'm using php5 and I've got the following regex, which almost works, but there are a couple of errors and there must be a way to do it in one go:

        //Split the string in the url of $text at every ~@@
        $regexp = "/(?:|(?<=~@@))(.*?=.*?)(?:~@@|$|\/(?!.*~@@))/";
        preg_match_all($regexp, $text, $a); 
        //$a[1] is an array containing var1=content1 var2=content2 etc;

        //Now create an array in the form [var1] = content, [var2] = content2
        foreach($a[1] as $key => $value) {
            //Get the two groups either side of the equals sign
            $regexp = "/([^\/~@@,= ]+)=([^~@@,= ]+)/";
            preg_match_all($regexp, $value, $r); 

            //Assign to array key = value
            $val[$r[1][0]] = $r[2][0]; //e.g. $val['subject'] = 'hi'
        }

        print_r($val);

My queries are that: 1. It doesn't seem to capture more than 3 different sets of parameters 2. It is breaking on the @ symbol and so not capturing email addresses. 3. I am doing multiple different regex searches where I suspect I would be able to do one.

Any help would be really appreciated.

Thanks

VIm: copy match with cursor position atom to local variable

I'm searching for a way to copy match result to local variable in vim script.

The issue is that I want to match text that includes cursor position atom \%#, that is, for example: [A-Za-z:]*\%#[A-Za-z:]\+, which matches identifiers like ::namespace::ParentClass::SubClass text under cursor (so <cword> does not work for me).

I would like to use this later in a script, but the more I dig the more I start to wonder if that's even possible (or: if I should do it differently, by collecting current line, cursor position and then just extract the identifier under cursor manually).

If that's not possible from within the vim script - what would be the idea behind the \%# atom? what is its use?

How to identify a set of dates from a string in rails

I have the following strings
"sep 04 apr 06"
"29th may 1982"
"may 2006 may 2008"
"since oct 11"

Is there a way to obtain the dates from these string. I used the gem 'dates_from_string', but it is unable to correctly obtain date from first scenario.

regular expression for decimal with fixed total number of digits

Is there a way to write regular expression that will match strings like

(0|[1-9][0-9]*)\.[0-9]+

but with a specified number of numeric characters. for example: for 3 numeric characters it should match "0.12", "12.3" but not match "1.234" or "1.2". I know I can write it something like

(?<![0-9])(([0-9]{1}\.[0-9]{2})|([1-9][0-9]{1})\.[0-9]{1})(?![0-9])

but that becomes quite tedious for large number of digits.

(I know I don't need {1} but it better explains what I'm doing)

Regex Multiple Matches PHP

Im trying to get all numbers from a string, having - or _ before the number and optional - _ space or the end of string at the end of the number.

so my Regex looks like this [-_][\d]+[-_ $]?

My problem is, i dont match numbers right after each other. From a String "foo-5234_2123_54-13-20" i only get 5234,54 and 20.

What i tried is following (?:[-_])[\d]+(?:[-_ $])? and [-_]([\d]+)[-_ $]? which obvoiusly didnt work,im looking for hours now and i know it cant be that hard so im hoping someone can help me here in short.

If that makes a different, im using php preg_match_all.

How to search a particular string in a file using pattern matcher in java

I have the following paragraph

java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:197) at jcifs.netbios.SessionServicePacket.readPacketType(SessionServicePacket.java:68) at jcifs.netbios.NbtSocket.connect(NbtSocket.java:107) at jcifs.netbios.NbtSocket.(NbtSocket.java:68) at jcifs.smb.SmbTransport.ensureOpen(SmbTransport.java:275) at jcifs.smb.SmbTransport.send(SmbTransport.java:602) at jcifs.smb.SmbTransport.negotiate(SmbTransport.java:847) at jcifs.smb.SmbTree.treeConnect(SmbTree.java:119) at jcifs.smb.SmbFile.connect(SmbFile.java:790) at jcifs.smb.SmbFile.connect0(SmbFile.java:760) at jcifs.smb.SmbFile.queryPath(SmbFile.java:1149) at jcifs.smb.SmbFile.exists(SmbFile.java:1232) at com.ssc.faw.util.SmbFileOperator.copyFile(Unknown Source) at com.ssc.faw.newnav2faw.FundList.checkFiles(Unknown Source) at com.ssc.faw.newnav2faw.FundList.buildList(Unknown Source) at com.ssc.faw.newnav2faw.Process.buildFundList(Unknown Source) at com.ssc.faw.job.NavToFaw.runNav2Faw(Unknown Source) at com.ssc.faw.job.NavToFaw.runNav2Faw(Unknown Source) at com.ssc.faw.job.NavToFaw.runJob(Unknown Source) at com.ssc.faw.job.NavToFaw.main(Unknown Source) [WARN ] 2015-05-05 21:02:26,383 Caught an Exception for file \ac_asd_2.my_web.com\global\nvice\alert\ filename abcd123.xls continuing to process other funds 0 : null jcifs.smb.SmbException: An error occured sending the request.

Now the question is, based on the occurence of the word "Connection reset" I need to find the immediate next .xls filename "abcd123.xls" (could be of any name) Can we do this via REGEX??

What can be the best RegEx for parsing the following string?I need to parse the lines highlighted in the below string

/product/prd-2210444/croft-barrow-denim-jacket-womens.jsp" class="showQuickViewPan image-holder-s javascript:void(0);" title="Croft & Barrow® Denim Jacket - Women's" rel="http://ift.tt/1JqaxcT javascript:void(0);" title="Croft & Barrow® Denim Jacket - Women's" rel="http://ift.tt/1IfQnoP javascript:void(0);" title="Croft & Barrow® Denim Jacket - Women's" rel="http://ift.tt/1JqaxcV javascript:void(0);" title="Croft & Barrow® Denim Jacket - Women's" rel="http://ift.tt/1IfQnoT javascript:void(0);" title="Croft & Barrow® Denim Jacket - Women's" rel="http://ift.tt/1JqaxcZ javascript:void(0)" class="moreViewSwatch-su /product/prd-2210444/croft-barrow-denim-jacket-womens.jsp /product/prd-201610/chaps-wool-blend-2-button-blazer-men.jsp" class="showQuickViewPan image-holder-s javascript:void(0);" title="Chaps Wool-Blend 2-Button Blazer - Men" rel="http://ift.tt/1IfQnp1 javascript:void(0);" title="Chaps Wool-Blend 2-Button Blazer - Men" rel="http://ift.tt/1Jqaxd1 javascript:void(0)" class="moreViewSwatch-su /product/prd-201610/chaps-wool-blend-2-button-blazer-men.jsp /product/prd-1492409/levis-classic-denim-jacket-womens.jsp" class="showQuickViewPan image-holder-s javascript:void(0);" title="Levi's Classic Denim Jacket - Women's" rel="http://ift.tt/1IfQpNs javascript:void(0);" title="Levi's Classic Denim Jacket - Women's" rel="http://ift.tt/1Jqaxd3 javascript:void(0);" title="Levi's Classic Denim Jacket - Women's" rel="http://ift.tt/1IfQpNu javascript:void(0);" title="Levi's Classic Denim Jacket - Women's" rel="http://ift.tt/1JqauxU javascript:void(0)" class="moreViewSwatch-su /product/prd-1492409/levis-classic-denim-jacket-womens.jsp /product/prd-c155964/chaps-classic-fit-gray-wool-blend-stretch-suit-separates-men.jsp" class="showQuickViewPan image-holder-s /product/prd-c155964/chaps-classic-fit-gray-wool-blend-stretch-suit-separates-men.jsp

how to find out '<' character which is not a markup tag in xml string using java?

The below xml is converted into a String.I have to find '<' character which is part of xml element actionComent value

<actionTakenTaskCollectionRoot>
  <actionTakenTask actionTakenTaskId="8a8080844cd55b0b014cd5f783ea0692">
    <actionComment>a **<** b</actionComment>
  </actionTakenTask>
</actionTakenTaskCollectionRoot>

How can I use vim regex to replace text when math divide is involved in the expression

I am using vim to process text like the following

0x8000   INDEX1 ....
0x8080   INDEX2 ....
....
0x8800   INDEXn ....

I want to use regular expression to get the index number of each line. that is

0x8000 ~ 0
0x8080 ~ 1
....
0x8800 ~ n

The math evaluation should be (hex - 0x8000) / 0x80. I am trying to using vim regular expression substitution to get the result in line

%s/^\(\x\+\)/\=printf("%d", submatch(1) - 0x8000)

This will yield

0     INDEX0
128   INDEX1
....
2048  INDEXn

What I want to do is to further change it to

0     INDEX0
1     INDEX1
...
20    INDEXn

That is, I want to further divide the first column with an 0x80. Here is when I get the problem.

The original argument is "submatch(1) - 0x8000". I now add an "/ 0x80" to it, which forms

%s/^\(\x\+\)/\=printf("%d", (submatch(1) - 0x8000)\/0x80)

Now Vim report error

Invalid expression: printf("%d", (submatch(1) - 0x8000)\/0x80))

It looks like vim meet problem when processing "/". I also tried with a single "/" (without escape), but still fails.

Can anyone help me on this?

How to extract a complex version number using sed?

I use sed in CentOs to extract version number and it's work fine:

echo "Version 4.2.4 (test version)" | sed -nre 's/^[^0-9]*(([0-9]+\.)*[0-9]+).*/\1/p'

But my problem is that i am not able to extract when the version is shown like this:

Version 4.2.4-RC1 (test version)

I want to extract the 4.2.4-RC1 if it is present.

Any ideas ?

EDIT

maybe the extract is make from a path like this: /var/opt/test/war/test-webapp-4.1.56-RC1.war. It's not the same format each time. Like :

echo "var/opt/test/war/test-webapp-4.1.56-RC1.war" | sed -nre 's/^[^0-9]*(([0-9]+\.)*[0-9]+).*/\1/p'

Regular Expression for Percentage of marks

I am trying to create a regex that matches percentage for marks

For example if we consider few percentages

1)100%
2)56.78%
3)56 78.90%
4)34.6789%

The matched percentages should be

100%
56.78%
34.6789%

I have made an expression "\\d.+[\\d]%" but it also matches for 56 78.90% which I don't want.

If anyone knows such expression please share

Powershell Regex Expression. Convert line uri to UK friendly format

I would like some assistance with Regex within Powershell please. If someone can help I'd be really grateful...

I have downloaded a script from Microsoft which will allow us to take a string and convert it into a friendly format to display on user profiles.

The original string is tel:+441234123456;ext=3456

What I need to do is convert it into a UK friendly format so

converted string is 01234 123456

The steps I think I need to take are :- Removing the tel:+44 and replacing with 0. After first 4 digits add a space. Finish the variable with the last 6 digits. Remove the ;ext=3456

There was a similar process but for US suggested, unfortunately no knowing regex this goes over my head slightly!

$tel = $LineURI -replace ‘tel:(\+1)([2-9]\d{2})([2-9]\d{2})(\d{4});ext=\d{4}’,’$1 ($2) $3-$4;

Any suggestions or help welcome!

How to re-match a group that did not capture anything?

I'm trying to parse a string in which a certain section can either be enclosed between " or ' or not be enclosed at all. However, I'm struggling finding a syntax that works when no quotation marks are there at all.

See the following (simplified) example:

>>> print re.match(r'\w(?P<quote>(\'|"))?\w', 'f"oo').group('quote')
"

>>> print re.match(r'\w(?P<quote>(\'|"))?\w', 'foo').group('quote')
None

>>> print re.match(r'\w(?P<quote>(\'|"))?\w(?P=quote)', 'f"o"o').group('quote')
"

>>> print re.match(r'\w(?P<quote>(\'|"))?\w(?P=quote)', 'foo').group('quote')
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
'NoneType' object has no attribute 'group'

The desired result for the last attempt should be None as the second command in the example.

Regular expression to create multiple word fragments based off the same words

Let's say I have the following string:

var str = "I like barbeque at dawn";

I want pairs of all words which are separated by a space. This can be achieved via the following regular expression:

  var regex = /[a-zA-Z]+ [a-zA-Z]+/g;
  str.match(regex);

This results in:

["I like", "barbeque at"]

But what if I want ALL permutations of the pairs? The regular expression fails, because it only matches any given word onces. For example, this is what I want:

["I like", "like barbeque", "barbeque at", "at dawn"]

I know I can use the recursive backtracking pattern to generate permutations. Do regular expressions have the power to create these types of pairs for me?