如何将选定的单选按钮存储在数组中?

时间:2019-04-11 21:26:08

标签: javascript php html ajax

我正在进行在线检查,其中问题是通过php来自数据库并通过ajax显示的。我想获取选定的单选按钮并将其存储在数组中,这是没有发生的,因为我没有得到值。只有我不能在数组中推送无线电值,其他所有东西都工作正常。 如果您需要检查问题,我可以提供php代码 请帮助

HTML:

<button type="button" class="btn btn-info btn-md" id="mark" onclick="loadNextQues(1)">Mark for Review & Next</button>
<button type="button" class="btn btn-info btn-md">Clear Response</button>
<button type="submit" class="btn btn-info btn-md" id="save" style="position:absolute;right:20px;bottom:35px" onclick="loadNextQues(0)">Save and Next</button>
<form action="check.php">
  <button type='submit' class="btn btn-info btn-md" id="water" style="visibility:hidden;position:absolute;right:20px;bottom:35px">submit</button>

Javascript:

 function loadNextQues(flag) {
  quesno++;
  if (flag == 1) {
    //add css to the button for review
  } else {
    //add css for the button as answered
  }
  url = "http://localhost/assignments/load-questions.php?qno=" + quesno;
  $.get(url, function(data, status) {
    response = JSON.parse(data);
    console.log(response);
    var quest = "<p>" + response.qno + " " + response.question + "</p>";
    quest += "<form>";
    quest +=
      '<input type="radio" name="op" value=\'' +
      response.opA +
      "'>A." +
      response.opA +
      "<br>";
    quest +=
      '<input type="radio" name="op" value=\'' +
      response.opB +
      "'>B." +
      response.opB +
      "<br>";
    quest +=
      '<input type="radio" name="op" value=\'' +
      response.opC +
      "'>C." +
      response.opC +
      "<br>";
    quest +=
      '<input type="radio" name="op" value=\'' +
      response.opD +
      "'>D." +
      response.opD +
      "<br>";
    quest += "</form>";
    document.getElementById("questBox").innerHTML = quest;
  });

  if (quesno == 15) {
    document.getElementById("mark").style.visibility = "hidden";
    document.getElementById("save").style.visibility = "hidden";
    document.getElementById("water").style.visibility = "visible";
  }
  var myArr = [];
  var Selected = document.querySelectorAll('[name="op"]:checked');
  if (Selected != null) {
    arr.push(Selected.value);
  }
  console.log(arr);
}

2 个答案:

答案 0 :(得分:0)

您可以使用ES6语法和.map()数组方法。像...

var arr = Selected.map(dom => dom.value);

答案 1 :(得分:0)

您需要遍历元素以获取它们的值,也未定义arr。

编辑以获得预期效果...

MYARRAY: str1,str2,str3