Question

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

Was it helpful?

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/

OTHER TIPS

Well, it seems like you had some syntax errors there, like missing ; and commas instead of them. UPDATE: and use val instead of append to set textarea value.

function eliminateDuplicates(arr) {
    var i=0;
    var len=arr.length;
    var out=[];
    var 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";
        });
        var h=hotels.toString().replace(/,/g,'');
        $("#text-area").val(h);
    });
});

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top