freewheeler
freewheeler

Reputation: 1356

Set input value with JavaScript - depending on value of different input

Hey I got this problem I cannot work out by myself. It's html form which passes data to PHP to send mail.

First, I have dropdown list:

<select id="dropdown" name="dropdown">
    <option selected="true" disabled="disabled">Choose</option>
    <option id="A" value="[email protected]">One</option>
    <option id="B" value="[email protected]">Two</option>
</select>

This dropdown defines the value of next input:

<input type='text' name="to" id="to" value="e-mail"/>

<script>
document.getElementById('dropdown').onchange = function () {
    document.getElementById('to').value = event.target.value  
    }
</script>

At last, I need to define third input from the value of second.

<input type='text' name="from" id="from" value="Office manager"/>

But this last code doesn't work for me:

<script>
var name;
if (document.getElementById('to').value == "[email protected]" {
    name = "Martin";
} else {
    name = "Tom";
}
document.getElementById("from").value = name;
</script>

How do I proceed? JSFiddle

Upvotes: 0

Views: 129

Answers (3)

Siguza
Siguza

Reputation: 23840

  1. Syntax Error.

    if (document.getElementById('to').value == "[email protected]" // No ')'
    
  2. If you use event in your function, you should pass it as an argument.

    document.getElementById('dropdown').onchange = function (event /* <-------- HERE */) {
        document.getElementById('to').value = event.target.value  
    }
    

    By not declaring it, you're using window.event, which might work in some browsers, but it's bad practise.

Upvotes: 1

bernland
bernland

Reputation: 688

Check out the solution at: http://jsfiddle.net/jam7m5ca/1/

You forgot to pass the parameter event.

document.getElementById('dropdown').onchange = function (event) {
    document.getElementById('to').value = event.target.value;
};

Upvotes: 0

Riddler
Riddler

Reputation: 576

It does if you put it like this

http://jsfiddle.net/170x1xs9/

document.getElementById('dropdown').onchange = function () {
    document.getElementById('to').value = event.target.value

    var name;
    if (document.getElementById('to').value == "[email protected]") {
        name = "Martin";
    } else {
        name = "Tom";
    }
    document.getElementById("from").value = name;
    }

Upvotes: 1

Related Questions