Onclick Event Not Working, Onmouse Working Though - php

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" />

Related

Send checkbox values through ajax for a php/mysql query

I am creating an html form and using it's values to dynamically filter search results from a mysql database. I have several dropdown's and one checkbox field for multiple values and I cannot get the checked values to send over ajax to my php page. Is there a way to update my query results based on this checkbox field the same way it current is for the other select fields?
HTML Code:
<form name="searchForm">
<input type="checkbox" name="services" value="twic" onclick="get_check_value()">TWIC</input><br/></li>
<input type="checkbox" name="services" value="enclosedTrucking" onclick="get_check_value()">Enclosed Trucking</input><br/>
<input type="checkbox" name="services" value="flatBedTrucking" onclick="get_check_value()">Flat Bed Trucking</input><br/>
</form>
Java script:
<script type="text/javascript">
function get_check_value()
{
var c_value = "";
for (var i=0; i < document.searchForm.services.length; i++) {
if (document.searchForm.services[i].checked)
{
c_value = c_value + document.searchForm.services[i].value + "\n";
}
}
return = c_value;
//alert(c_value);
}
</script>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('results');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var os = document.getElementById('originState').value;
var c = document.getElementById('commodity').value;
var ds = document.getElementById('destState').value;
var ser = c_value;
var queryString = "?os=" + os ;
queryString += "&c=" + c + "&ds=" + ds + "&ser=" + ser;
//ajaxRequest.open("GET", "php/search2.php" +
// queryString, true);
ajaxRequest.open("GET", "php/testqueries.php" + queryString, true);
ajaxRequest.send(null);
}
</script>
PHP to receive the variables:
$ser = $_GET['ser'];
Try this using jquery,
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$('#btnSubmit').on('click', function () {
var os = $('#originState').val();
var c = $('#commodity').val();
var ds = $('#destState').val();
var ser = get_check_value();
var queryString = "os=" + os;
queryString += "&c=" + c + "&ds=" + ds + "&ser=" + ser;
$.ajax({
url:'php/testqueries.php',
data:queryString,
success:function(data){
$('#results').html(data);
}
});
return false; // to prevent from page reload
});
</script>
Change your `html like,
<form name="searchForm">
<input type="checkbox" name="services" value="twic" />TWIC
<br/>
<input type="checkbox" name="services" value="enclosedTrucking" />Enclosed Trucking
<br/>
<input type="checkbox" name="services" value="flatBedTrucking" />Flat Bed Trucking
<br/>
<input type="submit" id="btnSubmit" value="Submit" />
</form>

Alternative to innerHTML for IE select box

I have a problem that is php data not showing in select box. innerhtml not working in Internet Explorer. long_description_detail_list data not showing in select box.please help me
first page:
<div id="long_description_detail_list" style="display:none;">
<option value="0">Select..</option>
<?php
include_once('Model/Language.php');
$r = new Language();
$a = $r->Select();
for($i = 0; $i < count($a); $i++)
{
print '<option value="'.$a[$i][0].'">'.$a[$i][1].'</option>';
}
?>
</div>
<script language="javascript" type="text/javascript">
//Browser Support Code
function create_long_description_detail_div(){
if(count_table_long_description_detail() >=3) {
alert("You can not add more than 3 long_description Details");
}
else {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var blank_long_description_detail = ajaxRequest.responseText;
document.getElementById('long_description_detail_counter').value ++;
$('#my-all-long_description_details-here').append(blank_long_description_detail);
set_new_height_of_step_2('inc');
var long_description_list_counter = document.getElementById('long_description_detail_counter').value;
var long_description_detail_list = document.getElementById('long_description_detail_list').innerHTML;
document.getElementById('llanguage[' + long_description_list_counter + ']').innerHTML = long_description_detail_list;
}
}
var long_description_detail_counter = document.getElementById('long_description_detail_counter').value;
var queryString = "?long_description_detail_counter=" + long_description_detail_counter;
ajaxRequest.open("GET", "Views/User/long_description/add_long_descriptions_detail.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
data not showing here in second page named add_long_descriptions_detail.php:
<select id="llanguage[<?php echo $counter; ?>]" name="llanguage[<?php echo $counter; ?>]" class="txtBox">
<option value="0">Select..</option>
</select>
IE doesn’t support updating the elements of a <select> with innerHTML, but what you can do is use the DOM, which is always the right way to go about things anyways.
Make your server-side script return a JSON array of options; it’ll make everything a lot easier.
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState === 4) {
// Parse the response
var options = eval('(' + ajaxRequest.responseText + ')');
// Get the box; I have no clue what this is
var box = document.getElementById('llanguage[' + long_description_list_counter + ']');
// Clear any current elements
while(box.childNodes.length > 0) {
box.removeChild(box.firstChild);
}
// Add new ones
for(var i = 0; i < options.length; i++) {
var newOption = document.createElement('option');
newOption.value = options[i].value;
newOption.appendChild(document.createTextNode(options[i].text));
}
}
};
(This is a little trimmed-down from your original code, but I’m sure you can fit it in.)
It’s also probably a good idea to use an old-IE-compatible JSON parser instead of eval.
The JSON should look like this:
[
{ "text": "Some text", "value": "some-value" }
]
You can use json_encode to produce it conveniently from a PHP array.

Ajax reply javascript not functioning for validation

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;
}
}

Jquery get value of element loaded with AJAX

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());

keypressed() and onCLick() implementation problem in IE

I've the following input text box and a button.
<div id="sender" onKeyUp="keypressed(event);">
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>
The keypressed(event) function actually detects if the key being pressed is "Enter" and calls the doWork() function.
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
This code seems to work fine in Chrome & Firefox. But in IE, the function seems to called twice.
Can anyone help me tweak the code so that it works properly in IE also.
Thanks
EDITED:
Whole ajax codes
<!--
var httpObject = null;
var link = "";
var timerID = 0;
var nickName = "Unname"; //"<?php echo $nickname; ?>";
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML += response;
objDiv.scrollTop = objDiv.scrollHeight;
var inpObj = document.getElementById("msg");
inpObj.value = "";
inpObj.focus();
}
}
// Change the value of the outputText field
function setAll(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML = response;
objDiv.scrollTop = objDiv.scrollHeight;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
link = "message.php?nick="+nickName+"&msg="+encodeURIComponent(document.getElementById('msg').value);
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);
}
}
// Implement business logic
function doReload(){
httpObject = getHTTPObject();
var randomnumber=Math.floor(Math.random()*10000);
if (httpObject != null) {
link = "message.php?all=1&rnd="+randomnumber;
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setAll;
httpObject.send(null);
}
}
function UpdateTimer() {
doReload();
timerID = setTimeout("UpdateTimer()", 5000);
}
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
//-->
If someone is facing a similar problem, this could be useful.
I solved the problem by detecting IE browser using PHP script and discarding the onKeyUp() function while rendering HTML for IE.
IE Detection PHP script
//Detect IE function
function detectIE() {
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
return true;
else
return false;
}
And this is how i changed the event handling.
<div id="sender" <?php if (detectIE()) { /*do nothing */ } else { echo "onKeyUp=\"keypressed(event);\""; } ?> >
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>

Categories