1

I'm beginning to learn JavaScript , and browser API. Why, if I press the "save" button , the pop up window does not appears in the browser ? Where am I wrong?

<label for="txtNome"><input id="txtNome" type="text" value=""/><br/></label>
<label for="txtCognome"><input id="txtCognome" type="text" value=""/><br/></label>
<button id="btnSalva"/>Salva</button><br/>

<script>
    var model = { nome: "Mario", cognome: "Rossi" };

    var view = {
        txtNome: document.getElementById("txtNome"),
        txtCognome: document.getElementById("txtCognome"),
        btnSalva: document.getElementById("btnSalva")
    };

    var controller;
        controller = {

        init: function () {
            view.txtNome.value = model.nome;
            view.txtCognome.value = model.cognome;
            view.btnSalva.onclick = controller.salva;
        },

        salva: function () {
            model.nome = view.txtNome.value;
            model.cognome = view.txtCognome.value;
            window.alert("FATTO");
        }
    };
</script>
3
  • Welcome to world of ECMAScript aka JavaScript ! Because you forgot to add an event listener to the button. A function that will execute when button clicks. Commented Feb 2, 2016 at 22:07
  • are you using some kind of MVC framework? There's nothing there that "runs" - just a bunch of variables. Commented Feb 2, 2016 at 22:09
  • 1
    change view.btnSalva.onclick = controller.salva into view.btnSalva.onclick = this.salva use this and do not forget to call the init method as well.. onclick or so.. Commented Feb 2, 2016 at 22:10

1 Answer 1

2

You need to call controller.init(), otherwise your code does nothing, you were just declaring some objects.

var model = { nome: "Mario", cognome: "Rossi" };

var view = {
  txtNome: document.getElementById("txtNome"),
  txtCognome: document.getElementById("txtCognome"),
  btnSalva: document.getElementById("btnSalva")
};

var controller;
controller = {

  init: function () {
    view.txtNome.value = model.nome;
    view.txtCognome.value = model.cognome;
    view.btnSalva.onclick = controller.salva;
  },

  salva: function () {
    model.nome = view.txtNome.value;
    model.cognome = view.txtCognome.value;
    window.alert("FATTO");
  }
};

controller.init(); //call init!
<label for="txtNome"><input id="txtNome" type="text" value=""/><br/></label>
<label for="txtCognome"><input id="txtCognome" type="text" value=""/><br/></label>
<button id="btnSalva"/>Salva</button><br/>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It was so obvious that I'm ashamed of having asked for it!!
No problem, sometimes it happens!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.