Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles

mercredi 6 mai 2015

How to use a set of characters in the javascript match method

How can I use all the following characters as a regular expression in the javascript match method and escape the characters that need to be escaped?

~!@#$%^&*()_-+={}[]|:;<>,./? and space

so that mysstring.match(REGEX) returns null only if mysstring does not contain any of the above set of characters

 "abc".match(REGEX) //should return null
 "abc@".match(REGEX) //should NOT return null (it has @)
 "ab c".match(REGEX) //should NOT return null (it has a space)
 "++abc".match(REGEX) //should NOT return null (it has +)

Limiting the jQuery search scope correctly?

I've stumbled up this code and I'm wondering if its just limiting the scope or selecting both of the elements at the same time.

container = jQuery("#test", parent.document);

jQuery("param[name=scale]", another.object)

Can anyone shed some light on this?

Submitting Values From a Jquery Slider

Hey guys I have this code here for a jquery slider. I want to take the value of the slider out and use an http post method to submit the value to a database. I have a processing form which I used successfully for textboxes and radio buttons. I was hoping to save the value of the slider in a hidden field and just post it. I know this gets the value from the slider.

    var selection = $( ".selector" ).slider( "value" );

Now how can I add this into the value in this submit form?

    <input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value=selection>

This is my whole code.

    <<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Slider - Slider bound to select</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="style.css">
  <script>
  $(function() {
    var select = $( "#minbeds" );
    var slider = $( "<div id='slider'></div>" ).insertAfter( select ).slider({
      min: 1,
      max: 10,
      range: "min",
      value: select[ 0 ].selectedIndex + 1,
      slide: function( event, ui ) {
        select[ 0 ].selectedIndex = ui.value - 1;
      }
    });
    $( "#minbeds" ).change(function() {
      slider.slider( "value", this.selectedIndex + 1 );
    });
  });
  var selection = $( ".selector" ).slider( "value" );
  </script>
</head>
<body>

<form id="mainForm_1" class="MainForm" method=post enctype=multipart/form-data action=processorss.php onSubmit="return validatePage1();">



  <label for="minbeds" class="mainForm">Rate Your Prefence for Fish 1-10</label>
 <select name="minbeds" id="minbeds">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
  </select>
  <li class="mainForm">



  <input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value=selection>

                    <input id="saveForm" class="mainForm" type="submit" value="Submit" />
                </li>
</form>


</body>
</html>

Randomly space characters throughout string?

To shuffle a string, I could use something like this

String.prototype.shuffle = function () {
    var arr = this.split("");
    var len = arr.length;
    for (var n = len - 1; n > 0; n--) {
        m = Math.floor(Math.random() * (n + 1));
        tmp = arr[n];
        arr[n] = arr[m];
        arr[m] = tmp;
    }
    return arr.join("");
}

But how could I randomly space it with n characters, while preserving the string order?

For example:

"test"   =>   "t-es--t"
"test"   =>   "-t-e-st"
"test"   =>   "te--st-"

I've thought about creating a list from the string, generating a random number to represent an index, and then shifting the list to the left, but is there a better way to do this?

Jquery Sortable retrieve hidden Id on change

i am using the jquery sortable arrange images in a certain order, all i want to do is on change get the hidden id of the image and the new current position number so i can run an ajax request to update the new position in my database, however when i change the image position the alert is not triggered(in below code) so i am wondering what i am doing wrong.

Jquery code

<script>
        $(function() {
            $("#sortable").sortable({
                stop: function(event, ui) {

                    $('input.imageHiddenImageId').each(function(idx) {

                        var imageId = (this).val();
                        alert("New position: " + ui.item.index() + "id:" + imageId);
                        //Run some AJAX code to server
                    });

                }
            });
            $( "#sortable" ).disableSelection();
        });
    </script>

HTML code

<ul id="sortable">
   <li class="ui-state-default">
      <img src="http://localhost/site/gallery/3.png" style="max-width: 100%; height: auto;">
      <input type="hidden" class="imageHiddenImageId" id="imageHiddenImageId" name="imageHiddenImageId" value="45">
      <input type="hidden" id="imageHiddenNo" name="imageHiddenNo" value="2">
    </li>
 </ul>

Thanks for the help

jstree custom node markup

Is there a way to have custom markup or add additional html elements to some of the nodes.

For example, we want to add an arrow (link) right after the node text for all the nodes under a path, and when user click on the arrow, open the context menu. I know the context menu can be opened using the right click, but the requirement is to have an arrow after the node and clicking on the arrow should open the context menu.

Is there a way to customize or add additional html elements to selective tree nodes, and programmatically open the context menu or link click event.

Can't return the response data using jQuery AJAX

I'm loading cross domain html page with jQuery AJAX.

My problem is to return or equal the response data (target's html code) .

var html = "";

get("http://google.com");

function get( url ){

    $.ajaxPrefilter( function (options) {
        if (options.crossDomain && jQuery.support.cors) {
            var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
            options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
        }
    });

    $.get(url,function (response) {

         // Here is the problem

     });    
}

In the $.get() method I tried to :

html = result ;

return result ;

Both tries didn't work.

Is there any similar way to 'export' the response data to a global scope var ?

P.S - I've tried to use a function with a parameter to return the response . It worked perfectly but that is not what I want at all.

Javascript. if else if else confusion

Why the else if condition still executes when the if condition is already true? I thought if the if condition is true anything under it like else if...else or else will be worthless. code:

for (i = 1; i <= 20; i++)
{
    if (i % 3 === 0 && i % 5 === 0)
    {
        console.log("FizzBuzz");
    }
    else if (i % 3 === 0)
    {
        console.log("Fizz");
    }
    else if (i % 5 === 0)
    {
        console.log("Buzz");
    }
    else
    {
        console.log(i);
    }
}

this is the output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

Display uploaded images on button click

On click of button preview i need the uploaded images to be shown ,the scripts it's working fine for changing event but not for the click one.

HTML

 <form action="test.php" enctype="multipart/form-data" id="mainform" method="post" name="mainform">
Imagine 1:<br>
 <input type="file" name="img1" id="img1"><br>
     <br><br>     
Imagine 2 :<br>
 <input type="file" name="img2" id="img2"><br>
     <br>
 Imagine 3 :<br>
 <input type="file" name="img3" id="img3"><br> 
     <br>
 Imagine 4 :<br>
 <input type="file" name="img4" id="img4"><br>    
     <br>
 Imagine 5 :<br>
 <input type="file" name="img5" id="img5"><br>   
     <br>
 Imagine 6 :<br>
 <input type="file" name="img6" id="img6"><br>   
     <br>
 Imagine 7 :<br>
 <input type="file" name="img7" id="img7"><br>    
     <br>
 Imagine 8 :<br>
 <input type="file" name="img8" id="img8"><br>    
     <br>
 Imagine 9 :<br>
 <input type="file" name="img9" id="img9"><br>   
     <br>
 Imagine 10 :<br>
 <input type="file" name="img10" id="img10"><br>    
     <br>
 Imagine 11 :<br>
 <input type="file" name="img11" id="img11"><br> 
     <br>
 Imagine 12 :<br>
 <input type="file" name="img12" id="img12"><br>    
     <br>
 Imagine 13 :<br>
 <input type="file" name="img13" id="img13"><br>    
     <br>
 Imagine 14 :<br>
 <input type="file" name="img14" id="img14"><br>     
     <br>
 Imagine 15 :<br>
 <input type="file" name="img15" id="img15"><br>    
     <br />
     Preview:
     <br />
     <input type="checkbox" id="previz" />Preview
</form>
<div id="#previzdiv">
<img src="" id="preview-img1">
<img src="" id="preview-img2">
<img src="" id="preview-img3">
<img src="" id="preview-img9">
<img src="" id="preview-img5">
</div>

Jquery:

$("#center2 #forme #previz").change(function(){
if(this.checked){
for(i=1;i<15;i++){
j = $("form#mainform #img"+i);
console.log(j);
readURL(j);
}
}

});
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                imgId = '#preview-'+$(input).attr('id');
                $(imgId).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
      }


      $("form#mainform input[type='file']").change(function(){
        readURL(this);
        console.log(this);
      });

The console log from "j" should look like <input type="file" name="img1" id="img1"> yet it different from what change event is console logging.Is the approach correct? JSFIDDLE:http://ift.tt/1JrktCS

GwtExt EditableGridSample JavaScript Exception

I am trying out the EditableGridSample.java Demo from GwtExt.

The apllication compiles and deploys but the page is blank. I wrapped a try catch around this line

try {
        HttpProxy proxy = new HttpProxy("data/plants.xml", Connection.GET);
    } catch (Exception e) {
        Window.alert(" Exception " + e);
}

and get the error message Exception com.google.gwt.core.client.javaScriptException(TypeError): Cannot set property 'BLANK_IMAGE_URL' of undefined

Please help

Tinymce editor becomes empty when ng-repeat list is reordered

This is a simplified example of a bug we faced in our project recently.

I have a list of objects with "name" and "position" properties and wanna use TinyMCE editor instead of textarea to display "name".

Besides, the list is ordered by "position" property which is editable.

Noticed that once "position" property is changed(list is reordered), TinyMCE editor becomes empty.

Anyone has any ideas why it happens and how to fix this?

Example code: JsFiddle

HTML

<script src="http://ift.tt/1DTrZWe"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <p>List of activities:</p>
        <div ng-repeat="activity in model.activities | orderBy: 'position'">
             <label for="$index">Position</label>
            <input id="$index" type="number" ng-model="activity.position" style="width: 50px">
            <textarea ng-model="activity.name" rows="2" cols="10"></textarea>

            <hr>
        </div>
    </div>
</body>

JS

var myApp = angular.module('myApp', ['ui.tinymce']);
/**
 * Binds a TinyMCE widget to <textarea> elements.
 */
angular.module('ui.tinymce', [])
  .value('uiTinymceConfig', {})
  .directive('uiTinymce', ['uiTinymceConfig', function (uiTinymceConfig) {
    uiTinymceConfig = uiTinymceConfig || {};
    var generatedIds = 0;
    return {
      priority: 10,
      require: 'ngModel',
      link: function (scope, elm, attrs, ngModel) {
        var expression, options, tinyInstance,
          updateView = function () {
            ngModel.$setViewValue(elm.val());
            if (!scope.$root.$$phase) {
              scope.$apply();
            }
          };

        // generate an ID if not present
        if (!attrs.id) {
          attrs.$set('id', 'uiTinymce' + generatedIds++);
        }

        if (attrs.uiTinymce) {
          expression = scope.$eval(attrs.uiTinymce);
        } else {
          expression = {};
        }

        // make config'ed setup method available
        if (expression.setup) {
          var configSetup = expression.setup;
          delete expression.setup;
        }

        options = {
          // Update model when calling setContent (such as from the source editor popup)
          setup: function (ed) {
            var args;
            ed.on('init', function(args) {
              ngModel.$render();
              ngModel.$setPristine();
            });
            // Update model on button click
            ed.on('ExecCommand', function (e) {
              ed.save();
              updateView();
            });
            // Update model on keypress
            ed.on('KeyUp', function (e) {
              ed.save();
              updateView();
            });
            // Update model on change, i.e. copy/pasted text, plugins altering content
            ed.on('SetContent', function (e) {
              if (!e.initial && ngModel.$viewValue !== e.content) {
                ed.save();
                updateView();
              }
            });
            ed.on('blur', function(e) {
                elm.blur();
            });
            // Update model when an object has been resized (table, image)
            ed.on('ObjectResized', function (e) {
              ed.save();
              updateView();
            });
            if (configSetup) {
              configSetup(ed);
            }
          },
          mode: 'exact',
          elements: attrs.id
        };
        // extend options with initial uiTinymceConfig and options from directive attribute value
        angular.extend(options, uiTinymceConfig, expression);
        setTimeout(function () {
          tinymce.init(options);
        });

        ngModel.$render = function() {
          if (!tinyInstance) {
            tinyInstance = tinymce.get(attrs.id);
          }
          if (tinyInstance) {
            tinyInstance.setContent(ngModel.$viewValue || '');
          }
        };

        scope.$on('$destroy', function() {
          if (!tinyInstance) { tinyInstance = tinymce.get(attrs.id); }
          if (tinyInstance) {
            tinyInstance.remove();
            tinyInstance = null;
          }
        });
      }
    };
  }]);

myApp.controller("MyCtrl", ["$scope", function($scope) {
    $scope.model = { 
        activities: [
            {name: "activity 1", position: 1}, 
            {name: "activity 2", position: 2}, 
            {name: "activity 3", position: 3}, 
            {name: "activity 4", position: 4}, 
            {name: "activity 5", position: 5}
        ] 
    };
    $scope.tinyMceOptions = {
        selector: "textarea",
        theme: "modern",
        plugins: [
            "autolink lists link charmap print preview hr anchor pagebreak autoresize",//advlist
            "searchreplace visualblocks visualchars code",
            "insertdatetime nonbreaking save table directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar1: "bold italic underline |  alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor | undo redo | link | pastetext",
        paste_auto_cleanup_on_paste: true,
        paste_strip_class_attributes: 'mso',
        paste_data_images: false,
        theme_advanced_buttons3_add: "pastetext,pasteword,selectall",
        image_advtab: true,
        //templates: [
        //    {title: 'Test template 1', content: 'Test 1'},
        //    {title: 'Test template 2', content: 'Test 2'}
        //],
        browser_spellcheck: true,
        menubar: false,
        //theme_advanced_disable: "bullist,numlist",
        target_list: [{ title: 'New page', value: '_blank' }],
        //advlist_number_styles: [
        //    {title : 'Standard', styles : {listStyleType : ''}},
        //    {title : 'a. b. c.', styles : {listStyleType : 'lower-alpha'}}
        //],
        //spellchecker_languages: "+English=en",
        //spellchecker_rpc_url: 'spellchecker.php',
        handle_event_callback: function (e) {
            // put logic here for keypress
        }
    };
}]);

How to inject services to monitor authentication and storage status?

I'm using Angular.js to build a client side application with Restangular. The problem is, I implemented a digest authentication with a wsse header which i have to generate at each request to my REST Server.

I saw that Restangular provide a function : addFullRequestInterceptor().

So now, i'm trying to use it inside my RestangularProvider to configure it in this file restangular.js :

'use strict';

// Config Restangular
app.config(function(RestangularProvider) {
  RestangularProvider.setBaseUrl(applicationConfig.SERVER_URL);
  RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
  RestangularProvider.addFullRequestInterceptor(function (element, operation, route, url, headers, params, httpConfig) {
    $http.defaults.headers.common['X-WSSE'] = TokenHandler.getCredentials(AuthHandler.authentication.user.username,AuthHandler.authentication.secret); // Here is my header generation.
    return {
      element: element,
      headers: headers,
      params: params,
      httpConfig: httpConfig
    };
  });
});

But i have an injection problem and i can't find out how to inject my TokenHandler service & my AuthHandler service to be able to know if the user is already loggedin or not and if he has localstroage or not.

Thanks for the help ;)

How to target the focused input dynamically

I have a Jquery code that will pop-up with a box saying "Today" only when a user focuses on an input field. When the user clicks on the box, this will populate the targeted input field with the current date. Currently my code is working but the problem is as follows:

Problem: When someone clicks on the Today button, it populates all the input fields on the page instead of the input being focused on.

I created a JSFiddle to give you the best representation of my site's structure and will give you an idea of what's happening. Im still learning a lot in with Jquery lately but this has stumped me. I tried to target the input itself by using $("input[id*=Next_Update]").val(now); but that just breaks the code.

Here is a quick sample of my code with the JSfiddle JSFiddle: http://ift.tt/1Jrktmo

$(document).ready(function() {
    $(".im_whiteboard [id*=Next_Update]").on('focusin', function() {
        var div = $('#now');
        var top = $('input').offset().top + $('input').height() + 5;
        var left = $('input').offset().left;
        $(div).css('top', top);
        $(div).css('left', left);
        $(div).fadeIn();
    });
    $('input').on('focusout', function() {
        $('#now').fadeOut();
    });
    $('#now').on('click', function() {
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        } 

        if(mm<10) {
            mm='0'+mm
        } 

        today = mm+'/'+dd+'/'+yyyy;
       $('input').val(today); 
    });
});

I would appreciate any support on this.

jQuery Flip front to 2 different backsides

I am having trouble getting a certain feature to work.

As you can see here: http://ift.tt/1F5JkhP

<div> CHECK CODE AT JSFIDDLE</div>

I am using the flip jquery plugin which made a flip, where you choose a category, and then gets sent to a certain login screen. My issue is, that I want the bottom one to flip to another backside. I have tried altering the jquery plugin, but without luck. Is there anyone who knows how I could make this work?

So the pink one goes to the pink login, and the blue one goes to the blue login.

Thank you in advance!

in case of rotation of object there are some "artifacts"

everybody. There is a textured 3d object. enter image description here In case of its rotation there are distortions. enter image description here To what it can be connected?

P.S. if to disconnect shadowing of object, will change nothing

Meteor Twitter/Facebook login callbacks

I'm working on an account system where in which a user can create their account with an email address, and a password, and they can then link their account to either twitter, or facebook, in order to pull in their profile image.

The thing I can't seem to figure out, is how to get either login to send a callback.

Im using the link-accounts package, and everything's working, but I'm not sure how to hook into the process. On linking the account, I'd like to be able to trigger an event, and I'd also like to allow users to unlink their accounts.

Anyone familiar with doing this?

How to set specific action to f:selectItems in JSF2

I have with ajax

<h:selectOneMenu>
<f:selectItem itemLabel="please click"/>
<f:selectItem itemLabel="1"/>
<f:selectItem itemLabel="2"/>
<f:ajax onevent="click()" />
</h:selectOneMenu>

I have with onChange

<h:selectOneMenu onChange="click()>
<f:selectItem itemLabel="please click"/>
<f:selectItem itemLabel="1"/>
<f:selectItem itemLabel="2"/>    
</h:selectOneMenu>

if I try the same attributes to selectItem, it doesnt work. I think they dont exist.

I used ajax, onChange but it seem to wrok for selectonemenu but not in particular for selectItem.

Best practices for unit testing backend calls with Angular/Mongo

I am writing an Angular application that has a Scala/Play backend and a MongoDB. I'm new to unit testing and I'm trying to wrap my head around how to test the Mongo calls.

The app was designed by someone else and I've inherited it. The backend is very generic there are only four API services defined - save, find, delete, and generate newID. The angular calls take in a collection name and maybe an ID.

I have written tests to make sure a particular method processes data in the way that I expect, but I am lost when it comes to testing the Mongo part.

For example, let's say I have two objects - Apples and Oranges. I could have methods such as these

myAppleSvc.getApple: (id) ->
    myDataSvc.find "apples", {id:id}
myOrangeSvc.getOrange: (id) ->
    myDataSvc.find "oranges", {id: id}

The lower level data svc would do something like this:

myDataSvc.find: (collection, query) ->
    deferred=$q.defer()
    @doPost "/api/v1/findJson/#{collection}", query, deferred
    return deferred.promise

The @doPost function is a helper method that handles the success/failure

doPost: (path, data, deferred) ->
    $http.post path, data
    .success (result) -> deferred.resolve result
    .error (result) -> deferred.reject result

There are some other things going on in the codebase, but this is the basic pattern.

I am trying to understand the best way to test this code. Most of my calls just return a promise to be resolved. How would I test the getOrange and getApple calls? As far as I can tell, all I can do is make sure they are returning a promise. With the dataSvc.find call, it seems all I need to do is make sure that it calls the correct URL and also returns a promise. Am I missing something?

Leaflet popup closing immediately after function fires to open popup dynamically

I have a feature that allows the user to look up a marker and zoom to its location, at which point I want the popup to open. Everything is working fine, except that the popup closes after the function fires. I can't figure out what's making the popup close. Here's my relevant code:

var geoJsonDataFeatures = {
"type": "FeatureCollection",
"features":[]
};

//create popup content
var htmlString = "<div>popup html goes here....</div>";
var popupContent = L.popup().setContent(htmlString);

//create geoJson object for each marker
var geoJsonData = {
"type": "Feature",
"id": siteNo, //a string saved as a variable 
"properties": {
    "popupContent": popupContent,
    "icon": icon //an L.icon object
    },
"geometry": {
    "type": "Point",
    "coordinates": [longitude, latitude] //strings saved as variables
    }
}

//push the geoJson feature into the features object
geoJsonDataFeatures.features.push(geoJsonData);

//create the map layer that holds the markers
var geoJsonDataLayer = L.geoJson(geoJsonDataFeatures, {
    onEachFeature: function (feature, layer) {
    layer.bindPopup(feature.properties.popupContent);
    layer.setIcon(feature.properties.icon);
    }
}).addTo(map);

....

//when the user has selected a site from a dropdown select menu,
//we pass the site number (siteNo) to a function to zoom and open the
//marker popup:

zoomOpenPopup(siteNo);

function zoomOpenPopup(siteNo){
var marker = {};
var popup = {};
var layerObj = {};

    if(map.hasLayer(geoJsonDataLayer))
    {
    layerObj = geoJsonDataLayer;
    }

    jQuery.each(layerObj._layers, function(k){

        if(siteNo == layerObj._layers[k].feature.id)
        {
        marker = layerObj._layers[k];
        popup = layerObj._layers[k].feature.properties.popupContent;
        }  
    });

marker.openPopup();
//popup._isOpen = true; //doesn't work
//popup.openOn(map); //doesn't work
//map.openPopup(popup); //doesn't work
 alert("done!"); 
}

When the alert fires, you can see the popup open on the map, but once it closes the popup disappears. I do have a function that updates the position of the popup anchor on open if the content is too wide, but I have the same issue even if I comment out that function and reload the page. Has anyone run into something similar?

javascript match method with a closing square bracket character

How can I use a closing square bracket as a character in a javascript regular expression?

"Acb[".match('[\(, \), \[]')

returns:

["["]

But when I add the closing square bracket as a character it does not work :

"Acb[".match('[\(, \), \[, \]]')
null


"Acb]".match('[\(, \), \[, \]]')
null