Domanda

Ciao, questo è quello che ho in testa al mio file:

function entsub(event)
        {
              if (event && event.which == 13) 
                write1();
              else
            return true;

        }

e nel corpo, la mia forma è:

<form id="writeform" name="writeform">
  Message: <br />
  <textarea name="message" rows="3" id="message" style="width:90%;" onkeypress="return entsub(event)"></textarea>

  <br />
  <input name="send" type="button" id="send" value="Send" onclick="write1()" />
  <span id="sent"></span>
  &nbsp;&nbsp;&nbsp; <input type="reset" value="Reset" />
  </form>

Devo fare in modo che quando premo Invio quando sono nell'area di testo, non crei una nuova riga ma la invii [vedi il mio <input type="button">]

Ma non funzionerà!Continua a creare una nuova linea...Usando IE8 ora.

È stato utile?

Soluzione

Usa keyCode invece di quale.

A seconda del browser, è necessario impedire l'azione predefinita. Dai un'occhiata a event.cancelBubble ed event.returnValue per IE ed event.stopPropagation () e event.preventDefault () per Firefox.

Altri suggerimenti

Beh, non sono sicuro di cosa faccia write1(), ma sarebbe prudente restituire false quando la condizione è soddisfatta.

function entsub(event)
{
    if (event && event.keyCode == 13) {
        write1();
        return false; //Return false to prevent default execution
                      //Some browsers use event.preventDefault() etc.
    }else{
        return true;
    }
}

Di solito il test tra browser è il seguente:

function entsub(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        write1();
    } 
    return true;
}

Se vuoi usare jquery, puoi farlo:

        $(document).ready(function() {

            $("#txtTest").keypress(function(e) {
                var code = (e.keyCode ? e.keyCode : e.which);

                if (code == 13) {
                    doSomething();
                    return false;
                }
            });

        });

        function doSomething() {
            alert("I did it!");
        }

dove txtTest è l'id della tua textarea.

Per un modo non correlato a js, sono abbastanza sicuro che puoi semplicemente utilizzare un input di type="submit" e utilizzerà invio per inviare il modulo.A quel punto, sposteresti semplicemente il tuo evento su onsubmit.

Un modo più pulito è quello di passare da <input type="button"> a <input type="submit"> e spostare onclick="..." in onsubmit="..." nel modulo. Ciò non richiederebbe così tanto JavaScript soggetto a errori e funzionerebbe in più casi.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top