Как получить доступ к объекту массива HTML в JavaScript? - PullRequest
0 голосов
/ 30 октября 2018

извините за простой вопрос. Я действительно новичок в Javascript. Мне нужно получить доступ к моему объекту формы массива HTML в моем JavaScript, но я не знаю, как это сделать.

Цель состоит в том, чтобы вызвать предупреждение в javascript, чтобы браузер отображал сообщение в соответствии с условием в javascript. Вот мой код:

checkScore = function()
 {
 //I don't know how to access array in HTML Form, so I just pretend it like this :
  
 var student = document.getElementByName('row[i][student]').value;
 var math = document.getElementByName('row[i][math]').value; 
 var physics = document.getElementByName('row[i][physics]').value; 

if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}

if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
 
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>

<form name="student_score" action="/action_page.php">

<table border=1>

<thead>

<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>

<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>

<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>             
</tr>

<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>

</tbody>
</table>
</form> 

<p>If you click the "Submit" button, it will save the data.</p>

Ответы [ 3 ]

0 голосов
/ 30 октября 2018

Ну, он точно соответствует вашей строке кода (потому что вы сказали, что не хотите слишком сильно менять код).

<h2>HTML Forms</h2>

<form name="student_score" action="/action_page.php">

<table border=1>

<thead>

<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>

<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>

<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>             
</tr>

<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>

</tbody>
</table>
</form> 

JavaScript [Снова отредактировано с использованием части кода @Jon P, селектор запросов действительно более динамичен, а значение запрошенного вами «другого» поля закомментировано]

//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
    //Get our ancestor row (the parent of the parent);
    var row = element.parentNode.parentNode;
    //Use an attribute selector to get our infor from the row
    var student = row.querySelector("[name*='[student]']").value;
    var math = row.querySelector("[name*='[math]']").value;
    var physics = row.querySelector("[name*='[physics]']").value;
    var other = row.querySelector("[name*='[otherinfo]']");

    if (parseInt(math) >= 80) {
        //other.value = student + " ,You are good at mathematic";
        alert(student + " ,You are good at mathematic");
    }

    if (parseInt(physics) >= 80) {
        //other.value = student + " ,You are good at physics";
        alert(student + " ,You are good at physics");
    }
    otherField.focus();
    otherField.select();
}

Проверено :), и извините за мой английский!

0 голосов
/ 31 октября 2018

Мы собираемся использовать несколько вещей здесь, чтобы упростить это.

Первый - Прослушиватели событий , это удаляет весь javascript из вашего HTML. Это также делает его более динамичным и более простым для рефакторинга, если к таблице добавляются строки с помощью javascript.

Далее идет parentNode, который мы используем, чтобы найти tr, который заключал элемент, по которому щелкнули;

Затем мы используем querySelectorAll с селектором атрибута , чтобы получить наши целевые поля из tr выше.

/*This does the work*/
function checkScore(event) {
  //Get the element that triggered the blur
  var element = event.target;
  //Get our ancestor row (the parent of the parent);
  var row = element.parentNode.parentNode;
  //Use an attribute selector to get our infor from the row
  var student = row.querySelector("[name*='[student]']").value;
  var math = row.querySelector("[name*='[math]']").value;
  var physics = row.querySelector("[name*='[physics]']").value;
  var otherField = row.querySelector("[name*='[otherinfo]']");

  if (parseInt(math, 10) >= 80) {
    alert(student + " ,You are good at mathematic");
  }

  if (parseInt(physics, 10) >= 80) {
    alert(student + " ,You are good at physics");
  }

  otherField.focus();
  otherField.select();
}

/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
  targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>

<form name="student_score" action="/action_page.php">

  <table border=1>

    <thead>
      <tr>
        <td>Student</td>
        <td>Math Score</td>
        <td>Physics Score</td>
        <td>Other info</td>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td><input type="text" name="row[1][student]" class='student'></td>
        <td><input type="number" name="row[1][math]" min="0" max="100"></td>
        <td><input type="number" name="row[1][physics]" min="0" max="100"></td>
        <td><input type="text" name="row[1][otherinfo]"></td>
      </tr>

      <tr>
        <td><input type="text" name="row1[2][student]"></td>
        <td><input type="number" name="row[2][math]" min="0" max="100"></td>
        <td><input type="number" name="row[2][physics]" min="0" max="100"></td>
        <td><input type="text" name="row[2][otherinfo]"></td>
      </tr>

      <tr>
        <td>
          <input type="submit" value="Submit">
        </td>
      </tr>

    </tbody>
  </table>
</form>
0 голосов
/ 30 октября 2018

Попробуйте, не проверяли

var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");

for(var i = 0; i < students.length; i++){
    var student = students[i].childnodes[0].value;
    var math = students[i].childnodes[1].value;
    var physics = students[i].childnodes[2].value;
    if (parseInt(math) >= 80 ) {
    alert(student + " ,You are good at mathematic");
    }

    if (parseInt(physics) >= 80 ){
    alert(student + " ,You are good at physics");
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...