Javascript Autocomplete - ColdFusion - with unique identifier - javascript

I have found this tidbit of code - which works fine.
But I also need an associated Identification ID pass along with the name.
So example has state say "California" - but I also have a unique ID associated to Califonrnia say "yye4" etc...
I can create my list easily with coldfusion as below.
var getStates = function(){
return [<cfoutput query=ulist>"#username#",</cfoutput>];
}
But I also need to pass a unique number in the form as well that is also associated to each username.
Thoughts?
<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<cfajaximport tags="cfinput-autosuggest">
<script>
var init = function()
{
autosuggestobj = ColdFusion.Autosuggest.getAutosuggestObject('state');
autosuggestobj.itemSelectEvent.subscribe(foo);
}
var foo = function(event,args)
{
var msg = "";
msg = msg + "Event: " + event + "\n\n";
msg = msg + "Selected Item: " + args[2] + "\n\n";
msg = msg + "Index: " + args[1]._nItemIndex + "\n\n";
alert(msg);
}
var getStates = function(){
return ["California","Connecticut","Colorado","Illinois","Alabama","Iowa","Utah","Alaska"];
}
</script>
</head>
<body>
<h3>Attaching an event handler to the autosuggest object</h3>
<cfform name="mycfform" method="post" >
State:<BR>
<cfinput
type="text"
name="state"
autosuggest="javascript:getStates({cfautosuggestvalue})"
autosuggestMinLength=1
autosuggestBindDelay=1>
<cfset ajaxOnLoad("init")>
</cfform>
</body>
</html>

This, roughly? I used a text box rather than a hidden field so you could see it in action.
<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<cfajaximport tags="cfinput-autosuggest">
<script>
// itcodes would contain the unique numbers instead of sample names.
var itCodes = ["Callie","Connie","Col","Illiana","Allie","Fred","Daphne","Alex"];
var itNames = [];
var init = function()
{
autosuggestobj = ColdFusion.Autosuggest.getAutosuggestObject('state');
autosuggestobj.itemSelectEvent.subscribe(foo);
}
var foo = function(event,args)
{
var msg = "";
var nameIndex = itNames.indexOf(document.getElementById('state').value);
msg = msg + "Event: " + event + "\n\n";
msg = msg + "Selected Item: " + args[2] + "\n\n";
msg = msg + "Index: " + args[1]._nItemIndex + "\n\n";
document.getElementById('hCodes').value = itCodes[nameIndex];
alert(msg);
}
var getStates = function(){
itNames = ["California","Connecticut","Colorado","Illinois","Alabama","Iowa","Utah","Alaska"];
return itNames;
}
</script>
</head>
<body>
<h3>Attaching an event handler to the autosuggest object</h3>
<cfform name="mycfform" method="post" >
State:<BR>
<cfinput
type="text"
name="state" id="state"
autosuggest="javascript:getStates({cfautosuggestvalue})"
autosuggestMinLength=1
autosuggestBindDelay=1>
<input type="text" id="hCodes" name="hCodes" value="">
<cfset ajaxOnLoad("init")>
</cfform>

Related

How do I insert an object data array into a database with AJAX

I want to insert data from an array into a database table in the submit() function where the sql syntax is at. I want to insert the data then redirect to another page after successful. I don't know how to do this with ajax.
I tried to make ajax syntax but I don't know if i'm passing the data correctly for obj.name and obj.books corresponding to their own values in the array.
example:
[{"name":"book1","books":["thisBook1.1","thisBook1.2"]},{"name":"book2","books":["thisBook2.1","thisBook2.2","thisBook2.3"]}]
function submit(){
var arr = [];
for(i = 1; i <= authors; i++){
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
/////////////////////////////////
//I tried this:
$.ajax({
type: "POST",
data: {arr: arr},
url: "next.php",
success: function(){
}
});
/////////////////////////////////
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form action"next.php" method="post">
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
</form>
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str = '<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
//var val = confirm("Are you sure ..?");
//if(val){
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
//}
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
// sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
// mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Send your array to server ,stringify array before sending it to server so in server you can decode json and recover your array, and then insert received data to database
JS
function submit(){
var arr = [];
for(i = 1; i <= authors; i++){
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
sendToServer(arr)
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {arr: JSON.stringify(data)},
url: "next.php",
success: function(){
}
});
}
PHP (next.php)
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $d;
// insert to db
}
Please Keep the following in mind
Javascript/JQuery is client side and hence cannot access the database which is on the server.
You can Send data via AJAX to next.php and then use this data to insert into your database.
To improve debugging, use the following code to ensure the correct data is being delivered in next.php
var_dump($_POST);
Your SQL statements must be executed in next.php using the data passed by $_POST (since your "type" of AJAX request is post).

Firefox Javascript debugger doesn't work - buttons grayed out

I'm trying to debug a JavaScript in Firefox's debugger, and it won't let me set any breakpoints, and all the step buttons (step into, step out) are grayed out. I also tried Firebug, and I have the exact same results - no breakpoints, step buttons grayed out. What gives? This is my first post here, and I apologize for my messy code here. Anywho, here's my code:
<?xml version - "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Page 452 - Exercise 11.7</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial scale=1.0">
<script>
function buttonClicked() {
var article = ["the", "a", "one", "some", "any"];
var noun = ["boy", "girl", "dog", "town", "car"];
var verb = ["drove", "jumped", "ran", "walked", "skipped"];
var preposition = ["to", "from", "over", "under", "on"];
var story = "Once upon a time, ";
var sentence = "";
alert (sentence);
var output = document.getElementById("textArea");
output.value = "";
for (var i=0; i<=3; i++){
sentence += article[Math.floor(Math.random()*article.length)] + " ";
alert(sentence.charAt(0));
alert("Story is " + story);
/* if (charAt(sentence[0-3]) == ".") {
sentence +=
} */
sentence += noun[Math.floor(Math.random()*noun.length)] + " ";
sentence += verb[Math.floor(Math.random()*verb.length)] + " ";
sentence +=
preposition[Math.floor(Math.random()*preposition.length)] + " ";
sentence += article[Math.floor(Math.random()*article.length)] + " ";
sentence += noun[Math.floor(Math.random()*noun.length)] + ". ";
story += sentence;
output.value = story;
window.alert (sentence);
window.alert (story);
// sentence ="";
}
story += "THE END";
// output.value = sentence;
}
</script>
</head>
<body>
<p>Click the button for a funny story!<br/>
<input type="button" id="go" onclick="buttonClicked()" value="Go!"/><br/></p>
<textarea id="textArea" rows="10" cols="30"></textarea>
</body>
</html>

How to create file upload like gmail?

I am having a code with "upload" and done "button". It will select the file on clicking of "upload" and upload the file on clicking "Done" in the given location. But I need to auto-upload file, like Gmail attachment. Can anyone help me out pls
Try this code....
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File(s) size</title>
<script>
function updateSize() {
var nBytes = 0,
oFiles = document.getElementById("uploadInput").files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
}
// end of optional code
document.getElementById("fileNum").innerHTML = nFiles;
document.getElementById("fileSize").innerHTML = sOutput;
}
</script>
</head>
<body onload="updateSize();">
<form name="uploadForm">
<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
<p><input type="submit" value="Done"></p>
</form>
</body>
</html>
You can use a 3rd party libraries for implementing drag, drop and auto upload features as well.
There is one library which I know is http://www.dropzonejs.com/

how to edit the text of row in jQuery +JQM [duplicate]

This question already has an answer here:
Binding the click event of a row with jQuery
(1 answer)
Closed 8 years ago.
I am creating a demo in which I make row in button click .I want to edit it's text when I click generated row "it generate another row inside container".can we give a option to change the text of row while clicking the edit button .It some thing open pop up when your press done it save the text on same id ?
http://jsfiddle.net/k7zJ4/2/
function createTestCase(testCaseName,iscreatedFromScript,jsonObject) {
var id;
if (typeof ($("#testCaseContainer li:last").attr('id')) == 'undefined') {
id = "tc_1";
} else {
id = $("#testCaseContainer li:last").attr('id');
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = '<div class="testcaselist_row">' + '<ul>' + '<li id="' + id + '" class="clickTestCaseRow">' + testCaseName + '<a class="delete deleteTestCase_h"></a><button class="editclass" style="width:200px !important">edit</button ></li>' + '</ul>' + '</div>';
$('#testCaseContainer').append(html);
var elem = document.getElementById('testCaseContainer'); // just to scroll down the line
elem.scrollTop = elem.scrollHeight;
}
Please find the below sample code that will replicate the scenario you want to achieve in your code using jqm.Save the below code as html and click on add text case and click on change text button
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role=" content ">
<div class="contentsubbox" id="testCaseContainer">
<div class="testcaselist_row"><ul id="testCaseLists" data-role="listview" data-theme="a"></ul></div>
</div>
</div>
<footer id="firstPageFooter">
<button class="addtestbtn" id="addTestCase" data-theme="a" style="color: #ffffff!important;">Add Test Case</button>
</footer>
</div>
<script>
$( document ).ready(function() {
console.log( "ready!" );
});
$('#addTestCase').click(function () {
createTestCase("trdt",false,null);
});
$('#testCaseLists').delegate('li', 'tap', function () {
console.log('put your text changing logic here');
$(this).find('a:first').text('text u want to change');//text function shud contain the text
});
function createTestCase(testCaseName,iscreatedFromScript,jsonObject) {
console.log("create test case");
var id;
if ($("div.contentsubbox").find("ul li").length == 0){
id = "tc_1";
} else {
id = $("#testCaseContainer").find("ul li:last").attr('id');
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = "<li id="+ id +" class='clickTestCaseRow'><a href='#' style='color: #ffffff!important;'>" + testCaseName + "</a><a class='delete deleteTestCase_h'></a><button class='editclass' style='width:200px !important'>Change text</button ></li>";
$('#testCaseLists').append(html);
$('#testCaseLists').listview('refresh');
var elem = document.getElementById('testCaseContainer'); // just to scroll down the line
elem.scrollTop = elem.scrollHeight;
}
</script>
</body>
</html>
Add comments if you need further help.

Apply special tags to textarea in all selected text even if there are newline capturing all contents in cursor poisition

The example below writes tag [code] and [/code] to selected text in textarea but only applied to begin and at the end of the string... I'd like to have [code] and [/code]
applied to every part of the strings considerating newline as new string...
example posted performs:
[code]test
test
test[/code]
I'd like to apply instead:
blablabla...
[code]test[/code]
[code]miao miao[/code]
[code]this is teh 3rd string[/code]
etcetera, some extra string
as you can see I'd like to apply code only selected string considerating a new string with newline... it's possible in pure javascript? No jquery or mootools, please only standalone script...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>[javascript code]</title>
<script language="JavaScript" type="text/javascript">
var myValueBefore = "[code]";
var myValueAfter = "[/code]";
function applyCode(myField, myValueBefore, myValueAfter) {
if (document.selection) {
myField.focus();
document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;
} else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValueBefore+ myField.value.substring(startPos, endPos)+ myValueAfter+ myField.value.substring(endPos, myField.value.length);
}
}
</script>
</head>
<body>
<br><br><br>
<table align="center" border="0" cellpadding="15" cellspacing="0" width="70%">
<tr>
<td>
<form action="#" method="post">
<input type="button" value="Apply Code" onclick="javascript:applyCode(test, myValueBefore, myValueAfter);"><br>
<textarea rows="5" cols="130" name="test"></textarea>
</form>
</td>
</tr>
</table>
</body>
</html>
You can develope this codesnippet further:
var myValueBefore = '[code]',
myValueAfter = '[/code]';
function applyCode(myField, myValueBefore, myValueAfter) {
var newLine = new RegExp('\n|\r\n', 'g'), range, selectedText, beforeSelectedText, afterSelectedText;
if (document.selection) {
range = document.selection.createRange();
range.text = myValueBefore + range.text.replace(newLine, myValueAfter + '\n' + myValueBefore) + myValueAfter;
return;
} else {
beforeSelectedText = myField.value.substring(0, myField.selectionStart);
afterSelectedText = myField.value.substr(myField.selectionEnd);
selectedText = myField.value.substring(myField.selectionStart, myField.selectionEnd);
myField.value = beforeSelectedText + myValueBefore + selectedText.replace(newLine, myValueAfter + '\n' + myValueBefore) + myValueAfter + afterSelectedText;
}
return;
}
A live demo at jsFddle.

Categories

Resources