franchyze923
franchyze923

Reputation: 1200

How to prevent Enter causing Dojo website to reload

I have a Dojo Dialog and within it there is a Form, TextBox and Button.

When the Form is open and I type something in the TextBox and press Enter, the entire website reloads.

How can I prevent this? Clicking the OK button works as expected. Is there a way I can disable the Enter behavior?

var form = new Form();

new TextBox({
    placeHolder: "enter value:"
}).placeAt(form.containerNode);

new Button({
    label: "OK", 
    'onClick': function () {
        console.log(`form value is: ${form._descendants[0].value}`)
        dia.hide();
    },
}).placeAt(form.containerNode);

var dia = new Dialog({
    content: form,
    title: "Save",
    style: "width: 300px",
});

form.startup();
dia.show();

Upvotes: 1

Views: 104

Answers (1)

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

By default the form submits when we click enter, in order to prevent that , you must listen the submit event and prevent the default browser action by using event.preventDefault()

adding the above code will fix your issue :

form.on("submit", function(e){
    e.preventDefault();
})   

See belwo working snippet :

require(["dijit/Dialog", "dijit/registry", "dojo/ready", "dijit/form/Button", "dijit/form/Form" , "dijit/form/ValidationTextBox"],
  function(Dialog, registry, ready, Button, Form, ValidationTextBox) {


    ready(function() {
      
      
    
      var form = new Form();

      new ValidationTextBox({
        name:"textValue",
        required:true,
        placeHolder: "enter value:"
      }).placeAt(form.containerNode);

      new ValidationTextBox({
        name:"otherTextValue",
        required:true,
        placeHolder: "enter value:"
      }).placeAt(form.containerNode);

      new Button({
        label: "OK",
        type:"submit"
      }).placeAt(form.containerNode);

      var dia = new Dialog({
        content: form,
        title: "Save",
        style: "width: 300px",
      });
     
      form.on("submit", function(e){
         e.preventDefault();
         if(form.validate()) {
            console.log(form.get("value"))
            dia.hide()
         }
      })    
      
      form.startup();
      dia.show();
      
      
      
      registry.byId("btn").on("click", function() {
        form.reset();
        dia.show();
      });

    });
  }
);
<script type="text/javascript">
  dojoConfig = {
    isDebug: true,
    async: true,
    parseOnLoad: true
  }
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<link href="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dijit/themes/claro/claro.css" rel="stylesheet" />

<body class="claro">
  <div data-dojo-type="dijit/form/Button" id="btn"> show again </div>
</body>

Upvotes: 1

Related Questions