简体   繁体   中英

button is still clickable after call window.alert

I was trying to prevent multiple submit. To prevent to submit the same value, I called window.alert to stop the process and tell the user the input value is already registered. The problem is the submit seems to be clickable after the alert window opened. Because after clicking the button several times after the alert window opens, and I closed the alert window. the alert window immediately re-opened without any clicks. the submit button seems to clickable after the windo open. how to disable all input right after the alert window open?

I was trying to disable a button by setting the state. However, it didn't work.

HTML  
<form onSubmit={(e) => submitHandler(e)}>
        <input
          name="words"
          value={words}
          placeholder="Enter Tag for search"
          onChange={(e) => onChangeHandler(e)}
        />
        {disable ? (
          <h1>updating</h1>
        ) : (
          <button type="submit" disable={disable}>
            submit
          </button>
        )}
      </form>


const submitHandler = (e) => {
    e.preventDefault();
    if (!words) {
      return null;
    }
    setNewSearchWordsState({ ...newSearchWordsState, disable: true });
    const newList = list.map((item, idx) => {
      if (idx === id) {
        item.searchWords.map((searchWord) => {
          if (searchWord === words) {
            setNewSearchWordsState({ ...newSearchWordsState, words: '' });
            window.alert(`${words} already registered`);
          }
          item.searchWords.push(words.toLowerCase());
        });
      }
      return {
        ...item,
      };
    });
    updateSearchWords(newList);
    setNewSearchWordsState({ words: '', disable: false });
  };

You may want try this working sample https://codepen.io/cunlay/pen/BaaROPG

// HTML

<form onsubmit="submitHandler()">
    <input id="words" onkeyup="changeHandler()" placeholder="Enter Tag for search" />
    <button type="submit" id="btn" disabled=true>Submit</button>
</form>

//JAVASCRIPT

<script>
function changeHandler(){
  var words = document.getElementById('words'); 
  var btn = document.getElementById('btn'); 
  var text = words.value;

  if(!text){
    btn.disabled = true;
  }else{
    btn.disabled = false;
  }
}

function submitHandler(){
  //Your code here
  alert("submitted");
  return false;
}
</script>

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