Javascript code does not work

Asked

Viewed 4,957 times

0

I’m working on a page for web and I would like to know why my code does not work. Simply. It should print an "Alert" if the conditions of the if are true but this is not happening.

//valida dados com javascript
function verifica(objeto) {

  // convertendo string para int
  objeto = parseInt(objeto);

  if ( objeto.value<1 )
  {
    alert("O número de empresas deve ser maior que 0.");
  }
}
body {
  background-color: #C1CDC1;
}

p {
  color: #660066;
  font-size: x-large;
  font-family: Calibri;

}

.auto-style1 {
  text-align: center;
  margin-right: 10px;
  margin-left: 10px;
}
</br> </br> </br>
<p class="auto-style1"> Um conjunto de empresas ligadas umas às outras forma uma rede de relacionamentos. </br>
Para medir o grau de conectividade da rede, use a calculadora abaixo:</p>
<!-- formulário -->
<form name="form" id="form" action="" method="get">
  <table cellpadding="0" cellspacing="0" border="1" align="center">
    <tr>
      <td>Digite o número de empresas da rede.</td>
      <td><input type="text" name="txt_empresas" id="txt_empresas" value=""/> </td>
    </tr>
    <tr>
      <td> Digite o número de conexões da rede.</td>
      <td><input type="text" name="txt_conexoes" id="txt_conexoes" value=""/></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="button" name="btn_calcular" id="btn_calcular" value="Calcular"
                                            onsubmit="verifica(document.form.txt_empresas);" /></td>
    </tr>
  </table>
</form>


I made some suggested changes here and I still can’t reach the expected result. Alert does not appear:

//valida dados com javascript
function verifica(form1) {


  if ( (form1.txt_empresas.value == "") || (!isNum(form1.txt_empresas.value)) ||     (form1.txt_empresas.value <1) ) {
    alert ("Preencha o número de empresas corretamente.");
    form1.txt_empresas.focus();
    return false;
  }

  if ( (form1.txt_conexoes.value == "") || (!isNum(form1.txt_ligacoes.value)) || (form1.txt_conexoes.value <1) ) {
    alert ("Preencha o número de ligações corretamente.");
    form1.txt_conexoes.focus();
    return false;
  }

  return true;
}

function isNum(v) {

  var ValidChars = "0123456789";
  var isNumber=true;
  var Char;

  for (i=0; i< v.length && isNumver ==true; i++) {

    Char = v.charAt(i);
    if (ValidChars.indexOf(Char) == -1) {

      IsNumber = false;
    }
  }
  return isNumber;
}
body {
  background-color:#CDC8B1;
}

p {
  color: #660066;
  font-size: x-large;
  font-family: Calibri;

}

.auto-style1 {
  text-align: center;
  margin-right: 10px;
  margin-left: 10px;
}

form {
  align: center;
}
<br/> <br/> <br/>
<p class="auto-style1"> Um conjunto de empresas ligadas umas às outras forma uma rede de relacionamentos. <br/>
  Para medir o grau de conectividade da rede, use a calculadora abaixo:</p>
<!-- formulário -->
<form name="form1" id="form1" action="processa.php" method="get" onsubmit="return    verifica(this);">
  <table cellpadding="0" cellspacing="0" border="1" align="center">
    <tr>
      <td>Digite o número de empresas da rede.</td>
      <td><input type="text" name="txt_empresas" id="txt_empresas" value=""/> </td>
    </tr>
    <tr>
      <td> Digite o número de conexões da rede.</td>
      <td><input type="text" name="txt_conexoes" id="txt_conexoes" value=""/></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="btn_calcular" id="btn_calcular" value="Calcular" /></td>
    </tr>
  </table>
</form>

  • 2

    I noticed that one was missing } to close the function verifica. It was just a mistake when it came to putting the question, or your code is just like that?

  • @Giannini, I edited your question to organize your HTML, JS and CSS.

4 answers

5

The event onsubmit does not exist in inputs. It is used in the form.

Put the event on form and your code will work.

  • I made some suggested changes here and I still can’t reach the expected result. Alert does not appear. See the question.

  • @Giannini I did a test with your HTML, I left both fields blank and a alert appeared. You have some typing errors, like "txt_links" instead of "txt_connections", "isNumver" instead of "isNumber" and "Isnumber" instead of "isNumber", but fix these basic errors that will work

4

Good night.

There are some things to be corrected in your code.

1º -The js function is wrong parseint is running on the object and value and this missing close the last key.

function verifica(objeto) {

            // convertendo string para int
            value = parseInt(objeto.value);
            if (value < 1)
            {
                alert("O número de empresas deve ser maior que 0.");
            }
        }

2º - The onsubmit event must be in the form and not in the button.

<form name="form" id="form" action="" method="get" onsubmit="verifica(document.form.txt_empresas);">

3º - The button type must be SUBMIT to reload the form.

<input type="submit" name="btn_calcular" id="btn_calcular" value="Calcular"/>

Just a note, if I were you would start working with the element id, for example instead of Document.form.txt_companies using Document.getElementById("txt_companies")

  • I made some suggested changes here and I still can’t reach the expected result. Alert does not appear. See the question.

1

Two things were wrong with your code.

(TL;DR) Working version: http://jsfiddle.net/su4rux5o/1/

Now, about the mistakes:

  1. We had to convert the value to number before checking if the quantity was less than 1 (Form1.txt_enterprises.value <1);
  2. In your isNum function, you have created a variable isNumber, however in for you typed isNumver.

I also changed the way inputs are accessed. Using getElementById and not dot notation from the form.

0

Giannini, there is an implementation in Ecmascript 2015 (ES6) to check if the object of type Number is an Integer: Number.isInteger. Although it is not available in most modern browsers, you can use a suggested Polyfill adaptation in the link.

Another point, if you want to cancel the form submission, the ideal is to call the event.preventDefault() instead of a return false.

Number.prototype.isInteger = function() {
    return isFinite(this) && Math.floor(this) === this.valueOf();
};

var form1 = document.getElementById("form1");
form1.addEventListener("submit", function (event) {
  var qtd = {};
  qtd.Empresas = parseInt(form1.txt_empresas.value);
  qtd.Conexoes = parseInt(form1.txt_conexoes.value);

  if (!qtd.Empresas.isInteger() || qtd.Empresas < 1) {
    
    alert ("Preencha o número de empresas corretamente.");
    form1.txt_empresas.focus();
    event.preventDefault();
    return;
  }

  if (!qtd.Conexoes.isInteger() || qtd.Conexoes < 1) {
    alert ("Preencha o número de ligações corretamente.");
    form1.txt_conexoes.focus();
    event.preventDefault();
    return;
  }

  return true;
});
body {
  background-color:#CDC8B1;
}

p {
  color: #660066;
  font-size: x-large;
  font-family: Calibri;

}

.auto-style1 {
  text-align: center;
  margin-right: 10px;
  margin-left: 10px;
}

form {
  align: center;
}
<br/> <br/> <br/>
<p class="auto-style1"> Um conjunto de empresas ligadas umas às outras forma uma rede de relacionamentos. <br/>
  Para medir o grau de conectividade da rede, use a calculadora abaixo:</p>
<!-- formulário -->
<form name="form1" id="form1" action="processa.php" method="get">
  <table cellpadding="0" cellspacing="0" border="1" align="center">
    <tr>
      <td>Digite o número de empresas da rede.</td>
      <td><input type="text" name="txt_empresas" id="txt_empresas" value=""/> </td>
    </tr>
    <tr>
      <td> Digite o número de conexões da rede.</td>
      <td><input type="text" name="txt_conexoes" id="txt_conexoes" value=""/></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="btn_calcular" id="btn_calcular" value="Calcular" /></td>
    </tr>
  </table>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.