Make input value depend on `select option` selection

1.9k Views Asked by At

Basically if male is selected, make the input named pronoun have a value of his. Else, make the input named pronoun have a value of her.

<select name="sex">
    <option value="male">Male</option>
    <option value="female">Female</option>
</select>
<input type="text" name="pronoun" value="" placeholder="pronoun" />
5

There are 5 best solutions below

0
On BEST ANSWER

Try

$("select").change(function() {
   if($(this).val() == 'male'){
      $('input[name=pronoun]').val('his')
   }
   else{
      $('input[name=pronoun]').val('her')
    }
});

or

$("select").change(function() {
    $('input[name=pronoun]').val(($(this).val() == 'male') ? 'his' : 'her');
}).change();

Fiddle

0
On

Use jQuery -

var value = $('select[name="sex"]').val() == 'male' ? 'his' : 'her';
$('input[name="pronoun"]').val(value); // Set the value by default

$('select[name="sex"]').on('change', function() {
    if($(this).val() == 'male') {
        $('input[name="pronoun"]').val('his');
    } else {
        $('input[name="pronoun"]').val('her');
    }
})

Check it here

0
On

use change() event

$("select[name=sex]").change(function () {
    $('input[name=pronoun]').val((this.value == 'male') ? "His" : "Her")
});

DEMO

0
On

Html Code :

<select  name="sex" class="test">
  <option value="male">Male</option>
  <option value="female">Female</option>
</select>
<input type="text" name="pronoun" class="pronoun" value="" placeholder="pronoun"/>

Jquery Code :

<script>
$('.test').on('change', function() {
var value =this.value;
    if(value == 'male')
    {
        $('.pronoun').val('his');
    }
    else
    {
        $('.pronoun').val('her');
    }
});
</script>

please check it

0
On

You should assign an id value and use jQuery's selector and event handler to do what you want.

<select id="sex" name="sex">
    <option value="male">Male</option>
    <option value="female">Female</option>
</select>
<input id="pronoun" type="text" name="pronoun" value="" placeholder="pronoun" />

<script>
$('#sex').change(function() {
    $('#pronoun').val($(this).val() == 'female' ? 'her' : 'his');
});
$('#sex').change();
</script>