简体   繁体   中英

Disable a table cell after the first click in javascript

I have a table cell as the following :

<td id=report onMouseUp='clickReport()' onKeyPress='clickReport()' >Click</td>";

The event function is as below :

function clickReport() {
document.form.submit();
}

On form submission, there is a back-end process going on. Until the 1st process completes(ie, until the page reloads), I do not want the user to press the press the "Click" again, else it may affect the previous running process. So, I thought of disabling the "Click" after the first press.

I tried using preventDefault() but it is not working.

function clickReport() {
document.form.submit();
document.getElementById("report").onMouseUp = function(e) 
{
 e.preventDefault();
 return false;
}
document.getElementById("report").onKeyPress = function(e) 
{
 e.preventDefault();
 return false;
}
}

Can someone please help!

1) You might pass the element parameter to your event functions, so you can acces the DOM element easily. See below.

<td id=report onMouseUp='clickReport(this)' onKeyPress='clickReport(this)' >Click</td>";

2) On the first function run you might null the events, so they will not fire anymore. See below.

// the *element* parameter is yor <td> element here 
function clickReport(element) {
    document.form.submit();
    element.onMouseUp = null;
    element.onKeyPress= null;
}

3) You might use onclick event instead of onmouseup and get rid of onkeypress , if you only want to make it work on click.

<td id=report onclick='clickReport(this)'>Click</td>";

function clickReport(element) {
    document.form.submit();
    element.onclick= null;
}

Working codepen: https://codepen.io/anon/pen/MmVNMe

this should work.

since at first the disableClick is undefined the click will fire, as soon as it fires the flag will be set to true and the click will no longer be possible.

<td id=report onMouseUp='!disableClick && clickReport()' 
 onKeyPress='!disableClick && clickReport()' >Click</td>"

function clickReport() {
 document.form.submit();
 window.disableClick = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM