-2

I'm trying to create a button that becomes deactivated after the first click; however I have no clue how to do it. This is what I have now:

<input type="button" id="btnSearch" value="Search" onclick="Fuction();" />

This button will NOT submit a form. Could someone help me? I'm totally new to this. I've tried following the answer in other threads but got lost.

user2864740
  • 54,112
  • 10
  • 112
  • 187
user3650090
  • 9
  • 1
  • 1
  • 3

4 Answers4

5

Separating javascript from HTML:

HTML:

<input type="button" value="Click me!" id="form-button"/>

Javascript:

document.getElementById('form-button').onclick = function () {
    this.disabled = true;
}
Frinsh
  • 310
  • 3
  • 14
3

Not the preferred way of course, but this will get you the result you are after.

function Fuction() {
  document.getElementById('btnSearch').disabled = 'disabled';
}
Tommy Ivarsson
  • 565
  • 3
  • 7
  • Why the downvote? This answer make an unnecessary DOM look-up, but it works nonetheless. – Pavlo May 18 '14 at 17:28
  • 2
    The major problem with this is that a user would need to define one function for every button they want to apply it to, which isn't exactly a good idea. – Meredith May 18 '14 at 17:29
  • Of course. That's why I said it's not the preferred way. However it does work and it is very simple. I may be mistaken but I gathered OP was a beginner and beginners need trivial solutions to problems in order to get going. – Tommy Ivarsson May 18 '14 at 17:34
  • 1
    It comes down to if you want to teach beginners _a solution_ or if you want to teach them _a good solution_. – Meredith May 18 '14 at 17:36
  • @Meredith IMO, SO isn't a programming language course, and no solution is without a downside. What he should be doing is explaining why exactly this is "not the preferred way" – Pavlo May 18 '14 at 17:47
  • @Pavlo I'd be ok with that – Meredith May 18 '14 at 17:51
  • 1
    I'd say that most often it's more sensible to teach them a solution they can understand at the level they are at. – Tommy Ivarsson May 18 '14 at 18:30
2

Set disabled attribute in the end of your handler:

function Fuction(button) {
    // your code

    button.disabled = true;
}

Markup:

<input type="button" id="btnSearch" value="Search" onclick="Fuction(this);" />
Pavlo
  • 35,298
  • 12
  • 72
  • 105
0

Just call event.preventDefault() in the functions implicitly added event variable to first stop the propagation. To disable it afterwards just call setAttribute("disabled", true); on the element. Something like

function aMeaningfulName(e) {
    e.preventDefault();
    e.target.setAttribute("disabled", true);

    // your logic here
}
nietonfir
  • 4,516
  • 6
  • 27
  • 41