Jquery .on() method not working on dynamic content

A page that executes javascript every time an input field it checked and also load new data thru ajax.

My jquery selector

$(".te_multiselect_checkbox").on("change", function( e ) {} 

was not working on the new content. When I ran $(‘.te_multiselect_checkbox’) in the console before the new content was retrieve I would get http://x-v.it/uploads/capit/ge/n3/8y.jpg but after the new content was loaded I got

http://x-v.it/uploads/capit/4q/7x/s1.jpg
(x.fn.x.init)
I dont know if this happens because the page was architect to do so or javascript is doing it.

What I learned is the selector is not getting the new content change the selector to

$(document.body).on('change', '.te_multiselect_checkbox', function( e ) {}

Here is the explanation:
http://stackoverflow.com/questions/15090942/jquery-on-method-not-working-on-dynamic-content
http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements

tags:
jquery maintain selector when new ajax content
jquery get by class more than 100

jQuery Deferreds

Just some examples that were useful to me


http://x-v.it/gdfug8

var myVar  = 1;
function test(){
    var deferred = new $.Deferred();
    setTimeout(function(){
        myVar = 2;
        deferred.resolve();
    },2000);
    
    return deferred; //or return deferred.promise()
}

test().done(function(){
    console.log(myVar);  //should execute after the call below
})

console.log(myVar); //should be one because this is excuded first ever though it after the above call
 

$.get( "includes/cifras.html", function( data ) {
    $( "#songs" ).html( data );
}).done( function(){
            var songs = new Array();
            $('.first_line').each(function(i){
                songs[i] = {}
                songs[i]['html'] = $(this).html();
                songs[i]['id'] = i;
            });

            songs.reverse();
            $.each( songs, function( key, value ) {
                $('#list').append('
' + value['html'] + '

'); }); $('.cifra').click(function(){ $('#stand').html($('.cifra-mono').eq(this.id).html()); $('#list').css('display','none'); $(".back").css('display','block'); }); }); $( ".back" ).click(function() { $('#stand').html(''); $('#list').css('display','block'); $(".back").css('display','none'); });

jQuery Mobile Issues

$(”).click() fires twice with using alert().

I found out that in my case the addition of data-role="page" to my page container prevented tap events from being fired twice.

meta size for android is not working

Its seems that width=device-width and user-scalable=yes needs to be on its own line


    <meta name="viewport" content="width=device-width;
    user-scalable=yes;
    initial-scale=5.0;maximum-scale=5.0;minimum-scale=1.0"/>

sample code:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Page Title</title> 
    
    <!--Don't format this meta because it has to be in lines for it to work, to zoom change the value in initial-scale-->
    <meta name="viewport" content="width=device-width;
    user-scalable=yes;
    initial-scale=5.0;maximum-scale=5.0;minimum-scale=1.0"/>
    <!--***********************END*************************************-->
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
</head> 
<body> 

<div data-role="page">
    <div data-role="header">
        <h1>Page Title</h1>
    </div><!-- /header -->

    <div data-role="content">   
        <p>Page content goes heasdfre.</p>      
    </div><!-- /content -->

    <div data-role="footer">
        <h4>Page Footer</h4>
    </div><!-- /footer -->
</div><!-- /page -->
<script>


$('h1').click(function(){
    alert('header tag');
});

</script>
</body>
</html>

Phonegap jQuery Mobile error – same origin policy

I’m developing an android application thru phonegap and I like to test my application in Chrome However jquery mobile was causing this error->

XMLHttpRequest cannot load file:///home/sock/Desktop/phonegap-2.7.0/lib/android/example/assets/www/js/jquery.js?_=1369249074564. Origin null is not allowed by Access-Control-Allow-Origin. jquery.js:8416
XMLHttpRequest cannot load file:///home/sock/Desktop/phonegap-2.7.0/lib/android/example/assets/www/js/jquery.mobile-1.2.0.js?_=1369249074596. Origin null is not allowed by Access-Control-Allow-Origin.

The way around this is to close all chrome browsers and run this is the command line (I’m using ubuntu)

$ chromium-browser --allow-file-access-from-files

Chrome will open again and now you will not get this error when you run your page.


I was receiving the error when doing ajay request:


XMLHttpRequest cannot load file:///home/example/assets/www/delete.txt. Origin null is not allowed by Access-Control-Allow-Origin.

this error occurs in chrome but doesnt occur in the app when deployed so I disable this warning for developing purpose by running

$ chromium-browser --disable-web-security

>Example: Small Javascript library

>In jQuery you can call a function like $.ajax() and insert an object inside of it and each property does an action. Below I have simplified an example to demonstrate how this works.


//create the library
var lib = {
sum: function(num){ //create a method
var num1 = num.a;
var num2 = num.b;
this.result = num1 + num2;
},
table: 'table' //this is a random property, its not necessary
}

//call a method and create an object inside of it to send data to the library
lib.sum({
a : 1, //these are the properties that will be processed
b : 4
});
alert(lib.result); //output 5



//above is similar to the jQuery AJAX below
$("#input").keyup(function(){
var data = $('#input').val();
$.ajax({
url:"models/post.php", //these are the properties that will be processed
type: "post",
data: ({name:data, age:'15'}),
success:function(result){$(".result").html(result);}
});
});

jQuery Deconstructed is a rather nice way to look through the source. You will learn alot by studying it.

>Web Charts – PHP and Javascript

>pChart.net and jqPlot.com are two different libraries that allow you as a web developer create beautiful charts and graphs.

jqPlot is a javascript library that uses jQuery. jqPlot is great because it can pull data directly from multiple mediums such as csv, txt, json and so on. However it sucks because different charts may need different plugin files and you need to make sure the right script is included, but its still simple.

pChart is a PHP libray that uses its GD library. You may need to configure your php depending if this library is installed or not. pChart is a object oriented class that creates an image of a chart on the webpage. The webpage becomes an image which will not let you output any html. The only way you can link to the chart is by using <img> or <iframe> tag. Whats great is that you can create an image that can be save but what sucks is that you may not be able to use AJAX and it takes a huge load on your CPU.

>Example: JSON

>WARNING!! Do not test it in Chrome it will not work. Only live.

JSON: is used for data storage and can be an alternative to XML.

HTML:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script>
window.onerror = function(a,b,c){alert(a+b+c);} //if error alert
$(document).ready(function(){
//Short hand
$('button').click(function(){
$.getJSON("info.js", function(json) {
alert(json.name[1].first)
});

//Long
$.ajax({
async: false,
url: 'info.js',
dataType:'json',
success: function(json) {
ret = json.name[1].first;
}
});
});
});
</script>

<p>hello</p>
<button>Click Me</button>

JSON (info.js) – everything must have double quotes except numbers. You cannot comment in JSON. It has to look like the example below and it has to be in object/brackets {}


{
"name" : [{"first" : "Britney", "last":"Spears"},
{"first" : "Angelina", "last":"Jolie"}],
"age" : 25
}

>Setting the input className to the object value

>The code below creates and set the value of the object when filling out a form. This can be used for POST or GET method request.


<input type="text" class="balls" />
<input type="text" class="bat" />
<script>
var stat = {
data: {date: '2011-02-01', type: 'balls'},
column: //sets the value to stat.data
function(){
$('input').focusout(function () {
var attr = $(this).attr("class");//get the attribute (className) of tag
//create and set value for the object
stat.data[attr] = $(this).val(); //set value to stat.data
});
}() //this autostarts the function
}
<script/>

From locahost/stats website

>jQuery AJAX .load()

>jQuery AJAX is wonderfully powerfull. The more I use it the more I like it. Its very simple compared to the pure AJAX javascript code. jQuery has a couple of different AJAX syntax but the simplest is the .load(). Choose which element you want to target and which location/file you want to pull content from. Barabam AJAX.

Example:

$(‘div’).load(‘test.html’);

Above changes the div tag in current page to the test.html

One cool feature is the ability to pull a selected portion of the location by having a space after the location name and specifying the part.

Example:

$(‘div’).load(‘test.html #content’);

Above changes the div tag in current page to the test.html where the id equals “content”

More information check .load() – jQuery API