从HTML输入框中使用JS获取数值

huangapple go评论65阅读模式
英文:

get value from HTML input using JS

问题

我刚开始学习编程,试图将面向对象编程范式应用于一个示例中。

尝试创建一个对象(这里是角色),并将其属性分配为HTML文件中输入的值。

出现的错误是'javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading 'value')。

<body>
    <label for="namebox">角色名</label>
    <input type="text" name="" id="namebox">
    <label for="agebox">年龄</label>
    <input type="text" name="" id="agebox">
    <label for="humanclass">人类</label>
    <label for="majinclass">魔人</label>

    <input type="radio" name="class1" id="humanclass">
    <input type="radio" name="class1" id="majinclass">

    <input type="button" value="创建角色" id="creationbtn" onclick='char1.identify()'>
    <input type="reset" value="取消">
</body>
class Charcreation {
    constructor(name, age, charclass) {
        this.name = name;
        this.age = age;
        this.class = charclass;
    }

    identify() {
        console.log('我的名字是' + this.name + ',我今年' + this.age + '岁,是一个' + this.class)
    }
}

charname = document.getElementById("namebox").value;
charage = document.getElementById('agebox').value;
charselection = document.getElementsByName('class1');
charclass = function getClass() {
    for (i = 0; i < charselection.length; i++) {
        if (charselection[i].checked)
            return charselection[i].id;
    }
}

char1 = new Charcreation(charname, charage, charclass())
char1.identify();

提前感谢。

英文:

I just started learning coding. and i was trying to apply the OOP pradigm to an example.
I am trying to create an object (the character here) and assign its properties as the values input within the html file.

the error that keeps appearing is 'javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading 'value') .

    &lt;body&gt;
    &lt;label for=&quot;namebox&quot;&gt;Character Name&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;namebox&quot;&gt;
    &lt;label for=&quot;agebox&quot;&gt;Age&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;agebox&quot;&gt;
    &lt;label for=&quot;humanclass&quot;&gt;Human&lt;/label&gt;
    &lt;label for=&quot;majinclass&quot;&gt;Majin&lt;/label&gt;

    &lt;input type=&quot;radio&quot; name=&quot;class1&quot; id=&quot;humanclass&quot;&gt;
    &lt;input type=&quot;radio&quot; name=&quot;class1&quot; id=&quot;majinclass&quot;&gt;

    &lt;input type=&quot;button&quot; value=&quot;Create Character&quot; id=&quot;creationbtn&quot; onclick=&#39;char1.identify()&#39;&gt;
    &lt;input type=&quot;reset&quot; value=&quot;Cancel&quot;&gt;

&lt;/body&gt;
    class Charcreation {
    constructor(name, age, charclass) {
        this.name = name;
        this.age = age;
        this.class = charclass;
    }

    identify() {
        console.log(&#39;my name is &#39; + this.name + &#39; and i am a &#39; + this.age + &#39; years old &#39; + this.class)
    }
}


charname = document.getElementById(&quot;namebox&quot;).value;
charage = document.getElementById(&#39;agebox&#39;).value;
charselection = document.getElementByName(&#39;class1&#39;).value;
charclass =
    function getClass() {
        for (i == 0; i &lt; charselection.length; i++) {
            if (charselection[i].checked)
                return charselection[i];
        }
    }

char1 = new Charcreation(charname, charage, charclass())
char1.identify();

Thanks in advance

答案1

得分: 1

这是你要的翻译:

There are a few errors in your code as @Chris G points out plus some others. Here's an update to your code with corrections to get a successful output for your `char1.identify();` method.

I've added some CSS styling that's not necessary to the output.

When the user clicks on the `#creationbtn` button, code execution needs to retrieve values of the form controls each time. Your original code is retrieving values of the `input` controls when the page is loaded and not each time the button is clicked.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->
class Charcreation {
  constructor(name, age, charclass) {
    this.name = name;
    this.age = age;
    this.class = charclass;
  }

  identify() {
    var identityText = 'my name is ' + this.name + ' and i am a ' + this.age + ' years old ' + this.class;
    //console.log(identityText);
    document.querySelector("#identity").textContent = identityText;
  }
}

function createIdentity() {
  var charname = document.getElementById("namebox").value;
  var charage = document.getElementById('agebox').value;
  var charselection = document.getElementsByName('class1');
  var charclass =
    function getClass() {
      for (i = 0; i < charselection.length; i++) {
        if (charselection[i].checked) {
          var labelElem = document.querySelector("label[for=" + charselection[i].id + "]");
          if (labelElem) {
            return labelElem.textContent;
          }
        }
      }
    }

  var char1 = new Charcreation(charname, charage, charclass());
  char1.identify();
}

<!-- language: lang-css -->
#character-form {
  display: grid;
  width: 15rem;
}

.radio-control {
  display: grid;
  grid-auto-flow: column;
  padding: .5rem 0;
  width: fit-content;
}

.radio-control input {
  margin: 0 .5rem;
}

<!-- language: lang-html -->
<div id="character-form">
  <label for="namebox">Character Name</label>
  <input type="text" name="" id="namebox">

  <label for="agebox">Age</label>
  <input type="text" name="" id="agebox">

  <span class="radio-control">
        <label for="humanclass">Human</label>
        <input type="radio" name="class1" id="humanclass">
    </span>
  <span class="radio-control">
        <label for="majinclass">Majin</label>
        <input type="radio" name="class1" id="majinclass">
    </span>

  <input type="button" value="Create Character" id="creationbtn" onclick='createIdentity()'>
  <input type="reset" value="Cancel">
  <span id="identity"></span>
</div>

<!-- end snippet -->

希望这对你有帮助。

英文:

There are a few errors in your code as @Chris G points out plus some others. Here's an update to your code with corrections to get a successful output for your char1.identify(); method.

I've added some CSS styling that's not necessary to the output.

When the user clicks on the #creationbtn button, code execution needs to retrieve values of the form controls each time. Your original code is retrieving values of the input controls when the page is loaded and not each time the button is clicked.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

class Charcreation {
  constructor(name, age, charclass) {
    this.name = name;
    this.age = age;
    this.class = charclass;
  }

  identify() {
    var identityText = &#39;my name is &#39; + this.name + &#39; and i am a &#39; + this.age + &#39; years old &#39; + this.class;
    //console.log(identityText);
    document.querySelector(&quot;#identity&quot;).textContent = identityText;
  }
}

function createIdentity() {
  var charname = document.getElementById(&quot;namebox&quot;).value;
  var charage = document.getElementById(&#39;agebox&#39;).value;
  var charselection = document.getElementsByName(&#39;class1&#39;);
  var charclass =
    function getClass() {
      for (i = 0; i &lt; charselection.length; i++) {
        if (charselection[i].checked) {
          var labelElem = document.querySelector(&quot;label[for=&quot; + charselection[i].id + &quot;]&quot;);
          if (labelElem) {
            return labelElem.textContent;
          }
        }
      }
    }

  var char1 = new Charcreation(charname, charage, charclass());
  char1.identify();
}

<!-- language: lang-css -->

#character-form {
  display: grid;
  width: 15rem;
}

.radio-control {
  display: grid;
  grid-auto-flow: column;
  padding: .5rem 0;
  width: fit-content;
}

.radio-control input {
  margin: 0 .5rem;
}

<!-- language: lang-html -->

&lt;div id=&quot;character-form&quot;&gt;
  &lt;label for=&quot;namebox&quot;&gt;Character Name&lt;/label&gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;namebox&quot;&gt;

  &lt;label for=&quot;agebox&quot;&gt;Age&lt;/label&gt;
  &lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;agebox&quot;&gt;

  &lt;span class=&quot;radio-control&quot;&gt;
        &lt;label for=&quot;humanclass&quot;&gt;Human&lt;/label&gt;
        &lt;input type=&quot;radio&quot; name=&quot;class1&quot; id=&quot;humanclass&quot;&gt;
    &lt;/span&gt;
  &lt;span class=&quot;radio-control&quot;&gt;
        &lt;label for=&quot;majinclass&quot;&gt;Majin&lt;/label&gt;
        &lt;input type=&quot;radio&quot; name=&quot;class1&quot; id=&quot;majinclass&quot;&gt;
    &lt;/span&gt;

  &lt;input type=&quot;button&quot; value=&quot;Create Character&quot; id=&quot;creationbtn&quot; onclick=&#39;createIdentity()&#39;&gt;
  &lt;input type=&quot;reset&quot; value=&quot;Cancel&quot;&gt;
  &lt;span id=&quot;identity&quot;&gt;&lt;/span&gt;
&lt;/div&gt;

<!-- end snippet -->

答案2

得分: 0

错误信息一直出现的问题是 'javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading 'value')。

您确定脚本在DOM渲染后触发了吗?可能是它在实际HTML渲染之前运行,这就是为什么.getElementById("namebox")返回null的原因。

可能有其他方法来确保这一点,但我知道最简单的方法是将脚本放在页脚而不是页眉中。

英文:

> the error that keeps appearing is 'javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading 'value') .

Have you made sure that the script is firing after the DOM gets rendered?
It's possible that it is running before the actual HTML has been rendered and that is why .getElementById(&quot;namebox&quot;) is returning null.

There are probably other ways to ensure this, but the easiest I know of is just put the script inside of the footer instead of the header.

huangapple
  • 本文由 发表于 2023年2月18日 01:13:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定