0

I'm having trouble trying to accomplishing this.. Whatever option I select from a dropdown list named programs_dropdown I want to add to a text field named programs_input and separate the options values by a comma.

e.g. php, jquery, html

Below the dropdown list I have an add div. On click, it should add what I selected from the dropdown to the text field.

$(document).ready(function(){
    $('#add').click(function() {
        var programs = $("#programs_dropdown").val(); //get value of selected option
        $('#programs_input').val(programs.join(',')); //add to text input
    }); 
});

HTML

<select name="programs_dropdown" id="programs_dropdown">
<option value="php">php</option>
<option value="jquery">jquery</option>
<option value="html" selected="selected">HTML</option>
</select>

<div id=add">Add</div>

<input type="text" name="programs_input" id="programs_input" />

I'm getting skill.join is not a function

2 Answers 2

1

The select has to multi option if you want to select multiple. Change it to

<select name="programs_dropdown" id="programs_dropdown" multiple>

Then it would start working.

Demo

EDIT:

$(document).ready(function(){
    $('#add').click(function() {
        var program = $("#programs_dropdown").val(); //get value of selected option
        var programs = $('#programs_input').val().split(",");
        if (programs[0] == "") {
            programs.pop()
        }

        if ($.inArray(program, programs) == -1) {
            programs.push(program);
        }

        $('#programs_input').val(programs.join(',')); //add to text input
    });
});

DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the demo but I need it to be a dropdown. I want to add values one by one via add div depending what I have selected.
btw, what does the -1 in the second statement mean? I am trying to learn the code and can't figure that out.
It is checking for the presence of program in programs array. Unfortunately the inArray doesn't return bool (as expected) but returns index of the element found and -1 if the element is not found. api.jquery.com/jQuery.inArray
That makes sense! Thank you :) The script you provided is brilliant, I also learned a lot by studying it.
1

I think this is what you require Demo

2 Comments

There is a bug in it. Try clicking the Add more than once while the same option is selected.
Do you want unique items in textbox? If yes, here's the updated [Demo] jsfiddle.net/ba7Wn/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.