在搜索字段中更新文本的按钮,但要依次输入几个值?

问题描述 投票:0回答:1

有了这段代码,我们可以向搜索字段发送一个值。现在,考虑到这个例子,我们如何用同一个按钮依次插入更多的值,例如:值1,值2,值3...?

http:/jsfiddle.netg506bxL41

<form id="form1" name="form1" method="post">
    <p>
        <input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
    </p>
    <p>
        <label>
            <input type="text" name="bbb" id="bbb" />
        </label>
    </p>
</form>
<script type="text/javascript">
    
    function setValue() {
    
        document.getElementById('bbb').value = "valor 1";
    }
</script>
javascript html
1个回答
0
投票

你只要做一个计数器就可以了。

var valor = 0;

function setValue() {
  valor++;
  document.getElementById('bbb').value = "valor " + valor;
}
<form id="form1" name="form1" method="post">
    <p>
        <input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
    </p>
    <p>
        <label>
            <input type="text" name="bbb" id="bbb" />
        </label>
    </p>
</form>

0
投票

这是两种解决方案,一种是随机插入值,另一种是按顺序插入。它们都能完美地工作。

http:/jsfiddle.net62wLqz371

<form id="form1" name="form1" method="post">
    <p>
        <input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
    </p>
    <p>
        <label>
            <input type="text" name="bbb" id="bbb" />
        </label>
    </p>
</form>
<script type="text/javascript">
const myValues = ['Decoration', 'Health', 'Fun', 'Yesterday 4'];

function setValue() {
  const randomNum = Math.floor(Math.random() * myValues.length); ;
    document.getElementById('bbb').value = myValues[randomNum];
}
</script

http:/jsfiddle.net7bpaL5hy

<form id="form1" name="form1" method="post">
    <p>
        <input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
    </p>
    <p>
        <label>
            <input type="text" name="bbb" id="bbb" />
        </label>
    </p>
</form>
<script type="text/javascript">
const myValues = ['Decoration', 'Health', 'Fun', 'Yesterday 4'];
let myInd = 0;

function setValue() {
    document.getElementById('bbb').value = myValues[myInd];
    myInd = myInd >= (myValues.length - 1) ? 0 : myInd+1;
}
</script>
© www.soinside.com 2019 - 2024. All rights reserved.