Button to update the text in a search field but entering several values in sequence?

Asked

Viewed 24 times

-1

With this code we can send a single value to the search field. Now, taking this example, how do we insert more values in sequence with the same button, for example: value 1, health, fun, yesterday 5, etc.

Note that the values cannot be equal and it is also necessary that the previous value is erased and the new appears; that is, when clicking Value 1 should give rise to health, health should give place to fun and so on.

http://jsfiddle.net/g506bxL4/1/

<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>

1 answer

0


You can keep the state in a list of values already added. Then every click you add an element to that list and update the field information.

<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">

    let values = [];


    function setValue() {
        let newValue = values.length + 1;
        values.push(`valor ${newValue}`);
        document.getElementById('bbb').value = values.join(', ');
    }
</script>

See that in function setValue()we took values.length + 1. This is to calculate the next number.

After that we add to the array values and then update the field value.

  • I’m not getting any results, maybe someone can change the code in http://jsfiddle.net/g506bxL4/1/, just change and save to get a new page and address.

  • Attention, it is necessary that the previous value is deleted and the new one appears; that is, when you click the value1 must give place to the value2 and so on. Maybe someone can change the code to http://jsfiddle.net/g506bxL4/1/, just change and save to get a new page and address.

  • And the values cannot be equal, for example Value 1, health, fun, yesterday 5... and it is also necessary that the previous value is erased and the new appears; that is, when clicking Value 1 should give way to health 2, health should give place to fun, and so on.

  • You can take this example and apply your need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.