仅在有效时如何在同一页上显示表单数据?

时间:2018-10-26 23:24:59

标签: javascript forms validation form-submit

我正在做一个简单的作业,即创建一个表格,该表格采用成绩和姓名,然后分别显示每个成绩及其值和最终成绩。我没有使用form元素就创建了它,并且效果很好,但是问题是有效性,例如如果插入负数,它仍然可以计算。我必须更改代码,以便它将验证消息显示给用户,以显示某些值键入不正确或丢失,但是,该程序无法正常工作,因为它什么也不显示。我删除了表单元素,因此它仍将显示验证消息,但它还将计算空字段并显示该消息。 我创建了互相调用并在显示之前进行检查的函数,但仍然出现错误。 当用户单击“提交”时,如果所有有效数据都没有提交或不显示任何内容,我该怎么办?然后,如果全部有效,就会显示结果? 这是我的代码,希望你们能提供帮助。 附言:我的代码具有很多功能,正在测试中,因此请丢弃混乱的情况,希望对您有所帮助。 谢谢!

var x = 1;
var gradesArray = [];
var sum = 0;

var dict = [{
  grade: 94,
  message: ' is, A, excellent'
}, {
  grade: 90,
  message: ' is A-, great job'
}, {
  grade: 87,
  message: ' is B+, great'
}, {
  grade: 84,
  message: ' is, B, amazing'
}, {
  grade: 80,
  message: ' is, B-, study little more'
}, {
  grade: 77,
  message: ' is C+, you could do better'
}, {
  grade: 74,
  message: ' is C',
  70: ' is, C-'
}, {
  grade: 67,
  message: ' is D+'
}, {
  grade: 60,
  message: ' is D-'
}];


function gradeCheck(sum) {
  for (let i = 0; i < dict.length; i++) {
    if (sum >= dict[i].grade) {
      return dict[i].message;
    } else if (sum < 60) {
      return ' F, its a fail';
    }
  }
}

function gradeCal() {
  const elemnts = document.querySelectorAll('.grade-calculator input[type=number]')
  //var sum = 0;
  var x = 1;
  for (let element of elemnts) {
    gradesArray[x] = Number(element.value);
    sum += Number(element.value);
    x++;
  }
  pageResults(sum);
  //return false;
}


function pageResults(sum) {
  for (var i = 1; i < gradesArray.length; i++) {
    console.log(gradesArray[i]);
    document.getElementById(i.toString()).innerHTML = (gradesArray[i]).toString();
  }

  var nameS = document.getElementById("name").value;
  document.getElementById("AG").innerHTML = nameS + " your grade is: " + (sum / 4) + "  " + gradeCheck((sum / 4));
  showResults();
}


function showResults() {
  let fp = document.getElementById('formPage');
  let rp = document.getElementById('result');

  if (fp.style.display == '') {
    fp.style.display = 'none';
    rp.style.display = 'block';
  }
}

/* function validateForm(event) {
           gradeCal();
       }
        //I created this function so it 
        function process(){
    
           var nameV = document.getElementById('name').value,
               errors = 0;
            
           for(var i=0; i<gradesArray.length; i++){
               i <= 4? (gradesArray[i] > 0) && (gradesArray[i] < 26) ? errors += 0: errors +=1 : gradesArray[i] > 0 && gradesArray[i] < 100? errors += 0 : errors +=1;
           }
           if(nameV =='' && errors > 0){
               event.preventDefault();

           }else{
               pageResults(sum);
           }
       }
        */
<form>
  <p id='formPage' style="display:">
    <h2>Grade calculator</h2>
    <p class="form-example">
      <label for="name">Enter your name: </label>
      <input type="text" name="name" id="name" maxlength="10" required pattern="[A-Z][A-Za-z' -]+">
    </p>
    <p class="grade-calculator">
      <h3>Insert assignment grades</h3>
      <p class="assignment-Grd">
        <label for="assignment">Enter your assignment grade: </label>
        <p>
          <input type="number" name="assignment1" id="inputSpace1" min="0" max="25" placeholder="First Assignment" required pattern="\d+">
          <span class="validity"></span>
        </p>
        <p>
          <input type="number" name="assignment2" id="inputSpace2" min="0" max="25" placeholder="Second Assignment" required pattern="\d+">
          <span class="validity"></span>
        </p>
        <p>
          <input type="number" name="assignment2" id="inputSpace3" min="0" max="25" placeholder="Third Assignment" required pattern="\d+">
          <span class="validity"></span>
        </p>
        <p>
          <input type="number" name="assignment2" id="inputSpace4" min="0" max="25" placeholder="Fourth Assignment" required pattern="\d+">
          <span class="validity"></span>
        </p>
      </p>
      <p>
        <label for="assignment">Enter midtem grade: </label>
        <input type="number" name="midterm" id="inputSpace5" min="0" max="100" placeholder="midterm grade" required pattern="\d+">
        <span class="validity"></span>
      </p>
      <p>
        <label for="assignment">Enter Finam exam grade: </label>
        <input type="number" name="finalEx" id="inputSpace6" min="0" max="100" placeholder="final grade" required pattern="\d+">
        <span class="validity"></span>
      </p>
      <p>
        <label for="assignment">Enter project grade: </label>
        <input type="number" name="finalProj" id="inputSpace7" min="0" max="100" placeholder="Project grade" required pattern="\d+">
        <span class="validity"></span>
      </p>
      <p class="form-example">
        <button id="submitB" onclick="gradeCal()">Submit</button>
        <button onclick="reset()">Cancel</button>
      </p>
    </p>
  </p>
</form>
<div id="result" style="display: none">
  <h3>The results</h3>
  <div>First Assignment:
    <p class='gradeStyle' id="1"></p>
  </div>
  <div>Second Assignment:
    <p class='gradeStyle' id="2"></p>
  </div>
  <div>Third Assignment:
    <p class='gradeStyle' id="3"></p>
  </div>
  <div>Fourth Assignment:
    <p class='gradeStyle' id="4"></p>
  </div>
  <div>Midterm Exam Grade:
    <p class='gradeStyle' id="5"></p>
  </div>
  <div>Final Exam Grade:
    <p class='gradeStyle' id="6"></p>
  </div>
  <div>Project Grade:
    <p class='gradeStyle' id="7"></p>
  </div>
  <div>Average Grade:
    <p class='gradeStyle' id="AG"></p>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以使用一个简单的函数:

function validateGrade(inputBox) {
  if(inputBox.value<0) 
    inputBox.nextElementSibling.innerHTML = "Value cannot be less than 0";
}

并在每个文本框上使用onchange事件:

onchange="validateGrade(this)"

类似这样的东西:

var x = 1;
var gradesArray = [];
var sum = 0;

var dict = [{
  grade: 94,
  message: ' is, A, excellent'
}, {
  grade: 90,
  message: ' is A-, great job'
}, {
  grade: 87,
  message: ' is B+, great'
}, {
  grade: 84,
  message: ' is, B, amazing'
}, {
  grade: 80,
  message: ' is, B-, study little more'
}, {
  grade: 77,
  message: ' is C+, you could do better'
}, {
  grade: 74,
  message: ' is C',
  70: ' is, C-'
}, {
  grade: 67,
  message: ' is D+'
}, {
  grade: 60,
  message: ' is D-'
}];


function gradeCheck(sum) {
  for (let i = 0; i < dict.length; i++) {
    if (sum >= dict[i].grade) {
      return dict[i].message;
    } else if (sum < 60) {
      return ' F, its a fail';
    }
  }
}

function gradeCal() {
  const elemnts = document.querySelectorAll('.grade-calculator input[type=number]')
  //var sum = 0;
  var x = 1;
  for (let element of elemnts) {
    gradesArray[x] = Number(element.value);
    sum += Number(element.value);
    x++;
  }
  pageResults(sum);
  //return false;
}


function pageResults(sum) {
  for (var i = 1; i < gradesArray.length; i++) {
    console.log(gradesArray[i]);
    document.getElementById(i.toString()).innerHTML = (gradesArray[i]).toString();
  }

  var nameS = document.getElementById("name").value;
  document.getElementById("AG").innerHTML = nameS + " your grade is: " + (sum / 4) + "  " + gradeCheck((sum / 4));
  showResults();
}


function showResults() {
  let fp = document.getElementById('formPage');
  let rp = document.getElementById('result');

  if (fp.style.display == '') {
    fp.style.display = 'none';
    rp.style.display = 'block';
  }
}

function validateGrade(inputBox) {
  if(inputBox.value<0) 
    inputBox.nextElementSibling.innerHTML = "Value cannot be less than 0";
}

/* function validateForm(event) {
           gradeCal();
       }
        //I created this function so it 
        function process(){
    
           var nameV = document.getElementById('name').value,
               errors = 0;
            
           for(var i=0; i<gradesArray.length; i++){
               i <= 4? (gradesArray[i] > 0) && (gradesArray[i] < 26) ? errors += 0: errors +=1 : gradesArray[i] > 0 && gradesArray[i] < 100? errors += 0 : errors +=1;
           }
           if(nameV =='' && errors > 0){
               event.preventDefault();

           }else{
               pageResults(sum);
           }
       }
        */
.validity {
  color:red;
}
<form>
  <p id='formPage' style="display:">
    <h2>Grade calculator</h2>
    <p class="form-example">
      <label for="name">Enter your name: </label>
      <input type="text" name="name" id="name" maxlength="10" required pattern="[A-Z][A-Za-z' -]+">
    </p>
    <p class="grade-calculator">
      <h3>Insert assignment grades</h3>
      <p class="assignment-Grd">
        <label for="assignment">Enter your assignment grade: </label>
        <p>
          <input type="number" name="assignment1" id="inputSpace1" min="0" max="25" placeholder="First Assignment" required pattern="\d+" onchange="validateGrade(this)">
          <span class="validity"></span>
        </p>
        <p>
          <input type="number" name="assignment2" id="inputSpace2" min="0" max="25" placeholder="Second Assignment" required pattern="\d+" onchange="validateGrade(this)">
          <span class="validity"></span>
        </p>
        <p>
          <input type="number" name="assignment2" id="inputSpace3" min="0" max="25" placeholder="Third Assignment" required pattern="\d+" onchange="validateGrade(this)">
          <span class="validity"></span>
        </p>
        <p>
          <input type="number" name="assignment2" id="inputSpace4" min="0" max="25" placeholder="Fourth Assignment" required pattern="\d+" onchange="validateGrade(this)">
          <span class="validity"></span>
        </p>
      </p>
      <p>
        <label for="assignment">Enter midtem grade: </label>
        <input type="number" name="midterm" id="inputSpace5" min="0" max="100" placeholder="midterm grade" required pattern="\d+" onchange="validateGrade(this)">
        <span class="validity"></span>
      </p>
      <p>
        <label for="assignment">Enter Finam exam grade: </label>
        <input type="number" name="finalEx" id="inputSpace6" min="0" max="100" placeholder="final grade" required pattern="\d+" onchange="validateGrade(this)">
        <span class="validity"></span>
      </p>
      <p>
        <label for="assignment">Enter project grade: </label>
        <input type="number" name="finalProj" id="inputSpace7" min="0" max="100" placeholder="Project grade" required pattern="\d+" onchange="validateGrade(this)">
        <span class="validity"></span>
      </p>
      <p class="form-example">
        <button id="submitB" onclick="gradeCal()">Submit</button>
        <button onclick="reset()">Cancel</button>
      </p>
    </p>
  </p>
</form>
<div id="result" style="display: none">
  <h3>The results</h3>
  <div>First Assignment:
    <p class='gradeStyle' id="1"></p>
  </div>
  <div>Second Assignment:
    <p class='gradeStyle' id="2"></p>
  </div>
  <div>Third Assignment:
    <p class='gradeStyle' id="3"></p>
  </div>
  <div>Fourth Assignment:
    <p class='gradeStyle' id="4"></p>
  </div>
  <div>Midterm Exam Grade:
    <p class='gradeStyle' id="5"></p>
  </div>
  <div>Final Exam Grade:
    <p class='gradeStyle' id="6"></p>
  </div>
  <div>Project Grade:
    <p class='gradeStyle' id="7"></p>
  </div>
  <div>Average Grade:
    <p class='gradeStyle' id="AG"></p>
  </div>
</div>