3

I have a form with a textbox and then another form with three textboxes. The text I enter in the first textbox (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 disappers instead of showing in the others as well... what did I do wrong? Thanks a lot 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>
imbondbaby
  • 6,351
  • 3
  • 21
  • 54
Ollie
  • 542
  • 7
  • 18
  • Dasein gave you a good answer. Also see this post: [ – Yogi May 26 '15 at 22:53

3 Answers3

6

You are experiencing 2 basic errors there:

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

2- you are not assigning properly the sync function to the button

Like this:

button.onclick = function() {sync();return false;}
user2755140
  • 1,917
  • 4
  • 13
  • 16
1

you have some options:

you can set type="button" to your button so it doesn't submit your form, because this reload the full page and you are starting from 0, that is way the text disappears.

you can put your button out of the form tag.

and you are passing the result of sync() to the button.onclick, not the function. So, you can try

button.onclick = sync

happy codding

Castro Roy
  • 7,623
  • 13
  • 63
  • 97
1

First, your JS code is calling the function as it is loaded:

button.onclick = sync();

should be

button.onclick = sync;

(you assign the function code to the event, not the function execution)

Second, when using the button tag inside the form, it seems to be automatically interpreted as a "submit" button. When clicking it, your form is "posted" to nowhere, so the value disappears. Try replacing the button tag with an input tag with type button.

Fiddle for you

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

noderman
  • 1,934
  • 1
  • 20
  • 36