Jcdevelopment
Jcdevelopment

Reputation: 51

changing text input from dropdown does not update selected div

I have an text input that automatically changes the text in a div using keyup. The issue is, the user also needs to be able to select an option from a dropdown and have that update as well.

example: http://jsfiddle.net/jcdevelopment/w3tu5/18/

I use the following to update the div with no issue, yet when a dropdown is selected, nothing changes. Any suggestions?

$('#name').keyup(function () {
            $('._name').text($('#name').val());
        });

Upvotes: 2

Views: 817

Answers (4)

Shaunak D
Shaunak D

Reputation: 20646

Demo

Check this code, you need to change text of ._name too,

For input text,

$('#name').keyup(function () {
    $('._name').text($(this).val());
});

And for <select>

$('.drop').change(function () {
     $('._name').text($(this).val());
     $('#name').val($(this).val());
});

Side Note : Use $(this) to get the context of the current element, instead of using a selector repeatedly.

Upvotes: 1

Sid M
Sid M

Reputation: 4364

Is this what you are looking for fiddle

 $('.drop').change(function () {
            $('._name').text($('.drop').val());
            $('#name').val($('.drop').val());
        });

Upvotes: 2

manji
manji

Reputation: 47968

Changing the value of the input does fire the keyup event.

You just need to fire it yourself:

$('.drop').change(function () {
    $('#name').val($('.drop').val());
    $('#name').keyup();
});

or create a function that updates the label content:

function updateLabel(){
    $('._name').text($('#name').val());
}

and call it from the keyup event handler and the drop down change event handler:

$('#name').keyup(function () {
    updateLabel();
});

$('.drop').change(function () {
    $('#name').val($('.drop').val());
    updateLabel();
});

Upvotes: 0

martynas
martynas

Reputation: 12290

There are a couple ways to approach this. Here's one:

$('#name').keyup(function () {            
    $('._name').text($('#name').val());
    $('.drop option[value="' + $(this).val() + '"]').prop("selected", true);
});

DEMO

Upvotes: 0

Related Questions