I have a page with 2 select boxes, one of which is loaded by an AJAX call. I then want to validate the elements with jquery before I enable the submit button. The jquery works fine when I change the static select (strDirectorate) but not when I change the one loaded by AJAX (new_cc).
Is it because jquery is getting the value of new_cc as it was when the page was loaded?
<div class="selectfield">
<select id="strDirectorate" name="strDirectorate" class="mainform_select" onChange="getNewCostCentre(this.value)">
<option value="" selected="selected"></option>
<?php do { ?>
<option value="<?php echo $row_rsLocality['strLocalityShort']?>" <?php if($row_rsLocality['strLocalityShort'] == $strDirectorate){ echo $selected; } ?>><?php echo $row_rsLocality['strLocalityLong']?></option>
<?php
} while ($row_rsLocality = mysql_fetch_assoc($rsLocality));
$rows = mysql_num_rows($rsLocality);
if($rows > 0) {
mysql_data_seek($rsLocality, 0);
$row_rsLocality = mysql_fetch_assoc($rsLocality);
}
?>
</select>
</div>
<div id="txtNewCostCentre" class="selectfield">
<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">
<option value="" selected="selected"></option>
</select>
</div>
<div class="actions">
<input type="submit" id="submit_button" name="submit_button" class="styled_button" value="Submit" />
</div>
The function getNewCostCentre is
function getNewCostCentre(str)
{
if (str=="")
{
document.getElementById("txtNewCostCentre").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getNewCostCentre.php?q="+str,true);
xmlhttp.send();
}
The code for getNewCostCentre.php is
$sql="SELECT * FROM `tblcostcentreorganisation` WHERE `strOrganisation` LIKE '363 ".addslashes($dir)."%'";
$result = mysql_query($sql);
if(isset($_GET["q"])){
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)" style="background-color:#F8E0E0">';
$display_string .= '<option value="" selected="selected" disabled="disabled"></option>';
}else{
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">';
}
while($row = mysql_fetch_array($result))
{
$cc = substr($row['strCostCentre'], 3, strlen($row['strCostCentre'])-3) . " " . substr($row['strOrganisation'], 3, strlen($row['strOrganisation'])-3);
$org_name = $row['strOrganisation'];
if ($org == $org_name){
$display_string .= '<option value="'.$org_name.'" selected="selected">'.$cc.'</option>';
}else{
$display_string .= '<option value="'.$org_name.'">'.$cc.'</option>';
}
}
$display_string .= '</select>';
echo $display_string;
And the jquery validation is:
$(document).ready(function() {
$('.selectfield select').change(function() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
});
});
The onload code is as follows. I assume it's because I'm using .load within (after) .onload?
$(document).ready(function(){
window.onload = function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded);
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
});
You are binding your change handler for $('.selectfield select') when the page loads. This attaches the handler to all elements that match that selector.
If you then change this element, it won't have the handler attached.
Instead, you should use the live handler, to match all elements that exist now or are ever created in the future.
$('.selectfield select').live("change", function() {
...
});
UPDATE:
For you onload issue, it would be far easier not to repeat your code. If you need to fire off the validation after loading the content dynamically, then trigger the change event once the load has finished - like the following example:
$(document).ready(function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded, function() {
$('.selectfield select').trigger("change");
});
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
});
An ajax update of the input shouldn't trigger the javascript change event so the handler you've specified in change won't get called.
From the javascript specification (http://www.w3.org/TR/html401/interact/scripts.html) :
onchange = script [CT] The onchange event occurs when a control loses
the input focus and its value has been modified since gaining focus.
This attribute applies to the following elements: INPUT, SELECT, and
TEXTAREA.
I'd suggest performing the validation logic in the same part of your javascript where you're handling the response from the ajax request. Right after the line
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
add the call
validate();
Where validate is earlier defined as :
function validate() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
So that your jquery validation becomes:
$(document).ready(function() {
$('.selectfield select').change(validate());
Related
I have this form which has one select field for main-category, one select field for sub-category and a hidden field. This hidden field is only displayed when a specific value chosen from sub-category.
This sub-category options are the result of ajax response from main-category.
Here is the form:
<form>
<select id='main-cat' name='maincat' onchange="sortSubcat(this.value)"/>
<option value="">Please select one category</option>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
</select>
<div id='subcat-more'>
<select id='subcat' name='subcat'>
<option value=''>Please select a subcategory</option>
</select>
</div>
<div id='morefield' style='display:none'>
<input type='text' name='option1'/>
</div>
</form>
I have a Jquery code which handle this form validation, and it tells whether the #morefield is displayed or not. Here is part of this code:
$("#subcat").change(function(){
if (subcat.val() == 'sub-cat-one'){
$("#morefield").css("display","block");
}else{
$("#morefield").hide();
}
});
Unfortunately, Ajax response only displays option on screen however, it did not change in html so when I viewed source code, I don't see any option for sub-cat. Thats why even I chose option sub-cat-one, I would show the div #morefield.
Is there anyway to solve this problem?
Best Regards,
More informaiton:
Here is my ajax call:
function sortSubcat(str)
{
if (str=="")
{
document.getElementById("subcat").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("subcat").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/member/sortsubcat.php?q="+str,true);
xmlhttp.send();
}
Here is the php file:
<?php
require_once("../configs/dbconnect.php");
if (!empty($_GET['q'])){
$q = basename($_GET['q']);
$sql="SELECT * FROM subcat WHERE maincat=:q";
$result = $conn->prepare($sql);
$result->bindParam(':q', $q);
$result->execute();
echo "<option value=''>Please select a sub cat</option>";
foreach($result as $row)
{
echo "<option value='$row[name]'>$row[name]</option>";
}
}
else{
echo "<option value=''>Please select a subcat</option>";
}
$conn=null;
?>
You have to use
if ($(this).val() == 'sub-cat-one'){
instead of
if (subcat.val() == 'sub-cat-one'){
to access the correct html element (#subcat) in your onchange eventhandler.
You also shouldn't use the id subcat for more than one element. Currently the div and the select are having id subcat.
You have two elements ( div and select ) with same id subcat. id attribute should be unique for all elements .
I think you should try below suggestions:
Use AJAX success callback instead of using onchange.
if ($(this).val() == 'sub-cat-one')
I think I see where your problem is coming from, on each iteration you echo the result. And only that result gets returned to your ajax script. Do this in your php file:
$returned_string = '[';
foreach($result as $row)
{
$returned_string .= '{"name" : "'. $row[name]. '", "value" : "'. $row[name]. '"},';
}
$returned_string = substr($returned_string, 0, -1); //remove trailing ','
$returned_string .= ']';
header("Content-type: application/json");
echo $returned_string;
exit;
Then in your successCallback function:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = JSON.parse(xmlhttp.responseText);
var selectElement = document.getElementById('subcat');
for(var i = 0; i < response.length; i++)
{
var idx = i+1;
selectElement.options[idx] = new Option(response[idx].value, response[idx].name, false, false);
}
}
}
}
I am a beginner in ajax and on very short deadline so I am turning to this community for help.
My problem is:
When I successful make ajax request and the results are returned I cant select another value. I will try to explain below.
I have a PHP page with search form that contains 4 dropdowns and a submit button. Goal is to set the search parameters by selecting a values from dropdowns. When you select the first value, all the others must change values according to selected value.
For example: I have a dropdowns named:
Destination, Month, Port and Ship
When you select the Destination then all the other dropdowns are rewritten in manner that correspond to the destination. So when I have this the Destination is a single, now I want to select witch month, or port or Ship I want to use and so on.
I hope you understand.
EDITED: It seems it is not the problem with ajax but with Jquery event not fiering up after ajax returns values.
The code I have is:
Ajax:
<script>
var xmlhttp;
function showUser(dest,mese,port,ladja)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="remote.php";
url=url+"?dest="+dest+"&mese="+mese+"&port="+port+"&ladja="+ladja;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
PHP
<div id="src">
<div id="main">
<div id="content">
<form name="src" id="src_form" method="post" action="result.php">
<div id="lin1" class="lin"><?php Destinacija(); ?></div>
<div id="lin2" class="lin"><?php Mesec(); ?></div>
<div id="lin3" class="lin"><?php Pristanisce(); ?></div>
<div id="lin4" class="lin"><?php Ladja(); ?></div>
<div id="lin5"><button id="src" type="submit">Išči</button></div>
</form>
</div>
</div>
</div>
<script>
$("#content").on("change", ".lin", function(event){
event.preventDefault();
//console.log( $( this ).text() );
showUser(document.getElementById('dest').value,document.getElementById('mese').value,document.getElementById('port').value,document.getElementById('ladja').value);
});
</script>
<?php include("ajax.php"); ?>
<?php
function Destinacija()
{
include("class/class.Translate_inl.php");
$tr = new Translate_inl("dest_code");
include("includes/conSql.php");
$result = mysqli_query($con,"SELECT DISTINCT region_code FROM no_air_pricing");
echo '<select name="dest" id="dest">'.PHP_EOL;
echo '<option value="0">Destinacija</option>'.PHP_EOL;
while($row = mysqli_fetch_array($result))
{
$dest = $tr->TrVar($row['region_code']);
echo'<option value="'.$row['region_code'].'">'.$dest.'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
include("includes/disSql.php");
}
function Mesec()
{
$tr = new Translate_inl("meseci");
include("includes/conSql.php");
$mo = array();
$i=0;
$result = mysqli_query($con,"SELECT sail_date FROM no_air_pricing ORDER BY sail_date");
while($row = mysqli_fetch_array($result))
{
$month = explode("/",$row['sail_date']);
$mo[$i] = $month[0];
$i++;
}
include("includes/disSql.php");
$un_mo = array_unique($mo);
$un_mo = array_values($un_mo);
$k = count($un_mo);
echo'<select name="mese" id="mese">'.PHP_EOL;
echo'<option value="0">Mesec odhoda</option>'.PHP_EOL;
for($j=0; $j<$k; $j++)
{
echo'<option value="'.$un_mo[$j].'">'.$tr->TrVar($un_mo[$j]).'</option>'.PHP_EOL;
}
echo'</select>'.PHP_EOL;
unset($tr);
}
function Pristanisce()
{
$tr = new Translate_inl("port_code");
$port = array();
$i=0;
include("includes/conSql.php");
$result = mysqli_query($con,"SELECT departure_port_code FROM no_air_pricing ORDER BY departure_port_code");
while($row = mysqli_fetch_array($result))
{
$port[$i] = $row['departure_port_code'];
$i++;
}
include("includes/disSql.php");
$uport = array_unique($port);
$uport = array_values($uport);
$k = count($uport);
echo '<select name="port" id="port">'.PHP_EOL;
echo '<option value="0">Pristanišče odhoda</option>'.PHP_EOL;
for($j=0; $j<$k; $j++)
{
echo'<option value="'.$uport[$j].'">'.$tr->TrVar($uport[$j]).'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
unset($tr);
}
function Ladja()
{
$tr = new Translate_inl("ladje_kode");
$ladje = array();
$i=0;
include("includes/conSql.php");
$result = mysqli_query($con,"SELECT ship_code FROM no_air_pricing ORDER BY ship_code ");
while($row = mysqli_fetch_array($result))
{
$ladje[$i] = $row['ship_code'];
$i++;
}
include("includes/disSql.php");
$uladje = array_unique($ladje);
$uladje = array_values($uladje);
$k = count($uladje);
echo '<select name="ladja" id="ladja">'.PHP_EOL;
echo '<option value="0">Ladja</option>'.PHP_EOL;
for($j=0; $j<$k; $j++)
{
echo'<option value="'.$uladje[$j].'">'.$tr->TrVar($uladje[$j]).'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
unset($tr);
}
?>
Any help would be welcome. Thanks in advance.
I have edit the script code in php file, to implement the answer from Musa.
Still need help the original problem still stends.
Solved the problem.
I have puted:
$.ajaxSetup({
url: "remote.php",
global: true,
type: "POST"
});
before my ajax script and it fired up. Pleas don't ask me why, it just works ;)
Thank you for all the answers.
am trying to generate report through dynamically generated form. Through XMLHttpRequest the form loads well but the validation against the form fields wont work. I have tried eval() it works only during load time ( like eval(alert("hi")) but not on dom objects , think some scope problem. The form fields are dynamically generated and so its validation based on selection and availability role in database.
The code of two files is attached below
<script>
function showUser(str)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var s= xmlhttp.responseText;
parseScript1(s);
parseScript(s);
}
}
xmlhttp.open("GET","test2.php",true);
xmlhttp.send();
}
function parseScript1(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
var k = "<script> "+ scripts +"<\/script>";
document.getElementById("txtHint1").innerHTML=k ;
// Return the cleaned source
return source;
}
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
document.getElementById("txtHint").innerHTML=source;
// Return the cleaned source
return source;
}
function valid()
{
eval(validate());
}
</script>
<div id="txtHint1"><b>javascript will appear here</b></div>
<form>
<div id="nons1" >
<select id="nope1" name="users" onchange="showUser(this)">
<option value="">Select a option:</option>
<option value="1">not working here</option>
</select>
</div>
</form>
<div id="txtHint"><b>Select the value .</b></div>
test2.php
echo "<p>This form works fine singly not with xmlhttprequest";
echo'<form name="frm" method="post" action="test2.php" onsubmit="return(eval(validate()));">';
echo '<input value="" name="kfrm19" type="text">';
echo '<input name="save" value="submit" type="submit"></form>';
echo '<script>
function validate(){
if( document.frm.kfrm19.value.trim()=="")
{
alert( "If you can see this message .its working..." );
document.frm.kfrm19.focus() ;
return false;
}
}
</script>';
?>
try this:
function validate(){
if(document.frm.kfrm19.value.length == 0)
{
alert("If you can see this message .its working...");
document.frm.kfrm19.focus();
return false;
}
}
I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];
I have build an instant search with AJAX, It is like when you start typing result appears, then if you click anywhere on the body result disappear, onmouse over at input field result re appear. when clicked inside input field result disappers.
I want this result to stays open after onmouse event when clicked in input field. for that i have added a click event, but it is not working.
Please see the codes and suggest any possible way to do this.
<script type="text/javascript">
function showResult(str) {
if (str.length == 0) {
document.getElementById("search-result").innerHTML = "";
document.getElementById("search-result").style.border = "0px";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("search-result").innerHTML = xmlhttp.responseText;
document.getElementById("search-result").style.border = "1px solid #A5ACB2";
document.getElementById("search-result").style.display = "block";
document.getElementById("search-input").onmouseover = function() {
show_box()
};
document.getElementById("search-input").onclick = function() {
show_box()
};
}
}
xmlhttp.open("GET", "instant-search.php?keyword=" + str, true);
xmlhttp.send();
}
function close_box() {
fadeOut();
document.getElementById("search-result").style.display = "none";
}
function show_box() {
setOpacity(0);
document.getElementById("search-result").style.display = "block";
fadeIn();
}
document.onclick = function() {
close_box()
};
function setOpacity(value) {
document.getElementById("search-result").style.opacity = value / 10;
document.getElementById("search-result").style.filter = 'alpha(opacity=' + value * 10 + ')';
}
function fadeIn() {
for (var i = 20; i <= 100; i++)
setTimeout('setOpacity(' + (i / 5) + ')', 5 * i);
}
function fadeOut() {
for (var i = 20; i <= 100; i++)
setTimeout('setOpacity(' + (5 - i / 5) + ')', 5 * i);
}
</script>
HTML Code
<input name="keyword" type="text" size="50" id="search-input" onkeydown="showResult(this.value)" autocomplete="off" />
<div id="search-result"></div>
I'm so into jQuery that I forgot there is a difference on IE.
if(!e) {
e = window.event;
}
if(e.stopPropagation && e.preventDefault) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
try this?
<input name="keyword" type="text" size="50" id="search-input" onclick="showResult(this.value)" autocomplete="off" />
or to test if onclick works
<input name="keyword" type="text" size="50" id="search-input" onclick="alert('replace this with your function you want to call');" autocomplete="off" />