Synchronize text boxes (form input)

I have a form with a text box and then another form with three text boxes. The text I entered in the first text box (id = "logoName") should be visible in the other three (ids v1 - v3) when I click the button. I tried the following, but when I click the button, the text in the first box disappears instead of showing in the others, and also ... what did I do wrong? Many thanks for your help.

Js

var logoName = document.getElementById("logoName");
var v1 = document.getElementById("v1");
var v2 = document.getElementById("v2");
var v3 = document.getElementById("v3");
var button = document.getElementById("button");

function sync() {
    v1.value = logoName.value;  
    v2.value = logoName.value;
    v3.value = logoName.value;
}
button.onclick = sync();

      

CSS

p {
        font-size: 2em;
        float: left;
        margin-right: 2em;  
    }
    .clear {
        clear: both;    
    }
    .overview {
        margin-top: 2em;    
    }
    input[type="text"] {
        font-size: 2em; 
        width: 200px;
    }

      

Html

<form>
    <label>Logo-Name</label>
    <input id="logoName" type="text"/>
    <button id="button">synchronise</button>
</form>

<form class="overview">
    <input id="v1" type="text" /> <input id="v2" type="text" /> <input id="v3" type="text" />
</form>

      

+3


source to share


3 answers


You are experiencing two main errors here:

1- you are not preventing the default action of the submit button and

2- you are not assigning the correct function to the sync

button



Like this:

button.onclick = function() {sync();return false;}

      

+6


source


you have several options:

you can set type="button"

on your button so that it doesn't submit your form because that reloads the full page and you start at 0, meaning the text disappears.

you can put your button from form tag.



and you are passing the result sync()

to button.onclick

, not to a function. So you can try

button.onclick = sync

      

happy walking

+1


source


First, your JS code calls the function when it is loaded:

button.onclick = sync();

      

it should be

button.onclick = sync;

      

(you are assigning a function code to an event, not a function execution)

Second, when the tag is used button

inside a form, it appears to be automatically interpreted as a submit button. When you click it, your form "submits" to nowhere, so the value disappears. Try replacing the tag button

tag input

on type

button

.

Screenshot for you

http://jsfiddle.net/tn91aou1/3/

+1


source







All Articles