How do I get dependent dropdownlist to work? - javascript

I have 2 php files. One is called getCategory.php. This file is used to query sql server database to get all categories.
The other is called getSubCategory.php.
This queries the db to select all subcategories associated with categories.
The categoryId is the relationship key between the two.
Then I have a file with 2 dropdownlists.
One with id="cat_id" and the second dropdown has an id of sub_cat.
Our requirement is that you select an option from the category dropdown and the second dropdown, the subcategory dropdown, is populated with values based on your selection from category dropdown.
I have managed to do this successfully in the past with asp.net and classic asp.
I am not sure how to get this to work with php.
Particularly difficult for me atleast is the fact that the category and subcategory are in two separate files as indicated above.
Below is what I have managed to put together so far but your expert assistance is greatly needed to help get this working the correct way.
Thanks alot in advance.
<script type="text/javascript">
function getRecs()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.testform.subcat.options.length-1;j>=0;j--)
{
document.testform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="http://servername/path/getCategory.php";
var cat_id=document.getElementById('cat_id').value;
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<h1>
Requests
</h1>
<form>
<div id="tabs">
<ul>
<li>New Request</li>
<li>Existing Request</li>
<li>Request Details</li>
</ul>
<div id="tabs-1">
<div id="accordion">
<h3>Location</h3>
<div>
<p>
<div class="side-by-side clearfix">
<div>
<select name="cat_id" id="cat_id" data-placeholder="Choose a category..." class="chosen-select" style="width:500px;" onchange="getRecs();">
<option value=""></option>
</select>
</div>
<br />
<div>
<select name="sub_cat" id="sub_cat" data-placeholder="Choose a subcategory..." class="chosen-select" style="width:500px;">
<option value=""></option>
</select>
</div>
<br />
<div data-role="content">
<input type="text" name="address" id="address" value=" Enter a room..." onfocus="clearText(this)" onblur="restoreText(this)" style="width:493px;color:#999;font-size:9pt;height:20px;">
</div>
</div>
</p>
</div>
UPDATE
BEGIN - Latest code
<script type="text/javascript">
function getCats()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.reqform.subcat.options.length-1;j>=0;j--)
{
document.reqform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.reqform.subcat.options.add(optn);
}
}
}
var caturl="path/getCategory.php";
caturl=caturl+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(caturl);
httpxml.open("GET",caturl,true);
httpxml.send(null);
}
</script>
<script type="text/javascript">
function getRecs()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.testform.subcat.options.length-1;j>=0;j--)
{
document.testform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="path/getSubCategory.php";
var cat_id=document.getElementById('cat_id').value;
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body onload="getCats()">
<h1>
Requests
</h1>
<form name="reqform" method='POST' action='processRequest.php'>
<div id="tabs">
<ul>
<li>New Request</li>
<li>Existing Request</li>
<li>Request Details</li>
</ul>
<div id="tabs-1">
<div id="accordion">
<h3>Location</h3>
<div>
<p>
<div class="side-by-side clearfix">
<div>
<select name="cat_id" id="cat_id" data-placeholder="Choose a category..." class="chosen-select" style="width:500px;" onchange="getRecs();">
<option value=""></option>
</select>
</div>
<br />
<div>
<select name="sub_cat" id="sub_cat" data-placeholder="Choose a subcategory..." class="chosen-select" style="width:500px;">
<option value=""></option>
</select>
</div>
<br />
<div data-role="content">
<input type="text" name="address" id="address" value=" Enter a room..." onfocus="clearText(this)" onblur="restoreText(this)" style="width:493px;color:#999;font-size:9pt;height:20px;">
</div>
</div>
</p>
</div>
END - Latest code
[{"BuildingDisplay":"132 Mitchell Street Tax Commissioner Office - 132 Mitchell St., SW","BuildingID":"B610012","Address":"132 Mitchell St., SW","City":"Jonesboro","District":"Central","Location":"B610012 132 Mitchell Street Tax Commissioner Office","State":"GA","StreetName":"132 Mitchell St., SW","Zip":"30303","X":2227970.4292704,"Y":1364292.9044986},{"BuildingDisplay":"34 Peachtree Street - 34 Peachtree St.","BuildingID":"B630012","Address":"34 Peachtree St.","City":"Jonesboro","District":"Central","Location":"B630012 34 Peachtree Street","State":"GA","StreetName":"34 Peachtree St.","Zip":"30303","X":2228810.0213674,"Y":1365970.5523757},.....

Why aren't you using jQuery?
In stateck(): You make a JSON.parse to get a JSON Object but then you do a split?
Can you give an example how your httpxml.responseText looks like?
With jQuery your function getRecs() would be:
function getRecs() {
$.get( "getCategory.php", function( data ) {
// I don't know your JSON Structure, but here you could make someting like:
$.each(data, function(_key, _value) {
var opt = $("<option/>");
opt.attr("text", _value.text);
opt.attr("value", _value.value);
$("select").append(opt);
});
}, "json" );
}

Related

Display country state city names and display only country name in two fields

How to display country state city names. The result that I found is displaying only country name in rest two fields.
<html>
<head>
<title>dispaly country state district/title>
<link rel="stylesheet" href="coun.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script>
var stateObject = {
"India": { "AndhraPradensh": ["Guntur", "ananthapur","kurnool","krishna","kadapa"],
"Kerala": ["Thiruvananthapuram", "Palakkad"],
"Goa": ["North Goa", "South Goa"],
},
"The United States of America": {
"califonia": ["California’s 34th congressional district", "California’s 38th congressional district"],
"Florida": ["Florida"]
}, "Canada": {
"Alberta": ["Acadia", "Bighorn"],
"Columbia": ["Washington DC"]
},
}
window.onload = function ()
{
var countySel = document.getElementById("countySel"),
stateSel = document.getElementById("stateSel"),
districtSel = document.getElementById("districtSel");
for (var country in stateObject)
{
countySel.options[countySel.options.length] = new Option(country, country);
}
countySel.onchange = function ()
{
stateSel.length = 1;
districtSel.length = 1;
if (this.selectedIndex < 1) return;
for (var state in stateObject[this.value])
{
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
countySel.onchange();
stateSel.onchange = function ()
{
districtSel.length = 1;
if (this.selectedIndex < 1) return;
var district = stateObject[countySel.value][this.value];
for (var i = 0; i < district.length; i++) {
districtSel.options[districtSel.options.length] = new Option(district[i], district[i]);
}
}
}
</script>
Function is not working properly. The Problem is which user is selected is not displaying or stored correctly.
<script LANGUAGE="JavaScript" type="text/javascript">
function display()
{
var j=document.getElementById("countySel").selectedIndex;
var k=document.getElementsByTagName("option")[j].value;
var l=document.getElementById("stateSel").selectedIndex;
var m=document.getElementsByTagName("option")[l].value;
var n=document.getElementById("districtSel").selectedIndex;
var o=document.getElementsByTagName("option")[n].value;
var siva=document.getElementById("sai");
var displaysetting=siva.style.display;
if (typeof(Storage) !== "undefined")
{
localStorage.setItem('country',k)
localStorage.setItem('state',m)
localStorage.setItem('district',o)
if(displaysetting == "block")
{
siva.style.display='none';
inputfields.style.display='block';
document.getElementById("country1").innerHTML=localStorage.getItem('country');
document.getElementById("state1").innerHTML=localStorage.getItem('state');
document.getElementById("district1").innerHTML=localStorage.getItem('district');
}
else
{
siva.style.display='block';
}
}
else
{
document.getElementById("name1").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>
</head>
<body>
<form class="container" id="sai" style="display: block;" >
<div class="row">
<div class="form-group col-4">
<label>Select Country:</label>
<select name="state" id="countySel" class="form-control" size="1">
<option value="" selected="selected" >Select Country</option>
</select>
</div>
<div class="form-group col-4">
<label>Select State:</label>
<select name="country" id="stateSel" class="form-control" size="1">
<option value="" selected="selected" >Please select Country first</option>
</select>
</div>
<div class="form-group col-4">
<label>Select District:</label>
<select name="district" id="districtSel" class="form-control" size="1">
<option value="" selected="selected">Please select State first</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-secondary" type="submit" value="submit" onclick="display()" style="width: 100px;">SUBMIT</button>
</div>
</div>
</form>
<div class="container" id="inputfields" style="margin-top: 15px; display: none;">
<div class="row">
<div class="col-6">
<div id="img" style="width: 350px; height: 350px;">
</div>
</div>
<div class="col-6">
<div> COUNTRY: <p id="country1"></p></div>
<div> STATE: <p id="state1"></p></div>
<div> DISTRICT: <p id="district1"></p></div>
</div>
</div>
</div>
</body>
I tried a lot but i didn't found where i done mistake. Can any please sort out this problem.
You can modify your display() function like this:
let selectedCountryIndex=document.getElementById("countySel").selectedIndex;
let selectedStateIndex=document.getElementById("stateSel").selectedIndex;
let selectedDistrictIndex=document.getElementById("districtSel").selectedIndex;
let opt1 = document.getElementById("countySel").options[selectedCountryIndex].value;
let opt2 = document.getElementById("stateSel").options[selectedStateIndex].value;
let opt3 = document.getElementById("districtSel").options[selectedDistrictIndex].value;

Issue in selecting search result on up and down key (asp.net page)

Want to select given suggestions on search using onclick and Key up & down function.
Form Screenshot:
enter image description here
The html code of form is as follow:
<div class="search">
<div>
<i>
<input name="ctl00$txtcat" type="text" value="Enter Search Key" id="txtcat" class="product" autocomplete="off" onfocus="if(this.value =='Enter Search Key') this.value = '';" onblur="if(this.value == '') this.value = 'Enter Search Key';" onkeyup="api_helper.callAjax();" style="color:#787878;">
</i>
</div>
<div>
<input type="submit" name="ctl00$btnSearch" value="GO" id="btnSearch" class="btn_go" style="height:38px;width:61px;" />
<div id="myDiv"><table width="100%"><tbody><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Accounting Services</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Attorneys</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Appliances</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">AC/Heating</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">American</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Applicants </td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Automotive</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">ATM</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Accessories</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Asian</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Allergy/Breathing Specialists</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Apartment</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Auto Parts</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Accounting & Finance</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Advertising</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Auto</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Automotive</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Architects</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">African</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Asian</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Auto Parts</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Afghani</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Aqeeqah</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Accounting & Finance</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Automotive</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Apartment</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Automotive</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Accupuncture</td></tr><tr><td class="select" onclick="api_helper.AddtoTaxtBox(this.innerHTML)">Auctions</td></tr></tbody></table></div>
Calling the Result using following script:
<script language="javascript" type="text/javascript">
if (typeof (api_helper) == 'undefined') { api_helper = {} }
api_helper.doAjax = function (HandlerUrl, displayDiv) {
var Req; try { Req = new XMLHttpRequest(); }
catch (e) {
try { Req = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {
try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { return false; }
}
} Req.onreadystatechange = function () {
if (Req.readyState == 4) {
var d = document.getElementById(displayDiv);
d.innerHTML = Req.responseText;
}
}
Req.open("GET", HandlerUrl, true); Req.send(null);
}
api_helper.callAjax = function () {
var text = document.getElementById("txtcat").value;
if (text != "") {
var requestUrl = "Category_search.ashx?name=" + text;
var displayDiv = "myDiv";
api_helper.doAjax(requestUrl, displayDiv);
}
}
api_helper.AddtoTaxtBox = function (txt) {
var txtfinal = txt.toString();
txtfinal = txtfinal.replace('&', '&');
document.getElementById("txtcat").value = txtfinal;
document.getElementById("myDiv").innerHTML = "";
}
</script>
I need help to select displayed suggestion on click and key up & down. Selecting the input is set on onclick till now.

Display text box on selecting second linked dropdown menu

I made two linked drop down menus with ajax and php. My index.php:
<html>
<head>
</head>
<body>
<form name="form1" action="submit.php" method='POST'>
<select name="country" onchange="window.getStates()">
<option> Select Country</option>
<option value="pakistan">Pakistan</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
</select>
<input type="text" id="area" style="display: none;" size="16" placeholder="
Enter value"></input>
<input type="submit" id="submit" style="display: none" name="submit" value="submit">
</form>
<script type="text/javascript">
function show() {
{
document.getElementById('area').style.display = 'inline-block';
document.getElementById('submit').style.display = 'inline-block';
}
}
function getStates() {
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest;
} catch (e) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
var form = document['form1'];
var country = form['country'].value;
xmlhttp.open("GET", "http://localhost/getStates.php?country=" + country, true);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
var s = document.createElement("select");
s.onchange = show();
s.name = "state";
s.innerHTML = this.responseText;
if (form['state']) {
form.replaceChild(s, form['state']);
} else
form.insertBefore(s, form['submit']);
}
}
xmlhttp.send(null);
}
}
</script>
</body>
</html>
my getStates.php code:
<?php
$states=array(
"pakistan" => array("NWFP","Sindh","Bala","Punjab"),
"india" => array("delhi","gujrat","goa","U.P."),
"usa" => array("bgjs","hhtrs","Bhtrshts","Utah"),
"uk" => array("England","Scotland","Bahwgla","Punthwthjab")
);
if(isset($_GET['country']))
{
$c = $_GET['country'];
if(isset($states[$c]))
{
for($i = count($states[$c]) -1; $i>=0; $i--)
{
echo "<option value='".$states[$c][$i]."'>".$states[$c][$i]."</option>";
}
}
}
?>
In the index.php, when i select an option from the second drop down, i want the text box and submit button to be made divisible. How can i do this in a simple way? Please be clear and slow because i am new to ajax.
s.onchange=show();
is not working. That was just a random try but i don't know why it is wrong. Thanks!

Not getting forward for the page in Firefox

I am developing a simple log in form by using XML file values. I have an XML with values last name and first name. I am accessing the file and checking the values against the given values in order to validate log in.
It works fine in chrome, IE and safari. But, In mozilla it is not getting forwarded to the next page. The page just stays in the same page and shows a loading URL icon for indefinite time.
Here is my CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link href="css/stylemp3.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form onsubmit="return myFunction()" action="action.html">
First name:<br/>
<input type="text" required="required" name="firstname" id="firstname"/>
<br>
Last name:<br>
<input type="password" required="required" name="lastname" id="lastname"/>
<br/>
<select class="dropdown" id="ddl">
<option value="haha" selected="selected">show</option>
<option value="hihi" >hide</option>
</select>
<br/>
<input type="text" name="hide" id="hidee" class="hide"/>
<br/>
<input button type="submit" value="Submit"/>
</form>
<div></div>
<script>
window.onload = function() {
document.getElementById("firstname").focus();
};
$( "#ddl" )
.change(function () {
if($( "select option:selected" ).text() == "hide")
{
$("#hidee").hide();
}
else
{
$("#hidee").show();
}
})
.change();
</script>
<script>
function myFunction() {
var lastname = document.getElementsByName('lastname')[0].value;
var firstname = document.getElementsByName('firstname')[0].value;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","login.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("login");
for (i=0;i<x.length;i++)
{
alert(x[i].getElementsByTagName("firstname")[0].childNodes[0].nodeValue);
if((x[i].getElementsByTagName("firstname")[0].childNodes[0].nodeValue) == firstname)
{
alert("Smileeee.....:-))");
if((x[i].getElementsByTagName("lastname")[0].childNodes[0].nodeValue) == lastname)
{
alert("login Successful!!!!!");
return true;
break;
}
}
}
return false;
}
</script>
</body>
</html>

Autocomplete suggestions within Rich Text Editor

I'm presently working on a project to get a rich text editor up and running that allows for autocompletion suggestions to come up at the cursor's location after a token key is pressed, for example '#'. I have gotten this working inside of a textarea without issue through jQuery, but it won't play nice inside of a RTE iFrame.
The autocomplete example I have works through AJAX to scan a server file to check the text being typed for autocomplete 'tags'.
Editor from Mozilla: www-archive.mozilla.org/editor/midasdemo/
Autocomplete from: www.amirharel.com/2011/03/07/implementing-autocomplete-jquery-plugin-for-textarea/
<html>
<head>
<style type="text/css">
.imagebutton {height: 22; width: 23; border: solid 2px #C0C0C0; background-color: #C0C0C0}
.image {position: relative; left: 1; top: 1; height:20; width:21; border:none;}
.toolbar {height: 30; background-color: #C0C0C0;}
</style>
<script>
var command = "";
function InitToolbarButtons() {
var kids = document.getElementsByTagName('DIV');
for (var i=0; i < kids.length; i++) {
if (kids[i].className == "imagebutton") {
kids[i].onmouseover = tbmouseover;
kids[i].onmouseout = tbmouseout;
kids[i].onmousedown = tbmousedown;
kids[i].onmouseup = tbmouseup;
kids[i].onclick = tbclick;
}
}
}
function tbmousedown(e)
{
var evt = e ? e : window.event;
this.firstChild.style.left = 2;
this.firstChild.style.top = 2;
this.style.border="inset 2px";
if (evt.returnValue) {
evt.returnValue = false;
} else if (evt.preventDefault) {
evt.preventDefault( );
} else {
return false;
}
}
function tbmouseup()
{
this.firstChild.style.left = 1;
this.firstChild.style.top = 1;
this.style.border="outset 2px";
}
function tbmouseout()
{
this.style.border="solid 2px #C0C0C0";
}
function tbmouseover()
{
this.style.border="outset 2px";
}
function insertNodeAtSelection(win, insertNode)
{
// get current selection
var sel = win.getSelection();
// get the first range of the selection
// (there's almost always only one range)
var range = sel.getRangeAt(0);
// deselect everything
sel.removeAllRanges();
// remove content of current selection from document
range.deleteContents();
// get location of current selection
var container = range.startContainer;
var pos = range.startOffset;
// make a new range for the new selection
range=document.createRange();
if (container.nodeType==3 && insertNode.nodeType==3) {
// if we insert text in a textnode, do optimized insertion
container.insertData(pos, insertNode.nodeValue);
// put cursor after inserted text
range.setEnd(container, pos+insertNode.length);
range.setStart(container, pos+insertNode.length);
} else {
var afterNode;
if (container.nodeType==3) {
// when inserting into a textnode
// we create 2 new textnodes
// and put the insertNode in between
var textNode = container;
container = textNode.parentNode;
var text = textNode.nodeValue;
// text before the split
var textBefore = text.substr(0,pos);
// text after the split
var textAfter = text.substr(pos);
var beforeNode = document.createTextNode(textBefore);
afterNode = document.createTextNode(textAfter);
// insert the 3 new nodes before the old one
container.insertBefore(afterNode, textNode);
container.insertBefore(insertNode, afterNode);
container.insertBefore(beforeNode, insertNode);
// remove the old node
container.removeChild(textNode);
} else {
// else simply insert the node
afterNode = container.childNodes[pos];
container.insertBefore(insertNode, afterNode);
}
range.setEnd(afterNode, 0);
range.setStart(afterNode, 0);
}
sel.addRange(range);
};
function getOffsetTop(elm) {
var mOffsetTop = elm.offsetTop;
var mOffsetParent = elm.offsetParent;
while(mOffsetParent){
mOffsetTop += mOffsetParent.offsetTop;
mOffsetParent = mOffsetParent.offsetParent;
}
return mOffsetTop;
}
function getOffsetLeft(elm) {
var mOffsetLeft = elm.offsetLeft;
var mOffsetParent = elm.offsetParent;
while(mOffsetParent){
mOffsetLeft += mOffsetParent.offsetLeft;
mOffsetParent = mOffsetParent.offsetParent;
}
return mOffsetLeft;
}
function tbclick()
{
if ((this.id == "forecolor") || (this.id == "hilitecolor")) {
parent.command = this.id;
buttonElement = document.getElementById(this.id);
document.getElementById("colorpalette").style.left = getOffsetLeft(buttonElement);
document.getElementById("colorpalette").style.top = getOffsetTop(buttonElement) + buttonElement.offsetHeight;
document.getElementById("colorpalette").style.visibility="visible";
} else if (this.id == "createlink") {
var szURL = prompt("Enter a URL:", "http://");
if ((szURL != null) && (szURL != "")) {
document.getElementById('edit').contentWindow.document.execCommand("CreateLink",false,szURL);
}
} else if (this.id == "createimage") {
imagePath = prompt('Enter Image URL:', 'http://');
if ((imagePath != null) && (imagePath != "")) {
document.getElementById('edit').contentWindow.document.execCommand('InsertImage', false, imagePath);
}
} else if (this.id == "createtable") {
e = document.getElementById("edit");
rowstext = prompt("enter rows");
colstext = prompt("enter cols");
rows = parseInt(rowstext);
cols = parseInt(colstext);
if ((rows > 0) && (cols > 0)) {
table = e.contentWindow.document.createElement("table");
table.setAttribute("border", "1");
table.setAttribute("cellpadding", "2");
table.setAttribute("cellspacing", "2");
tbody = e.contentWindow.document.createElement("tbody");
for (var i=0; i < rows; i++) {
tr =e.contentWindow.document.createElement("tr");
for (var j=0; j < cols; j++) {
td =e.contentWindow.document.createElement("td");
br =e.contentWindow.document.createElement("br");
td.appendChild(br);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
insertNodeAtSelection(e.contentWindow, table);
}
} else {
document.getElementById('edit').contentWindow.document.execCommand(this.id, false, null);
}
}
function Select(selectname)
{
var cursel = document.getElementById(selectname).selectedIndex;
/* First one is always a label */
if (cursel != 0) {
var selected = document.getElementById(selectname).options[cursel].value;
document.getElementById('edit').contentWindow.document.execCommand(selectname, false, selected);
document.getElementById(selectname).selectedIndex = 0;
}
document.getElementById("edit").contentWindow.focus();
}
function dismisscolorpalette()
{
document.getElementById("colorpalette").style.visibility="hidden";
}
function Start() {
document.getElementById('edit').contentWindow.document.designMode = "on";
try {
document.getElementById('edit').contentWindow.document.execCommand("undo", false, null);
} catch (e) {
alert("This demo is not supported on your browser.");
}
InitToolbarButtons();
if (document.addEventListener) {
document.addEventListener("mousedown", dismisscolorpalette, true);
document.getElementById("edit").contentWindow.document.addEventListener("mousedown", dismisscolorpalette, true);
document.addEventListener("keypress", dismisscolorpalette, true);
document.getElementById("edit").contentWindow.document.addEventListener("keypress", dismisscolorpalette, true);
} else if (document.attachEvent) {
document.attachEvent("mousedown", dismisscolorpalette, true);
document.getElementById("edit").contentWindow.document.attachEvent("mousedown", dismisscolorpalette, true);
document.attachEvent("keypress", dismisscolorpalette, true);
document.getElementById("edit").contentWindow.document.attachEvent("keypress", dismisscolorpalette, true);
}
}
</script>
<style type="text/css" style="display:none">ul.auto-list{display:none;position:absolute;top:0px;left:0px;border:1px solid green;background-color:#A3DF99;padding:0;margin:0;list-style:none;}ul.auto-list>li:hover,ul.auto-list>li[data-selected=true]{background-color:#236574;}ul.auto-list>li{border:1px solid gray;cursor:default;padding:2px;}mark{font-weight:bold;}</style>
<style type="text/css">#ta{width:300px;height :100px;font-size:11px;font-family:"Helvetica Neue",Arial,sans-serif;white-space:pre;}</style>
<script src="js/jquery-1.5.js" type="text/javascript"></script>
<script src="js/autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
var tags = [];
function initEditorTextarea(){
$.ajax("autotags.txt",{
success: function(data, textStatus, jqXHR){
tags = data.replace(/\r/g, "" ).split("\n");
$("#editor textarea").autocomplete({
wordCount:1,
on: {
query: function(text,cb){
var words = [];
for( var i=0; i<tags.length; i++ ){
if( tags[i].toLowerCase().indexOf(text.toLowerCase()) == 0 ) words.push(tags[i]);
if( words.length > 5 ) break;
}
cb(words);
}
}
});
}
});
}
$(document).ready(function(){
Start();
initEditorTextarea();
});
</script>
</head>
<body>
<div id="editor">
<textarea style="width: 750px; height: 150px; margin-bottom: 10px;"></textarea>
</div>
<table bgcolor="#C0C0C0" id="toolbar">
<tr>
<td>
<select id="formatblock" onchange="Select(this.id);">
<option value="<p>">Normal</option>
<option value="<p>">Paragraph</option>
<option value="<h1>">Heading 1 <H1></option>
<option value="<h2>">Heading 2 <H2></option>
<option value="<h3>">Heading 3 <H3></option>
<option value="<h4>">Heading 4 <H4></option>
<option value="<h5>">Heading 5 <H5></option>
<option value="<h6>">Heading 6 <H6></option>
<option value="<address>">Address <ADDR></option>
<option value="<pre>">Formatted <PRE></option>
</select>
</td>
<td>
<select id="fontname" onchange="Select(this.id);">
<option value="Font">Font</option>
<option value="Arial">Arial</option>
<option value="Courier">Courier</option>
<option value="Times New Roman">Times New Roman</option>
</select>
</td>
<td>
<select unselectable="on" id="fontsize" onchange="Select(this.id);">
<option value="Size">Size</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</td>
<td>
<div class="imagebutton" id="bold"><img class="image" src="images/bold.gif" alt="Bold" title="Bold"></div>
</td>
<td>
<div class="imagebutton" id="italic"><img class="image" src="images/italic.gif" alt="Italic" title="Italic"></div>
</td>
<td>
<div class="imagebutton" id="underline"><img class="image" src="images/underline.gif" alt="Underline" title="Underline"></div>
</td>
<td>
</td>
<td>
<div style="left: 10;" class="imagebutton" id="forecolor"><img class="image" src="images/forecolor.gif" alt="Text Color" title="Text Color"></div>
</td>
<td>
<div style="left: 40;" class="imagebutton" id="hilitecolor"><img class="image" src="images/backcolor.gif" alt="Background Color" title="Background Color"></div>
</td>
<td>
<div style="left: 10;" class="imagebutton" id="justifyleft"><img class="image" src="images/justifyleft.gif" alt="Align Left" title="Align Left"></div>
</td>
<td>
<div style="left: 40;" class="imagebutton" id="justifycenter"><img class="image" src="images/justifycenter.gif" alt="Center" title="Center"></div>
</td>
<td>
<div style="left: 70;" class="imagebutton" id="justifyright"><img class="image" src="images/justifyright.gif" alt="Align Right" title="Align Right"></div>
</td>
<td>
<div style="left: 10;" class="imagebutton" id="insertorderedlist"><img class="image" src="images/orderedlist.gif" alt="Ordered List" title="Ordered List"></div>
</td>
<td>
<div style="left: 40;" class="imagebutton" id="insertunorderedlist"><img class="image" src="images/unorderedlist.gif" alt="Unordered List" title="Unordered List"></div>
</td>
<td>
<div style="left: 10;" class="imagebutton" id="outdent"><img class="image" src="images/outdent.gif" alt="Outdent" title="Outdent"></div>
</td>
<td>
<div style="left: 40;" class="imagebutton" id="indent"><img class="image" src="images/indent.gif" alt="Indent" title="Indent"></div>
<td>
<div style="left: 10;" class="imagebutton" id="createlink"><img class="image" src="images/link.gif" alt="Insert Link" title="Insert Link"></div>
</td>
<td>
<div style="left: 10;" class="imagebutton" id="createimage"><img class="image" src="images/image.gif" alt="Insert Image" title="Insert Image"></div>
</td>
<td>
<div style="left: 10;" class="imagebutton" id="createtable"><img class="image" src="images/table.gif" alt="Insert Table" title="Insert Table"></div>
</td>
</tr>
</table>
<br>
<iframe id="edit" width="100%" height="400px"></iframe>
<iframe width="250" height="170" id="colorpalette" src="images/colors.html" style="visibility:hidden; position: absolute;"></iframe>
<script>
function viewsource(source)
{
var html;
if (source) {
html = document.createTextNode(document.getElementById('edit').contentWindow.document.body.innerHTML);
document.getElementById('edit').contentWindow.document.body.innerHTML = "";
html = document.getElementById('edit').contentWindow.document.importNode(html,false);
document.getElementById('edit').contentWindow.document.body.appendChild(html);
document.getElementById("toolbar").style.visibility="hidden";
} else {
html = document.getElementById('edit').contentWindow.document.body.ownerDocument.createRange();
html.selectNodeContents(document.getElementById('edit').contentWindow.document.body);
document.getElementById('edit').contentWindow.document.body.innerHTML = html.toString();
document.getElementById("toolbar").style.visibility="visible";
}
}
function usecss(source)
{
document.getElementById('edit').contentWindow.document.execCommand("useCSS", false, !(source));
}
function readonly(source)
{
document.getElementById('edit').contentWindow.document.execCommand("readonly", false, !(source));
}
</script>
<input type="checkbox" onclick="viewsource(this.checked)">
View HTML Source</input>
</body>
</html>
I've spent a lot of time looking at browser based solutions and JS based options but none of them have worked yet. The best example I can find of what I'm trying to accomplish is the Confluence RTE environment: https://confluence.atlassian.com/display/CONF33/Using+Autocomplete+in+the+Rich+Text+Editor
I don't need anything super fancy, just the ability to run a WYSIWYG sort of basic rich text editor with the ability to autocomplete on a specific key input. How should I approach getting this to work?
EDIT: Had to change the links above the code as I'm new here so they wouldn't automatically be linked.

Categories