开发者

Jquery add values from dropdown to text input

开发者 https://www.devze.com 2023-03-10 06:56 出处:网络
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 val

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"开发者_StackOverflow中文版 />

I'm getting skill.join is not a function


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


I think this is what you require Demo

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号