jquery unable to bind functions - jquery-mobile

I am trying to attach onBlur and onFocus handler to a SSN input field. However, I am seeing an error saying object has no method 'ON'. The code is at http://jsfiddle.net/H4Q5f/
As you can see, I commented out to figure out the details, however had no luck so far. Any help is appreciated. For convenience, here is the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" src="../../appjavascript/ssa/mkwr/mytest.js"></script>
</head>
<body>
<div data-role="page" id="MyTestPage">
<div data-role="header" data-position="fixed" data-logo="true" data-tap-toggle="false" data-fullscreen="false" >
<h1> Page Title </h1>
</div>
<div data-role="content">
<div class="content-primary divcontent">
<h1 class='h1title'>Using This App</h1>
<p> Here are the instructions </a>
</p>
</div>
<div class="inputdata">
<br /> <br />
<input type="text" name="accessCode" id="AccessCode" value="" placeholder="Access Code:" /> <br />
<input type="text" id="ssn1" class="ssn" value="" placeholder="SSN1:" /> <br />
<input type="text" id="ssn2" class="ssn" value="" placeholder="SSN2:" /> <br />
</div>
<input type="button" id="myalert" value="Next" />
</div>
<!-- /content -->
</body>
</html>
And here is the java script
if (typeof TEST == "undefined" || !TEST) {
var TEST = {};
}
( function() {
TEST.mkwr = {
init : function() { // this is a public function
$("[data-role='page']").on("pagebeforeshow", TEST.mkwr.hideError());
$("[data-role='page']").on("pageshow", TEST.mkwr.setHandlers());
},
// On Blur, we need to add the '-'s if they doesn't exist so the user
// view edit the entered value formatted
ssnOnBlurHandler : function(input) { // Auto format SSN on blur
if ($(input).val().length == 9) {
var _ssn = $(input).val();
var _ssnSegmentA = _ssn.substring(0, 3);
var _ssnSegmentB = _ssn.substring(3, 5);
var _ssnSegmentC = _ssn.substring(5, 9);
$(input).val(
_ssnSegmentA + "-" + _ssnSegmentB + "-" + _ssnSegmentC);
}
}, // _ssnOnBlurHandler
// On focus, we need to remove the '-'s if they exist so the user
// can edit the entered value
ssnOnFocusHandler : function(input) {
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
if ($(input).val().length == 11) {
var _ssn = $(input).val();
var _ssnSegmentA = _ssn.substring(0, 3);
var _ssnSegmentB = _ssn.substring(4, 6);
var _ssnSegmentC = _ssn.substring(7, 11);
$(input).val(_ssnSegmentA + _ssnSegmentB + _ssnSegmentC);
}
}, // _ssnOnFocusHandler
// Hide all errors
hideError : function() {
$(".error").hide(); // Hide all errors
},
setHandlers : function() {
alert("Set Handlers");
// $(".ssn").each( function() {
// var input = this; input.blur(TEST.mkwr.ssnOnBlurHandler(input))
// });
// $(".ssn").each( function() {
// var input = this; input.focus(TEST.mkwr.ssnOnFocusHandler(input))
// });
}
};
})(); // end the anonymous function
$("[data-role='page']").bind("pageinit", TEST.mkwr.init());

I found a couple of issues with the code on the jsfiddle. Here is an updated one that is working to fire handlers and parse code. It looks like your ssn logic might need to be fixed a little but everything is getting you to there.
http://jsfiddle.net/H4Q5f/10/
The problems I saw were partly what was mentioned before you were using .on instead of .bind given the jquery version. But also you were not setting your handlers but rather firing your handlers. You had this:
input.bind("blur",TEST.mkwr.ssnOnBlurHandler(input))
which would return the result of the function to the set method which is not what you were looking for. So I changed it to this:
input.bind("blur",TEST.mkwr.ssnOnBlurHandler)
So now you are passing the handler to the set method so that it will fire when the event takes place.
Hope this makes sense.

The .on() function was introduced in jQuery 1.7. The code you've posted above includes jQuery 1.6.4 (<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>), which doesn't have that function. You can either upgrade to the latest version of jQuery (recommended) or use the equivalent function - .bind() - for the older versions.

Related

Cropping an image using JS plugin | PhoneGap| iOS

I am new to using PhoneGap on iOS and was stuck at cropping an image using imgAreaSelect JS plugin. The code works well in the web browsers while doesn't show any change in the iOS simulator. The image is being imported from a local folder.The code used is as below:
$('#testimg').imgAreaSelect({
handles: true,
aspectRatio: '16:9'
});
Please let me know if there any other way to crop an image using PhoneGap? This is how it looks in the web browser and the same does not happen in the iOS simulator.
The plugin imgAreaSelect probably wouldn't work. I have tried JCrop-http://deepliquid.com/content/Jcrop.html and it works perfectly fine. They explicitly mention that they have Touch support for iOS, Android, etc. Just follow the demo on the link.
Jcrop Does'nt support touch event in phone gap so there is no need to use I have spend 3 hour on it. I just want to crop after upload image from camera or salary in phonegap. I use following it is working fine.
https://github.com/acornejo/jquery-cropbox
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = 640;
$targ_h=280;
$jpeg_quality = 90;
$save=dirname(__FILE__).'/files/abcd.jpg';
$src = dirname(__FILE__).'/img/img.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-Type: image/jpeg');
imagejpeg($dst_r,null ,$jpeg_quality);
exit;
}
?>
<!DOCTYPE html>
<!-- saved from url=(0041)http://acornejo.github.io/jquery-cropbox/ -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery-cropbox</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
<link type="text/css" media="screen" rel="stylesheet" href="js/jquery.cropbox.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/hammer.js"></script>
<script type="text/javascript" src="js/jquery.cropbox.js"></script>
<script type="text/javascript" defer="">
$( function () {
$(function () {
var r = $('#results'),
x = $('.cropX', r),
y = $('.cropY', r),
w = $('.cropW', r),
h = $('.cropH', r);
$('#cropimage').cropbox({
width: 500,
height: 240
}).on('cropbox', function (event, results, img) { console.log("on crop");
x.text(results.cropX);
y.text(results.cropY);
w.text(results.cropW);
h.text(results.cropH);
$("#x").val(results.cropX);
$("#y").val(results.cropY);
$("#w").val(results.cropW);
$("#h").val(results.cropH);
});
});
});
</script>
</head>
<body>
<form action="index.php" method="post" onsubmit="return checkCoords();">
<div style="width:100%;">
<img id="cropimage" alt="" src="img/img.jpg" />
</div>
<div id="results"> <b>X</b>:
<span class="cropX"></span>
<b>Y</b>: <span class="cropY"></span>
<b>W</b>: <span class="cropW"></span>
<b>H</b>: <span class="cropH"></span>
<input type="text" name="x" id="x" size="4" />
<input type="text" name="y" id="y" size="4" />
<input type="text" name="w" id="w" size="4" />
<input type="text" name="h" id="h" size="4" />
</div>
<input type="submit" />
</form>
</body></html>

Is onchnge() function works in jquerymobile 1.4.2

I am using jquerymobile 1.4.2.This the code which i am using in my page
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"> </script>
</head>
<body>
<script>
function myFunction()
{
document.getElementById("myText").disabled=true;
}
</script>
<p>Click the button to disable the text field.</p>
<select onchange="myFunction()"><option>1</option><option>2</option></select>
First Name: <input type="text" id="myText">
</body>
</html>
The above program works fine But if i change that to this code
<script>
function myFunction()
{
document.getElementById("myText").disabled=false;
}
</script>
<p>Click the button to disable the text field.</p>
<select onchange="myFunction()"><option>1</option><option>2</option></select>
First Name: <input type="text" id="myText" disabled="disabled">
Then its not working please help me how to make text field enable using onchange() function
jQM enhances the input and creates a Textinput widget which has its own enable/disable methods (http://api.jquerymobile.com/textinput/#method-disable)
In your example, to enable the input:
function myFunction() {
$("#myText").textinput("enable");
}
Also, you should use unobtrusive javascript and the jQM page functions. e.g. remove the onclick from the markup:
<select id="theSelect" >
<option>1</option>
<option>2</option>
</select>First Name:
<input type="text" id="myText" disabled="disabled" />
Add the handler in the pagecreate jQM event:
function myFunction(selVal) {
if (selVal == '2'){
$("#myText").textinput("enable");
} else {
$("#myText").textinput("disable");
}
}
$(document).on("pagecreate", "#page1", function () {
$("#theSelect").on("change", function(){
var v = $(this).val();
myFunction(v);
});
});
Here is a DEMO

IOS database app(phonegap)- working on simulator but not working on device

I build an iphone app using phonegap. I am using sqlite3 db to store the data locally. The app is working perfectly on simulator but gives error on actual ios device. It is throwing "Could not prepare statement (1 no such table: table_name)" error code for the same is Code=5.
Do i have to install sqlite plugin on ios device? The app is in a testing stage. I followed steps provided in this, to install the app on ios device.
What am I missing here?
Update:
This is the piece of code I'am using. My db resides at location
/Users/imac/Library/Application Support/iPhone
Simulator/7.0.3/Applications/4C7CC11A-8938-479F-B810-86121D3311B7/Library/WebKit/Local Storage/File_0
And on the device it resides at
AppData/Library/WebKit/Local Storage/File_0
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title>Books | Categories</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" charset="utf-8" src="js/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
var db;
var shortName = 'Books';
var version = '1.0';
var displayName = 'BooksDB';
var maxSize = 200000;
function errorHandler(transaction, error) {
alert('Error: ' + error.message + ' code: ' + error.code);
}
function successCallBack() {
alert("DEBUGGING: success");
}
function nullHandler(){
alert('null handler');
};
function onBodyLoad(){
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
db = window.openDatabase(shortName, version, displayName, maxSize);
alert('db open');
ListDBValues();
}
function ListDBValues() {
var ArrayAlphabet=new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
$('.container').empty();
for (var i = 0; i < ArrayAlphabet.length; i++) {
data='<div class="order" id="'+ArrayAlphabet[i]+'"></div>';
load_books(ArrayAlphabet[i]);
$('.container').append(data);
data="";
}
return;
}
function load_books(bookTitleAlphabet)
{
if (!window.openDatabase) {
alert('Databases are not supported in this browser.');
return;
}
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM books where book_title like "'+bookTitleAlphabet+'%" order by book_title desc;', [],
function(transaction, result) {if (result != null && result.rows != null) {
$('#'+bookTitleAlphabet).html(bookTitleAlphabet);
for (var i = 0; i < result.rows.length; i++) {
var data;
var row = result.rows.item(i);
data="<a href='details.html?id="+row.book_id+"'> <div class='book'>";
data +="<div class='book_img'><img src="+row.book_thumb_location+"></div>";
data +="<div class='book_detail'>";
data +="<div class='title'>"+row.book_title+"</div>";
data +="<div class='author'>"+row.book_author+"</div>";
data +="</div>";
data +="<div class='clear'>";
data +="</div>";
data +="</div>";
data +="</a>";
var tempId='#'+bookTitleAlphabet;
$(tempId).append(data);
tempId="";
}}
if (result.rows.length==0)
{
var tempId='#'+bookTitleAlphabet;
$(tempId).hide();
}
},errorHandler);},errorHandler,nullHandler);
return;
}
</script>
</head>
<body onload="onBodyLoad()">
<div id="wrapper">
<div class="overflow_hide">
</div>
<div class="menu">
<div class="header">
<div class="back">
<a href="index.html">
<input class="gobutton" type="button" value="Back" ></a>
</div>
<div class="list_book">BOOKS
</div>
<div class="settings">
<a href="index.html">
<input class="gobutton" type="button" value="Home" ></a>
</div>
</div>
<div class="container">
<div class="clear">
</div>
</div>
</div>
<div class="opac">
<a href="about.html">
<div class="opac1">About Us
</div></a>
<a href="search.html">
<div class="opac1">Search
</div></a>
</div>
<div class="clear">
</div>
</div>
</body>
</html>
Is this because the app cannot find the db?
EDITED/NEW ANSWER:
As the article here points out, you will likely have to do some work in XCode itself. As you correctly noted, the pathing to the database is different for pre-populated versus runtime-created databases. In short, your modifications will look for the pre-populated database and move it to the expected location/folder when it is detected. The nice thing: this will happen before your code begins to execute (javascript) so your existing code won't be "aware" that this even happened.
It is worth noting that the post I am referring you to goes past this and excludes the item from backup to iCloud. You will have to make a judgment call on whether you want to do that or not. It is pre-populated does not mean you wish to NOT back up that database nor does it make the leap (as the author does) that the pre-populated database is likely "large".
OLD ANSWER:
The error does not seem to indicate that it is having difficulty with SQLite itself, but a problem with a specific table not existing.
This typically happens when you are testing (via simulator) and at some point hit the appropriate code that performs the CREATE statement for the table. Then, later on, you get accustomed to that table being there and accidentally disconnect the schema-checking or table-existance-checking code. Since the table exists already, your simulator continues on about and never tries to re-create that table. When you go to run it on the actual device, however, that CREATE code never executes and falls into an area where you expect the table to exist - which causes the error.
Since you haven't posted any code, this is all conjecture on my part. If you want me to take a look, I would be happy to.

TideSDK don't chage mainWindow Page

I'm trying to make an app with an login form (index.html) and a mini control panel (panel.html), but when i try to login the app only show the Notificaction and dont redirect to the panel.html page.
This is the code of my index.html
<script type="text/javascript">
function loginTrue() {
Ti.UI.currentWindow.setURL("app://panel.html");
}
function showNotify(title, message) {
var notification = Ti.Notification.createNotification({
'title': title || 'Sin Titulo',
'message': message || 'Sin mensaje',
'timeout': 10
});
notification.show();
}
</script>
<script type="text/javascript">
</script>
<script type="text/python">
import MySQLdb
import os
db = MySQLdb.connect(host="localhost",user="root", passwd="toor", db="db")
cursor = db.cursor()
def login():
username= document.getElementById('usuario').value;
passw= document.getElementById('contrasena').value;
cursor.execute("SELECT * FROM usuarios WHERE userlUsuario='"+username+"' and userContrasena='"+passw+"'" )
res = cursor.fetchone()
if(res==None):
showNotify("Error!", "Datos Invalidos, intente de nuevo.");
else:
showNotify("Acceso!", "Login Correcto!");
loginTrue();
</script>
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="css/style.css" media="all" />
</head>
<body class="login">
<div class="login">
<section id="login">
<h1><strong>Login</strong></h1>
<form method="link">
<input id="usuario" type="text" placeholder="Usuario" />
<input id="contrasena" type="password" placeholder="Contraseña" />
<button class="blue" onclick="login()">Entrar</button>
</form>
</section>
</div>
</body>
</html>
I found it, the problem was with the Login form that redirects the page to it self when someone click on the submit button, i resolve it adding "javascript:void(0);" as action of the form.
<form action="javascript:void(0);">

Listview tap event on iPad

I'm currently building a mobile site for iPad using jquery mobile and ASP.NET MVC 4. I have a dynamically created listview that is displaying search results. I want the user to be able to click on an item in the listview and have the text from that particular list item appear in a textbox that is also in the view.
I can get this to work in Safari on my desktop machine, but it will not work on an iPad.
For the sake of simplicity and to attempt to narrow down the problem, I hard-coded a simple little listview in my View. The results were the same. Works on desktop in Safari, but not on iPad.
Here is the very simplified VIEW code that works in Safari on desktop (Please note that _Header is a separate, partial View):
#section Header
{
<script type="text/javascript">
$('#testJs li').on('click', (function () {
var results = $.trim($(this).text());
$('#testText').val(results);
}));
</script>
#{ Html.RenderPartial("_Header"); }
}
#section Content
{
<input type="text" id="testText">
<ul id="testJs" data-role="listview" data-inset="true" data-theme="c">
<li id="task400" class="tasks">Test task 400</li>
<li id="task295" class="tasks">Test task 295</li>
</ul>
}
Please note that I have tried changing 'click' to 'tap' (see below) with no success. It still doesn't work on iPad.
<script type="text/javascript">
$('#testJs li').on('tap', (function () {
var results = $.trim($(this).text());
$('#testText').val(results);
}));
</script>
I've also tried using the following with the same results. Still doesn't work on the iPad.
<script type="text/javascript">
$('#testJs').delegate('li', 'tap', function () {
var results = $.trim($(this).text());
$('#testText').val(results);
});
</script>
I do wonder if this has something to do with our use of layout pages. We have slightly different layout pages, depending on if the site is being rendered on a mobile device or not.
Mobile Layout View:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
#Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
#Scripts.Render("~/bundles/modernizr")
#Styles.Render("~/Content/mobileCss", "~/Content/css")
<script type="text/javascript">
$(document).ready(function () {
$.mobile.ajaxEnabled = false;
});
</script>
</head>
<body>
<div data-role="page" data-theme="b">
<div data-role="header" data-position="fixed" data-tap-toggle="false">
#if (IsSectionDefined("Header")) {
#RenderSection("Header", false) }
else { <h1>#ViewBag.Title</h1> }
</div>
<div data-role="content">
#RenderSection("Content")
</div>
</div>
</body>
</html>
Desktop Layout View:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
#Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
#Scripts.Render("~/bundles/modernizr")
#Styles.Render("~/Content/mobilecss", "~/Content/css")
</head>
<body>
<div data-role="page" data-theme="b">
<div data-role="header" data-position="fixed" data-tap-toggle="false">
#if (IsSectionDefined("Header")) {
#RenderSection("Header") }
else { <h1>#ViewBag.Title</h1> }
</div>
<div data-role="content">
#RenderSection("Content")
</div>
</div>
</body>
</html>
I've been stuck on this for a few days, so any help would be appreciated. Everything I try works on my desktop, but not on an iPad - which is where I actually need it to function.
Thanks!
Did you try using bind on your testJs li? I'd bind a tapHandler like below:
<script>
$(function(){
$( "#testJs li" ).bind( "tap", tHandler );
function tHandler( event ){
var results = $.trim($(this).text());
$("#testText").val(results);
}
});
</script>
or with on like this should work:
$('#testJs').on('tap', 'li', function (event) {
  var results = $.trim($(this).text());
$("#testText").val(results);
console.log('this should work')
}
Also used double quotes on top example but that shouldn't make a difference I don't think. If it doesn't then make sure you .js references are correct, and use firebug in firefox to debug for any straggling errors.

Resources