How to refer on dynamically created variables - javascript

I want to know if it is possible to refer to an dynamically created variables and if yes how?
I create on this site many forms which have p elements on the bottom is one button and if I click that button I want to transmit the variable(IdJB) which was created specific in this form.
I marked the variable with a command in the code.
$(document).ready(function() {
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
Ausgabebereich.appendChild(f);
$(document).on('click', 'button', function() {
sessionStorage.setItem('IdJB', IdJB); //Here !!!!!!!!!!!!!
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
This is how the Programm looks like

Don't use a global variable. Put IdJB in an attribute of the button. You can use the jQuery .data() method for this.
Also, don't add the event handler every time through the loop. When you use event delegation, you should just add the handler once.
$(document).ready(function() {
$(document).on('click', 'button', function() {
var IdJB = $(this).data("IdJB");
sessionStorage.setItem('IdJB', IdJB);
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
$(bInhalt).data('IdJB', IdJB);
Ausgabebereich.appendChild(f);
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>

I may be misunderstanding your question, but if not: In order to reference dynamically created elements, the click handler just needs to be instantiated after the element is created and put in the DOM. An easy way to handle this is by having a function generate your tag like so:
function appendTag(parent, child){
parent.append(child)
child.click(function(){
//Click code here
});
}

So it looks like when you are adding the button click event dynamically you are adding it to all the buttons on the page. This is why when you click one it runs 3 times.
This can be seen by the button text in this line of code:
$(document).on('click', 'button', function() {
.....
});
To address this problem you need to make the click listener specific to the button. You can do that by making a more specific button selector. Although it's not a perfect solution one way to do this is to give each button a unique I'd. Something like button-## where ## here is a different number each time you create a new button. You can then do:
$(document).on('click', '#button-##', function() {
.....
});
Again replacing ## with the corresponding Id value.
Edit: actually you can use the answer #Laif posted by rather than using the $(document).on( call just simply do b.click()

Related

How to fix multiple appending in the div using jquery

I have problem regarding on appending a sample a href to the div or to the html elements, I have only 3 array response to my ajax, however the results shows duplicate item to the corresponding div. I will share to you guys my sample code that already made,
I have here my backend php:
<?php
require_once('../ConnectionString/require_db.php');
session_start();
//submit function
$status = 'Active';
$posttype_affiliation_page = 'affiliation_page';
$posttype_member_org_page = 'member_org_page';
$affiliation_member_org_content = $db->prepare('SELECT title,link,posttype FROM tblcontent
WHERE status = ? AND posttype = ? OR posttype = ? ORDER BY contentID DESC')
or die($db->error);
$affiliation_member_org_content->bind_param('sss',$status,$posttype_affiliation_page,$posttype_member_org_page);
$affiliation_member_org_content->execute();
$affiliation_member_org_content->bind_result($title,$link,$posttype);
$result = array();
while ($affiliation_member_org_content->fetch()) {
$result[] = array('title'=>$title,'link'=>$link,'posttype'=>$posttype);
header('Content-type: application/json');
}
echo json_encode($result);
?>
my front end:
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
My Html:
<div class="Affiliation">
<h5>Affiliation</h5>
<p style="font-size:14px;" class="list_affiliation_links">
</p>
</div>
<br>
<div class="Member">
<h5>Member Organizations</h5>
<p style="font-size:14px;" class="list_member_org_links">
</p>
</div>
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_affiliation_links').html('');
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_member_org_links').html('');
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
You should first clear html content and then set to DOM element. Might be it works for you.
you're appending a second p tag with your HTML that also gets selected in your append later in the code. You should only build the link withing the var data.
Greetings

Know which Form is submitted

I have eight Forms in a page (Form0, Form1, Form2 and so on). When a form is submitted, data is handed by JS and send to ReassignPreg.php, which search data in DB and send it back with json. Then the proper divs on the page are updated.
The code below is doing its job. But I have eigh copies of almost the same code, one for each Form (I only copy two of them for brevity). Newbie and amateur as I am, I wander which would be the way for synthesize this code (get Form name, and then pass that to only one function).
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox10").html(imagen)
$("#PregBox11").html(obj.Clase)
$("#PregBox12").html(obj.Dificultad)
$("#PregBox13").html(obj.Tipo)
});
return false;
});
});
</script>
A little more modularity helps a lot
$(document).ready(function () {
$("[id^=Form]").on('submit', function (e) {
e.preventDefault();
var _form = this.id.slice(-1); // 0, 1, etc
var cadena = $(this).serialize() + '&form=' + _form;
$.get('ReassignPreg.php?cadena=' + cadena, function (row) {
var image = $('<img />', {
src : "../ImageFolder/" + row.File + ".png",
width : 530
});
$("#PregBox"+_form+"0").html(image);
$("#PregBox"+_form+"1").html(row.Clase);
$("#PregBox"+_form+"2").html(row.Dificultad);
$("#PregBox"+_form+"3").html(row.Tipo);
}, 'json');
});
});
now you'll have a form key on the server containing the number of the form, for instance in PHP you'd get that with $_GET['form'] etc.
you could add an hidden field to each form with an ID/name and use that to identify the form submitting
You may need to assing classes to your PregBox elements and then target them accordingly to the form's ID.
$('form').submit(function(){ // listen to all form submissions.
var formID = $(this).prop('id'); // get the form ID here and do what you like with it.
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});

Javascript function not found when moved to external file

I'm moderatley new to ASP.NET and very new to Javascript. I'm writing a ASP.NET UserControl. I had the following:
<head>
<title>Select Asset </title>
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CheckThenCloseActiveToolTip(supplierID) {
var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
var selectedItems = radGrid.get_masterTableView().get_selectedItems()
if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
else {
DoPartialPostBack('selectasset', selectedItems[0]._dataItem.Id);
CloseActiveToolTip();
}
}
function PopulateRooms(e) {
var idx = e.selectedIndex;
if (idx > -1) {
var dcId = JSON.stringify({ dataCenterId: e.options[idx].value });
var pageUrl = '/WebService/AVWebService.asmx';
$.ajax({
url: pageUrl + '/GetRooms',
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: dcId,
success: OnRoomsReceived,
error: OnErrorCall
});
}
else {
var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
ddlRooms.disabled = true;
$('#ddlRooms').empty();
ddlRooms.options[0] = new Option('', '-1');
getAssets(0);
}
}
function OnRoomsReceived(result) {
var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
if (result.d.length > 0) {
ddlRooms.disabled = false;
$('#ddlRooms').empty();
ddlRooms.options[0] = new Option('', '-1');
for (var i = 0; i < result.d.length; i++) {
ddlRooms.options[i + 1] = new Option(result.d[i].Name, result.d[i].Id);
}
}
if (result.d.length = 1)
ddlRooms.selectedIndex = 1;
getAssets(0);
}
function resetGridData() {
getAssets(0);
}
function getAssets(startAt) {
var cpId = document.getElementById('hfldCompanyId').value;
var pageUrl = '/WebService/AVWebService.asmx';
var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
var ddldc = document.getElementById('MainContent_SelectAssetGrid1_ddlDataCenter');
var dcIdx = ddldc.selectedIndex;
var dcId = '';
if (dcIdx > -1)
dcId = ddldc.options[dcIdx].value;
var ddlrm = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
var rmIdx = ddlrm.selectedIndex;
var rmId = '';
if (rmIdx > -1)
rmId = ddlrm.options[rmIdx].value;
var ddlStatuses = $find('ctl00_MainContent_SelectAssetGrid1_ddlStatuses';
var rbgAssetClass = document.getElementById('MainContent_SelectAssetGrid1_rbgAssetClass');
var ac = 0;
var rbgInputs = rbgAssetClass.getElementsByTagName('input');
for (var i = 0; i < rbgInputs.length; i++) {
if (rbgInputs[i].checked) {
ac = i;
}
}
var filters = [];
var fbs = document.getElementsByClassName('rgFilterBox');
for (var i = 0; i < fbs.length; i++)
if (fbs[i].value != '')
filters[filters.length] = { field: fbs[i].alt, value: fbs[i].value };
var params = JSON.stringify({ companyId: cpId,
startIndex: startAt,
maximumRows: tableView.get_pageSize(),
filterExpressions: filters,
dataCenterId: ddldc.options[ddldc.selectedIndex].value,
roomId: rmId,
Statuses: ddlStatuses._checkedIndices,
assetClass: ac
});
$.ajax({
url: pageUrl + '/GetSelectAssetData',
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: params,
success: updateGrid,
error: OnErrorCall
});
}
function updateGrid(result) {
var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
tableView.set_dataSource(result.d.gridData);
tableView.dataBind();
tableView.set_virtualItemCount(result.d.count);
}
function gridAssetList_Command(sender, args) {
args.set_cancel(true);
var pageSize = sender.get_masterTableView().get_pageSize();
var currentPageIndex = sender.get_masterTableView().get_currentPageIndex();
if (args.get_commandName() == 'Filter')
currentPageIndex = 0;
getAssets(pageSize * currentPageIndex);
}
function gridAssetList_Created(sender, args) {
var fbtns = document.getElementsByClassName('rgFilter');
for (var i = 0; i < fbtns.length; i++)
fbtns[i].style.visibility = 'hidden';
var fbs = document.getElementsByClassName('rgFilterBox');
for (var i = 0; i < fbs.length; i++)
fbs[i].onkeypress = applyFilter;
}
function applyFilter(args) {
if (args.keyCode == 13)
resetGridData();
}
</script>
This works most of the time, but if I'm loading the UserControl using Page.LoadControl(), it didn't always load the scripts correctly. For a couple of reasons (maybe poor ones) I thought I'd move the scripts to an external file.
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../Scripts/SelectAsset.js" type="text/javascript"></script>
There's no additional code or setup in the .js file, just
function CheckThenCloseActiveToolTip(supplierID) {
var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
var selectedItems = radGrid.get_masterTableView().get_selectedItems()
if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
...
But now I get a RunTime error that "function gridAssetList_Command" us undefined. That function is bound to a grid's OnCommand event in the page .
When I examine the page in Firebug, it doesn't list my .js file in the list of script files.
I'm loading my scripts in the . I didn't change them, just moved them. What am I missing?
MORE INFO:
It appears to be using different ClientIds when adding the functions to the controls. The error I'm getting drops be in a dynamic resource with the following:
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadGrid, {"ClientID":"ctl00_MainContent_ctl03_gridAssetList","ClientSettings": ...
I'm going to try changing referenes to getElementByClass()
The best way to add javascript reference on asp.net web form is using ScriptManager on parent element or parent page such as a Master Page, And use ScriptManagerProxy on content pages and user controls.
Try use ScriptManager or combination of both to resolve your problem. Also use root application alias (~) for refer to file ex. src="~/Scripts/jquery-1.9.1.min.js"
So for simple way change your script reference to become:
<asp:ScriptManager ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery-1.9.1.min.js" />
<asp:ScriptReference Path="~/Scripts/SelectAsset.js" />
</Scripts>
</asp:ScriptManager>
Update:
use for example:
$('table[id*="gridAssetList"]') for table with id = ctl00_gridAssetList_xx
$('input[id*="inputTxt"]') for input with id = ctl100_inputTxt
etc
to call html tag that rendered by asp.net component using jquery selector.
hi steve i think its shows error due to script source path please check that first then to verify the script loaded or not try this below code
if(typeof(yourfunction_name=='function')
{
// this code will make sure that the function is present in the page
//function exits do your functionality.
}else
{
alert('Script not loaded');
}

form fill and submit without waiting for an event?

Using http://en.allexperts.com/q/Javascript-1520/create-form-submit-fly.htm as reference, I create the following form and it can be submitted by an onclick event or any other user-event? Is there a way to execute this when the page loads or do I have to wait for the user event always?
<script>
var params = something
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
inputForm.appendChild(newElement);
newElement.value = elementValue;
return newElement;
}
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", params.data1);
createNewFormElement(submitForm, "field2", params.data2);
submitForm.name= "submitpost";
submitForm.action= "some URL";
submitForm.submit();
}
</script>
If I understood correctly you want to do something like the following. Right?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var params = ["1","7"];
createFormAndSubmit();
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("INPUT");
newElement.name = elementName;
newElement.type = 'hidden';
newElement.value = elementValue;
inputForm.appendChild(newElement);
return newElement;
}
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", params[0]);
createNewFormElement(submitForm, "field2", params[1]);
submitForm.name= "submitpost";
submitForm.action= "show.jsp";
submitForm.submit();
}
});
</script>

Temporarily remove access to execute function

I'm working on a project where I on a website display content users can "interact" with using keypress W or P. Doing this, the site executes a function posting to a php writing to a mysql-database. However, if the key is pressed and HOLD or pressed multiple times in a row - I get multiple setTimeouts running and crap happens. How can I temporarily remove access to running (or disable) the keypress-functions when executed once?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.jkey-1.2.js"></script>
<link rel="stylesheet" href="custom.css">
<script>
$(function content(){
var reloading = function(data){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var field1 = data[3];
_field1 = field1;
var field2 = data[4];
_field2 = field2;
var ans1 = data[5];
_ans1 = ans1;
var ans2 = data[6];
_ans2 = ans2;
var val1 = parseInt(ans1, 10) ;
_val1 = val1;
var val2 = parseInt(ans2, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( "#"+vname +":" ).fadeIn("slow");
$('#valg1').hide().html( field1 ).fadeIn("slow");
$('#valg2').hide().html( field2 ).fadeIn("slow");
window["reload_timer"] = setTimeout(reloading,6000);
}
});
}
reloading();
$(document).jkey('p',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Thx!</i>< ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(window["reload_timer"]);
setTimeout(reloading,5000);
});
$(document).jkey('w',function() {
$.post("update.php", { "id2": _id} )
$('#output').hide().html( "<i>Thx!</i>< ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(window["reload_timer"]);
setTimeout(reloading,5000);
});
});
</script>
</head>
<body><div id="container">
<div id="username">
</div>
<div id="output"></div>
<div id="posted"></div>
<div id="field1"></div>
<div id="valg1"></div>
<div id="valg2"></div>
</div>
</body>
</html>
Introduce a variable called e.g. blocked:
var blocked = false;
In the key handlers, abort if blocked and set blocked to true otherwise:
$(document).jkey('w',function() {
if(blocked) return; // abort
blocked = true; // disallow any further key presses
Unblock in the success handler of reloading:
success: function() {
blocked = false; // allow again
Add a flag and check it in your two keypress handlers:
var allowKeyPress = true;
$(document).jkey('p',function() {
if (!allowKeyPress)
return;
allowKeyPress = false;
// your existing code here
}
Somewhere else in your code you then set allowKeyPress = true; again - I'm not sure exactly where you want to do that: perhaps within your reloading() function, perhaps in the success callback from your $.ajax() (in which case really you should add an error or complete handler to reset the flag if the ajax call fails), or perhaps just with a new, separate setTimeout().

Categories

Resources