Search code examples
jqueryexportmultiple-select

jquery export selected options to text area with remove duplicates lines


I create 2 buttons, first button: to export from multiple select field to text-area, second button: to remove duplicate lines from text-area

the export button only works if I have not yet click the remove duplicates button, if I have already clicked the remove duplicates button, when i click export button again, it doesn't works again

function eliminateDuplicates(arr) {
    var i,
    len=arr.length,
    out=[],
    obj={};

    for (i=0;i<len;i++) {
        obj[arr[i]]=0;
    }
    for (i in obj) {
        out.push(i);
    }
    return out;
}
$(document).ready(function(){
    $("#remove-duplicates-button").click(function(){
        $("#text-area").val(eliminateDuplicates($("#text-area").val().split("\n")).join("\n"));
    });
    $("#export-button").click(function(){
        var hotels = [];
        $('#hotels :selected').each(function(i, selected){
            hotels[i] = $(selected).val()+"\n";
        });
        $("#text-area").append(hotels);
    });
});

need help to fix in, this is the demo http://jsfiddle.net/4dtxf/3/

thanks for your help


Solution

  • Use this code instead:

    function eliminateDuplicates(arr) {
        var i,
        len=arr.length,
        out=[],
        obj={};
    
        for (i=0;i<len;i++) {
            obj[arr[i]]=0;
        }
        for (i in obj) {
            out.push(i);
        }
        return out;
    }
    $(document).ready(function(){
        $("#remove-duplicates-button").click(function(){
            $("#text-area").val(eliminateDuplicates($("#text-area").val().split("\n")).join("\n"));
        });
        $("#export-button").click(function(){
            $("#text-area").val("");
            $('#hotels :selected').each(function(i, selected){
                $("#text-area").val($("#text-area").val() + $(selected).val()+"\n");
            });
        });
    });
    

    Always use val() to modify or get content of text area...

    http://jsfiddle.net/4dtxf/14/