JQuery and Google Visualization
I am using JQuery in my page. Part of my page is a Google Visualization table, and trying to use JQuery from within this table causes an error.. Basically I used a form submit() event to all forms with class "lala". As you can see in the example below, the two forms outside of the Google Visualization table work fine. However, the form inside the table does not response to the event... Any ideas? (Example available at http://jsbin.com/izone/2 )
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://aja开发者_JAVA技巧x.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id='table_div'></div>
<form class="lala"><input type="text" id="textv" value="Outer Text 1" size="5"><input type="submit" value="Go!"></form>
<form class="lala"><input type="text" id="textv" value="Outer Text 2" size="5"><input type="submit" value="Go!"></form>
</body>
</html>
Javascript
$(document).ready(function(){
$("form.lala").submit(function() {
alert($('#textv',this).val());
});
});
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Form');
data.addRows(1);
data.setCell(0, 0, '<form class="lala"><input type="text" id="textv" value="Inner Text" size="5"><input type="submit" value="Go!"></form>');
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {'allowHtml':true});
}
Thanks! Joel
You've got two input
s with the same id - generally not a good idea, especially if you're trying to get the value of an input
by id.
Instead of using $(document).ready(function) you can use google.visualization.events.addListener. Change the last 2 lines of your drawTable() as following:
var table = new google.visualization.Table(document.getElementById('table_div'));
google.visualization.events.addListener(table, 'ready', function() {
$("form.lala").submit(function() {
alert($('#text-in-form',this).val());
});
});
table.draw(data, {'allowHtml':true});
Notice I've changed the id of the input text in table to 'text-in-form'.
精彩评论