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!
Related
I have a simple text file:
Text1
Text2
Text3
TextN
And would like to create an interface where each time the user presses the next button the text area will be populated with the next text. I guess I have to use an array for that but I am having problems changing the text with the next button. Moreover the code I have only works on Firefox. Does this mean that when I put the website on a server this will be interpreted by Firefox clients only?
function test() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var contents = xmlhttp.responseText;
myArray = contents.split("\n");
}
}
xmlhttp.open("GET", "deeds.txt", true);
xmlhttp.send();
}
function nextDeed() {
document.getElementById('deed').innerHTML = myArray[0]
}
<html>
<body>
<h1 align="center" style="font-family:Arial;">RELATION TAGGING </h1>
<textarea id="deed" rows="15" cols="160"></textarea>
<input type="button" value="next" onclick="nextDeed()" /><br/>
<div id="result">Result</div>
</body>
</html>
step = 0;
$("#next").click(function(){
step = step +1;
$.ajax({
url: "./text.php?"+"step="+step,
success: function(data){
$("#deed").val(data);
}
});
});
;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 align="center" style="font-family:Arial;" >RELATION TAGGING </h1>
<textarea id="deed" rows="15" cols="160">
</textarea>
<input type="button" id="next" value="next" /><br/>
<div id="result">Result</div>
</body>
</html>
PHP code : <?php $data = file_get_contents("file".$_GET["t"].".txt"); echo $data;?>
I am trying to retain div on exiting a page and am not very sure how to go about this, I am aware that I can achieve this using localStorage but cannot figure out how, here is the script
<script type="text/javascript">
function ShowHideDiv() {
var ddlPassport = document.getElementById("ddlPassport");
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = ddlPassport.value == "Y" ? "block" : "none";
var ddlPassport = document.getElementById("ddlPassport");
var dvPassports = document.getElementById("dvPassports");
dvPassports.style.display = ddlPassport.value == "N" ? "block" : "none";
}
</script>
<span>Do you have Passport?</span>
<select id = "ddlPassport" onchange = "ShowHideDiv()">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<!--<hr />-->
<div id="dvPassport" style="display: none">
Passport Number:
<input type="text" id="txtPassportNumber" />
</div>
<div id="dvPassports" style="display: none">
Other Number:
<input type="text" id="txtPassportNumbers" />
</div>
thank you very much for your help!
In the beforeunload of the window object, set whatever you like into localStorage.
Also, it's better to use CSS classes than to apply individual style properties.
window.addEventListener("DOMContentLoaded", function(){
var ddlPassport = document.getElementById("ddlPassport");
var dvPassport = document.getElementById("dvPassport");
var dvPassports = document.getElementById("dvPassports");
var passNum = document.getElementById("txtPassportNumber");
var passNums = document.getElementById("txtPassportNubmers");
ddlPassport.addEventListener("change", ShowHideDiv);
// Restore prior saved data:
if(localStorage.getItem("passportNumber")){
passNum.value = localStorage.getItem("passportNumber");
ShowHideDiv();
} else if(localStorage.getItem("passportNumbers")) {
passNums.value = localStorage.getItem("passportNumbers");
ShowHideDiv();
}
var numElement = null;
function ShowHideDiv() {
if(this.value === "y"){
dvPassport.classList.remove("hidden");
dvPassports.classList.add("hidden");
numElement = dvPassport;
} else if(this.value === "n") {
dvPassport.classList.add("hidden");
dvPassports.classList.remove("hidden");
numElement = dvPassports;
} else {
dvPassport.classList.add("hidden");
dvPassports.classList.add("hidden");
}
}
// As the user is leaving the page, store the text value:
window.addEventListener("beforeunload", function(){
if(numElement === dvPassport){
localStorage.setItem("passportNumber", passNum.value);
} else if(numElement === dvPassports) {
localStorage.setItem("passportNumbers", passNums.value);
}
});
});
.hidden { display:none; }
<span>Do you have Passport?</span>
<select id = "ddlPassport">
<option value="">--- Select ---</option>
<option value="n">No</option>
<option value="y">Yes</option>
</select>
<div id="dvPassport" class="hidden">
Passport Number:
<input type="text" id="txtPassportNumber">
</div>
<div id="dvPassports" class="hidden">
Other Number:
<input type="text" id="txtPassportNumbers">
</div>
I am new to JavaScript. I have made a form and taken textarea and button and displayed the text of the textarea in a div tag and have taken 2 buttons.
Now I want on click of first button the size of output in div tag increase and similarly on click of second button it becomes bold and so on ...
<html>
<body>
<form name="myform" onsubmit="return fuc1()">
<table>
<tr><td>Description</td><td> <textarea name="message1" id="message" rows="10" cols="30" font-size:"100px";></textarea><br/></td></tr>
<tr><td><button onclick=fincrease() type="button" name="sizeinc" id="sizeinc" >Increase SIZE</button></td>
<td><button type="button" name="sizedec" id="sizedec" >Decrease SIZE</button></td></tr>
<tr><td><button type="button" onclick="fbold()" name="bold" id="bold" >BOLD</button></td>
<td><button type="button" name="italic" id="italic" >ITALIC</button></td>
<td><button type="button" name="underline" id="underline" >UNDERLINE</button></td></tr>
<tr><td><select id="colors" onclick="fcolor()">
<option value="Default">(Please select color)</option>
<option value="pink">PINK</option>
<option value="yellow">YELLOW</option>
<option value="green">GREEN</option>
<option value="orange">ORANGE</option>
</select>
</td>
<td><select id="borders" onclick="fborder()">
<option value="Default">(Please select border)</option>
<option value="dashed">DOTTED</option>
<option value="thick solid">Thick Solid</option>
<option value="solid">Solid</option>
</select></td>
</tr>
<tr><td><input type="submit"/></td></tr>
</table>
<div id="div1">OUTPUT</div>
</form>
<script type="text/javascript">
function fuc1()
{
var tex=document.getElementById("message").value;
var colr=document.getElementById("colors").value;
var bord=document.getElementById("borders").value;
var increase=document.getElementById("sizeinc").value;
var decrease=document.getElementById("sizedec").value;
var italic1=document.getElementById("italic").value;
var bold1=document.getElementById("bold").value;
var under=document.getElementById("underline").value;
html=tex;
document.getElementById("div1").innerHTML=html;
return false;
}
function fcolor(){
var c=document.getElementById("colors").value;
if(c=="pink")
{
document.getElementById("div1").style.color= c;
}
if(c=="yellow")
{
document.getElementById("div1").style.color= c;
}
if(c=="green")
{
document.getElementById("div1").style.color= c;
}
if(c=="orange")
{
document.getElementById("div1").style.color= c;
}
}
function fborder(){
var b=document.getElementById("borders").value;
if(b=="dashed")
{
document.getElementById("div1").style.border=b;
}
if(b=="thick solid")
{
document.getElementById("div1").style.border=b;
}
if(b=="solid")
{
document.getElementById("div1").style.border=b;
}
}
function fbold()
{
}
</script>
Remember to add them to the onclick events of your buttons
function fbold()
{
if (document.getElementById("div1").style.fontWeight == "bold")
{
document.getElementById("div1").style.fontWeight = "normal"
}
else
{
document.getElementById("div1").style.fontWeight = "bold";
}
}
function fItalic() {
if (document.getElementById("div1").style.fontStyle == "italic") {
document.getElementById("div1").style.fontStyle = "normal"
}
else {
document.getElementById("div1").style.fontStyle = "italic";
}
}
function fUnderline()
{
if (document.getElementById("div1").style.textDecorationUnderline) {
document.getElementById("div1").style.textDecorationUnderline = false
}
else {
document.getElementById("div1").style.textDecorationUnderline = true;
}
}
function fincrease()
{
if (document.getElementById("div1").style.fontSize == undefined || document.getElementById("div1").style.fontSize == "")
{
document.getElementById("div1").style.fontSize = "14px"
}
document.getElementById("div1").style.fontSize = (Number(document.getElementById("div1").style.fontSize.replace("px", "")) + 1) + "px"
}
function fdecrease() {
if (document.getElementById("div1").style.fontSize == undefined || document.getElementById("div1").style.fontSize == "") {
document.getElementById("div1").style.fontSize = "14px"
}
document.getElementById("div1").style.fontSize = (Number(document.getElementById("div1").style.fontSize.replace("px", "")) - 1) + "px"
}
General tip: add some console.log("...") messages to your functions and open your page in a browser that has a console (e.g. in Google Chrome, press F12). That will enable you to see when a function is called while you test it.
More specific tip: on the select lists, replace onclick with onchange.
hello i want to hide the extra spacing taken by visibility:hidden. In the code when i select sort by date then it is replaced by default content, but when select sort by topic it comes under sort by date output. But i don't want this. I want to replace o/p of sort of topic to sort by date. I think it comes because of using visibility:hidden. Can anyone suggest me how i remove that space. I used display:none too, but no use.
<html>
<head>
<script>
function onloadfun()
{
document.getElementById("hideall").style.visibility="hidden";
}
function optionCheck()
{
if( document.getElementById("sorting").value=="bydate")
{
document.getElementById("topic1").style.visibility ="visible";
document.getElementById("topic").style.visibility ="hidden";
document.getElementById("showByDefault").style.display ="none";
}
if( document.getElementById("sorting").value =="bytopic")
{
document.getElementById("topic1").style.visibility ="hidden";
document.getElementById("topic").style.visibility ="visible";
document.getElementById("showByDefault").style.display ="none";
}
// validation of dropdownlist
var x = document.getElementById("sorting");
var option = x.options[x.selectedIndex].value;
var strUser1 = x.options[x.selectedIndex].text;
if(option=="s")
{
document.form.options.focus();
return false;
}
return true;
}
</script>
</head>
<body onLoad="onloadfun()">
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br /><br /><hr /><br /><br />
<?php include 'connection.php'; ?>
<div id="showByDefault">
<?php
echo "default content";
?>
</div>
<div id="hideall">
<div id="topic1">
<?php echo "hideing 1"; ?>
</div>
<div id="topic">
<?php echo "hideing 2"; ?>
</div>
</div>
</body>
</html>
Some reading:
visibility
The visibility CSS property has two purposes:
The hidden value hides an element but leaves space where it would
have been. The collapse value hides rows or columns of a table. It
also collapses XUL elements
display
In addition to the many different display box types, the value none
lets you turn off the display of an element; when you use none, all
descendant elements also have their display turned off. The document
is rendered as though the element doesn't exist in the document tre
An example based on your code but using display and setting it by a class using Element.classList.
var sorting = document.getElementById('sorting'),
showByDefault = document.getElementById('showByDefault'),
topic = document.getElementById('topic'),
topic1 = document.getElementById('topic1');
sorting.addEventListener('change', function optionCheck(e) {
var target = e.target;
if (target.value === 's') {
console.log('Do something here.');
} else if (target.value === 'bydate') {
topic1.classList.remove('hide');
topic.classList.add('hide');
showByDefault.classList.add('hide');
} else if (target.value === 'bytopic') {
topic1.classList.add('hide');
topic.classList.remove('hide');
showByDefault.classList.add('hide');
}
}, false);
#sorting {
width: 140px;
}
hr {
margin-top: 2em;
margin-bottom: 2em;
}
.hide {
display: none;
}
<form name="form">
<select id="sorting">
<option value="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<hr>
<div id="showByDefault">"default content";</div>
<div id="topic1" class="hide">"hiding 1";</div>
<div id="topic" class="hide">"hiding 2";</div>
The example is using unobtrusive JavaScript and unobtrusive CSS.
The principles of unobtrusive JavaScript
Change your code as follows.
I preferred to use display:block and display:none instead set visiblity
and also recommend jquery $(selector).show() and $(selector).hide() method.
<html>
<head>
<script>
function onloadfun() {
document.getElementById("hideall").style.display = "none";
}
function optionCheck() {
if (document.getElementById("sorting").value == "bydate") {
document.getElementById("hideall").style.display = "block";
document.getElementById("topic1").style.display = "block";
document.getElementById("topic").style.display = "none";
document.getElementById("showByDefault").style.display = "none";
}
if (document.getElementById("sorting").value == "bytopic") {
document.getElementById("hideall").style.display = "block";
document.getElementById("topic1").style.display = "none";
document.getElementById("topic").style.display = "block";
document.getElementById("showByDefault").style.display = "none";
}
// validation of dropdownlist
var x = document.getElementById("sorting");
var option = x.options[x.selectedIndex].value;
var strUser1 = x.options[x.selectedIndex].text;
if (option == "s") {
document.form.options.focus();
return false;
}
return true;
}
</script>
</head>
<body onLoad="onloadfun()">
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br />
<br />
<hr />
<br />
<br />
<?php //include 'connection.php'; ?>
<div id="showByDefault">
<?php echo "default content"; ?>
</div>
<div id="hideall">
<div id="topic1">
<?php echo "hideing 1"; ?>
</div>
<div id="topic">
<?php echo "hideing 2"; ?>
</div>
</div>
</body>
Try changing above three function in your code.
Use display:none instead of visibility hidden.
See example: http://www.w3schools.com/css/css_display_visibility.asp
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" );
}