Charlie
Charlie

Reputation: 15

Using a select option to populate input box with JQuery

I am getting a little frustrated and I know I have probably ballsed my code up but here goes.

I have a select dropdown that populates it's options with user id's, the select dropdown has a default value which I am trying to not use in the query.

I then want a chosen select option to populate a hidden text input with the selected user id from the option value.

So the code is detecting a change on the select, then it is saying if not default then copy value (user id) into the desired text input.

Here is my messy attempt at the jquery code, sorry for probably making a lot of mistakes with it.

jQuery(document).ready(function($){
    $('.client-select').on('change',function(event){
        if $('.client-select').val($(this) =! "default"){
            $('.clientuserid').val($(this).find('option:selected').value());
        }
    });
});

Any help with this would be greatly appreciated.

Many thanks.

Charlie

Upvotes: 1

Views: 3091

Answers (2)

nshah143
nshah143

Reputation: 559

Try below updated javascript code of yours

$(document).ready(function(){
    $('.client-select').on('change',function(){
         if($(this).val() != "default"){
            $('.clientuserid').val($(this).val());
        }else{
            $('.clientuserid').val('');
        }
    });
});

Also here is the working demo fiddle - http://jsfiddle.net/1d9hfrxp/1/ I hope this is what you were looking to achieve.

Upvotes: 2

P. Frank
P. Frank

Reputation: 5745

You have an error on your jquery formating script. You missed () for if function. Please try:

jQuery(document).ready(function($){
    $('.client-select').on('change',function(event){
        if ( $('.client-select').val($(this)) =! "default"){
            $('.clientuserid').val($(this).find('option:selected').val());
        }
    });
});

val() return the value of your dropdown selected element

Upvotes: 0

Related Questions