Getting values from an HTMLCollection to a string

旧巷老猫 提交于 2019-12-06 13:09:16

When you join the array, it is calling the "toString" of each element. In this case, they are DOM elements and return their type. You can use map first to create a new array of strings containing the value of each option:

http://jsfiddle.net/Lfx6r5sm/

var genres = arr.map(function(el){
    return el.value;
}).join(', ');

You could iterate through the selected items like so:

<script type="text/javascript">
function newComic(){
    var elem = document.querySelector("#genreList").selectedOptions;
    var arr = [];
    for(var x=0; x<elem.length; x++){
        // for the TEXT value
        //arr.push(elem[x].text);

        // for the value
        arr.push(elem[x].value);
    }
    var genres = arr.join(', ');
    window.alert(genres);
}
</script>
meteor

You need to iterate through HTMLCollection like this

<script>
    function newComic()
    {
       var elem = document.querySelector("#genreList").selectedOptions;
       console.log(elem);
       for (var i = 0; i < elem.length; i++) {
           console.log(elem[i].attributes[0].nodeValue); //second console output
       }
    }
</script>

I think jquery is best suited for this task.

HTML

<select id="genreList" multiple="multiple" name="addGenre[]"  style="width: 150px;font-size: 10pt;">
            <option value="Action">Action</option>
            <option value="Comedy">Comedy</option>
            <option value="Fantasy">Fantasy</option>
            <option value="Horror">Horror</option>
            <option value="Mystery">Mystery</option>
            <option value="Non-Fiction">Non-Fiction</option>
            <option value="Period">Period</option>
            <option value="Romance">Romance</option>
            <option value="Sci-Fi">Sci-Fi</option>
            <option value="Thriller">Thriller</option>
</select>

<p><input type="button" value="Add Comic" id="btnAddComic" style="font-size: 10pt; width: 150px; height:40px;"></p>

jQuery

$("#btnAddComic").click(function(){
    var inz = $( "#genreList option:selected" ).map(function(){
        return $(this).text();
    }).get().join(',');
    alert(inz);
});

SEE THE FIDDLE

http://jsfiddle.net/inzamamtahir/1bm45gu7/2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!