我如何输入变量来改变标签文本使用javascript

How do I input variables to change label text using javascript

本文关键字:标签 改变 文本 javascript 变量 何输入 输入      更新时间:2023-09-26

我试图使它,当用户输入一个名字到输入框,然后单击'输入候选人'按钮,它会改变下面的标签的名称。在javascript中有办法做到这一点吗?我刚刚开始编程,所以我有点像个新手。

            <form class="simple-form">
                <div>Enter your candidate <b>names</b> in the boxes below:</div>
                <br/>
                <label for="C1">Candidate 1:</label>
                <input type="text" name="C1" id="C1" class="InputBox" />
                <br/>
                <label for="C2">Candidate 2:</label>
                <input type="text" name="C2" id="C2" class="InputBox" />
                <br/>
                <label for="C3">Candidate 3:</label>
                <input type="text" name="C3" id="C3" class="InputBox" />
                <br/>
                <label for="C4">Candidate 4:</label>
                <input type="text" name="C4" id="C4" class="InputBox" />
                <br/>
                <label for="C5">Candidate 5:</label>
                <input type="text" name="C5" id="C5" class="InputBox" />
                <br/>
                <input type="button" OnClick="EnterCandidates" value="Enter Candidates" />
                <br/>
                <br/>
                <div>Enter the candidates <b>votes</b> in the boxes below:</div>
                <br/>
                <label for="V1" id="L_V1">Name 1:</label>
                <input type="text" name="V1" id="I_V1" class="InputBox" />
                <br/>
                <label for="V2" id="L_V2">Name 2:</label>
                <input type="text" name="V2" id="I_V2" class="InputBox" />
                <br/>
                <label for="V3" id="L_V3">Name 3:</label>
                <input type="text" name="V3" id="I_V3" class="InputBox" />
                <br/>
                <label for="V4" id="L_V4">Name 4:</label>
                <input type="text" name="V4" id="I_V4" class="InputBox" />
                <br/>
                <label for="V5" id="L_V5">Name 5:</label>
                <input type="text" name="V5" id="I_V5" class="InputBox" />
                <br/>
                <input type="button" OnClick="" value="Enter Votes" />
                <br/>
            </form>

感谢所有帮助过我的人。最后一个问题。我决定使用这个代码(感谢@David Thomas):

function EnterCandidates() {
  var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
    names = document.querySelectorAll('label[for^=V][id^=L_V]');
  Array.prototype.forEach.call(names, function(label, index) {
    if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
      label.textContent = candidateNameInputs[index].value;
    }
  });
}

我如何添加一个验证,使用户只能使用字符串,它有一定的字符限制,如20个字符?我试图添加一个你的家伙的建议,但我想我做错了,因为它没有工作。

您可能想使用

document.getElementById('Label ID').innerHTML = document.getElementById('Input ID').value

请参阅此处:http://jsfiddle.net/jzqp70oq/

希望这是你所期待的。

document.getElementById('L_V1').innerHTML= document.getElementById('C1').value;

//字符验证
var val = document.getElementById('c2').value;
if (!val.match(/^[a-zA-Z]+$/)) 
{
    alert('Only alphabets are allowed');
    return false;
}

//长度验证
if (val.length >10) {
   alert("characters are too long !")
} 

试试这个

<head>
<script type="text/javascript">
function test(){document.getElementById('Label_ID').innerHTML=document.getElementById('Input_ID').value;
}
</script>
</head>
//....
<input type="button" onClick="EnterCandidates();" value="Enter Candidates" />
//...

我认为下面的JavaScript实现了您想要的输出:

function EnterCandidates() {
    // Using document.querySelectorAll() to get the <input> elements
    // whose id attribute/property starts with the upper-case letter C:
    var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
    // finding the <label> elements whose 'for' attribute starts with
    // the upper-case letter V, and whose id starts with the string "L_V":
        names = document.querySelectorAll('label[for^=V][id^=L_V]');
    // using Function.prototype.call() to iterate over the Array-like
    // nodeList, returned by document.querySelectorAll, using an
    // an Array method (Array.prototype.forEach()):
    Array.prototype.forEach.call(names, function (label, index) {
        // the first argument of the anonymous function ('label')
        // is the array-element of the Array (or Array-like) structure
        // over which we're iterating, and is a <label> element,
        // the second argument ('index') is the index of that current
        // element in the Array (or Array-like structure).
        // if the value of the <input> at the same index in the collection
        // as the current <label>'s index has a value that is not
        // equal to its default-value:
        if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
            // we update the textcontent of the <label> to be
            // equal to that of the value entered in the <input>
            label.textContent = candidateNameInputs[index].value;
        }
    });
}

function EnterCandidates() {
  var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
    names = document.querySelectorAll('label[for^=V][id^=L_V]');
  Array.prototype.forEach.call(names, function(label, index) {
    if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
      label.textContent = candidateNameInputs[index].value;
    }
  });
}
label::before {
  content: "'A";
 white-space: pre;
}
label::after {
  content: ': ';
}
label,
input {
  box-sizing: border-box;
  line-height: 1.4em;
  height: 1.4em;
  margin-bottom: 0.2em;
}
input[type=button]:last-child {
  display: block;
}
<form class="simple-form">
  <fieldset>
    <legend>Enter your candidate <b>names</b> in the boxes below:</legend>
    <label for="C1">Candidate 1</label>
    <input type="text" name="C1" id="C1" class="InputBox" />
    <label for="C2">Candidate 2</label>
    <input type="text" name="C2" id="C2" class="InputBox" />
    <label for="C3">Candidate 3</label>
    <input type="text" name="C3" id="C3" class="InputBox" />
    <label for="C4">Candidate 4</label>
    <input type="text" name="C4" id="C4" class="InputBox" />
    <label for="C5">Candidate 5</label>
    <input type="text" name="C5" id="C5" class="InputBox" />
    <input type="button" onclick="EnterCandidates()" value="Enter Candidates" />
  </fieldset>
  <fieldset>
    <legend>Enter the candidates <b>votes</b> in the boxes below:</legend>
    <label for="V1" id="L_V1">Name 1</label>
    <input type="text" name="V1" id="I_V1" class="InputBox" />
    <label for="V2" id="L_V2">Name 2</label>
    <input type="text" name="V2" id="I_V2" class="InputBox" />
    <label for="V3" id="L_V3">Name 3</label>
    <input type="text" name="V3" id="I_V3" class="InputBox" />
    <label for="V4" id="L_V4">Name 4</label>
    <input type="text" name="V4" id="I_V4" class="InputBox" />
    <label for="V5" id="L_V5">Name 5</label>
    <input type="text" name="V5" id="I_V5" class="InputBox" />
    <input type="button" value="Enter Votes" />
  </fieldset>
</form>

JS demo,用于实验和开发。

请注意,我编辑了你的HTML结构,以及,试图使它更语义的结构;删除<br>节点,并切换到CSS来将元素分隔成新行;使用<legend>元素来保存每个部分的"指令"(删除您最初使用的<div>元素)。此外,我使用<fieldset>元素将相关元素分组在一起,将<label><input>组包装在一起,以及相关的"control"按钮。

此外,由于它使更新文本变得稍微容易一些,而不必添加"presentation"字符串(冒号),我使用CSS来实现这一目的,以便可以轻松更新演示文稿,而无需使用搜索/替换。不可避免的,设计变了

关于问题的更新,以及在评论中留下的问题:

是否有一种方法可以添加验证,以便用户只能使用字母表中的字母。还有字符限制,用户只能输入<20个字符?我如何在这个代码中实现它?如果有答案,我会修改我的帖子。

答案当然是"是",为此我建议采用以下方法:

function EnterCandidates() {
    var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
        names = document.querySelectorAll('label[for^=V][id^=L_V]'),
        // A regular expression literal; which means:
        // the complete string, from the start (^)
        // to the end ($) must comprise of characters
        // a-z (inclusive), apostrophe (') and white-space
        // (to allow O'Neill, for example); this must be
        // zero to 20 characters in length ({0,20}) and
        // is case-insensitive (i):
        validity = /^[a-z''s]{0,20}$/i,
        // two empty/uninitialised variables for use within
        // the forEach() loop:
        tempNode, tempVal;
    Array.prototype.forEach.call(names, function (label, index) {
        // caching the candidateNameInputs[index] Node:
        tempNode = candidateNameInputs[index];
        // caching the value of that Node:
        tempVal = tempNode.value;
        // if the value of the Node is not equal to the default-value
        // of the Node, AND the value of the Node matches the regular
        // expression (returns true if so, false if not):
        if (tempVal !== tempNode.defaultValue && validity.test(tempVal)) {
            // we remove the 'invalid' class from the Node if
            // it's present:
            tempNode.classList.remove('invalid');
            // update the text of the <label>:
            label.textContent = tempVal;
        // otherwise, if the value does not match (!) the
        // the regular expression:
        } else if (!validity.test(tempVal)) {
            // we add the 'invalid' class-name to the
            // Node:
            tempNode.classList.add('invalid');
            // and set the text of the <label> to
            // its original state, by concatenating
            // the string "Name " with the result of the
            // current (zero-based) index of the <label>
            // after adding 1 (to make it one-based):
            label.textContent = 'Name ' + (index + 1);
        // otherwise, if the value is equal to the default-value
        // we do nothing other than remove the 'invalid'
        // class-name from the <input> Node:
        } else if (tempVal === tempNode.defaultValue) {
            tempNode.classList.remove('invalid');
        }
    });
}

function EnterCandidates() {
  var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
    names = document.querySelectorAll('label[for^=V][id^=L_V]'),
    validity = /^[a-z''s]{0,20}$/i,
    tempNode, tempVal;
  Array.prototype.forEach.call(names, function(label, index) {
    tempNode = candidateNameInputs[index];
    tempVal = tempNode.value;
    if (tempVal !== tempNode.defaultValue && validity.test(tempVal)) {
      tempNode.classList.remove('invalid');
      label.textContent = tempVal;
    } else if (!validity.test(tempVal)) {
      tempNode.classList.add('invalid');
      label.textContent = 'Name ' + (index + 1);
    } else if (tempVal === tempNode.defaultValue) {
      tempNode.classList.remove('invalid');
    }
  });
}
label::before {
  content: "'A";
 white-space: pre;
}
label::after {
  content: ': ';
}
label,
input {
  box-sizing: border-box;
  line-height: 1.4em;
  height: 1.4em;
  margin-bottom: 0.2em;
}
input[type=button]:last-child {
  display: block;
}
input.invalid {
  border-color: #f00;
}
<form class="simple-form">
  <fieldset>
    <legend>Enter your candidate <b>names</b> in the boxes below:</legend>
    <label for="C1">Candidate 1</label>
    <input type="text" name="C1" id="C1" class="InputBox" />
    <label for="C2">Candidate 2</label>
    <input type="text" name="C2" id="C2" class="InputBox" />
    <label for="C3">Candidate 3</label>
    <input type="text" name="C3" id="C3" class="InputBox" />
    <label for="C4">Candidate 4</label>
    <input type="text" name="C4" id="C4" class="InputBox" />
    <label for="C5">Candidate 5</label>
    <input type="text" name="C5" id="C5" class="InputBox" />
    <input type="button" onclick="EnterCandidates()" value="Enter Candidates" />
  </fieldset>
  <fieldset>
    <legend>Enter the candidates <b>votes</b> in the boxes below:</legend>
    <label for="V1" id="L_V1">Name 1</label>
    <input type="text" name="V1" id="I_V1" class="InputBox" />
    <label for="V2" id="L_V2">Name 2</label>
    <input type="text" name="V2" id="I_V2" class="InputBox" />
    <label for="V3" id="L_V3">Name 3</label>
    <input type="text" name="V3" id="I_V3" class="InputBox" />
    <label for="V4" id="L_V4">Name 4</label>
    <input type="text" name="V4" id="I_V4" class="InputBox" />
    <label for="V5" id="L_V5">Name 5</label>
    <input type="text" name="V5" id="I_V5" class="InputBox" />
    <input type="button" value="Enter Votes" />
  </fieldset>
</form>

JS demo,用于实验和开发。

引用:

  • CSS:
    • ::after伪元素
    • ::before伪元素
    • content property.
  • HTML:
    • <fieldset>
    • <label> .
    • <legend> .
  • JavaScript:
    • Array.prototype.forEach() .
    • Element.classList .
    • Function.prototype.call() .
    • HTMLFieldSetElement .
    • HTMLLabelElement .
    • HTMLLegendElement .
    • JavaScript正则表达式指南。
    • Node.textContent .
    • RegExp.prototype.test() .