开发者

Storing selected row in array in JavaScript

How do we sto开发者_JAVA百科r selected row in array in JavaScript?


You shoud be more specific in what kind of object youre using in your html (DOM) code.

exampl: if you're using a SELECT 'resources' in a form

var fl = form.resources.length -1;

//Pull selected resources and add them to list
for (fl; fl > -1; fl--) {
   if (form.resources.options[fl].selected) {
    theText  = form.resources.options[fl].text;
        theValue = form.resources.options[fl].value);

        //your code to store in an aray goes here
        //...
   }

}


If I got it you want to store selected table rows using javaScript. If yes, this may help. This piece of code is to accumulate selected ID's (dataId), based on selection of selected row's id(elemId), in an input (hidId). I have modified my original code to maintain the records in an Array as well.

function checkSelection(hidId,elemId,dataId)
{
    var arr =
    str = '_' + dataId + '_';
    hid = document.getElementById(hidId);
    row = document.getElementById(elemId);
    if(!row.classList.contains("selected")) {
        row.classList.add("selected");
        if(!hid.value.toString().includes(str)) {
            hid.value = hid.value + str;
        }
        if(arr.includes(dataId))
            arr.push(dataId);
    }
    else {
        row.classList.remove("selected");
        if(hid.value.toString().includes(str))
            hid.value = hid.value.replace(str,"");
        if(!arr.indexOf(dataId)==-1)
            delete arr[arr.indexOf(dataId)];
    }
    alert(arr.toString());
}[I have tested it][1]

to focus more on the Array() a basic solution would be as below:

function checkSelect(hidId,elemId,dataId)
{
    row = document.getElementById(elemId);
    str = "";
    if(document.getElementById(hidId).getAttribute("value")!=null)
        str =   str+document.getElementById(hidId).getAttribute("value");
    str= str.replace('[','')
        .replace(']','')
        .replace('"','')
        .replace('\\','');
    document.getElementById(hidId).setAttribute("value",str);
    alert(document.getElementById(hidId).value);
    var arr = new Array();
    if(document.getElementById(hidId).value.length!=0 ) {
        arr=document.getElementById(hidId).value.split(',');
    }
    if(!row.classList.contains("selected")) {
        row.classList.add("selected");
        if(!arr.includes(dataId.toString())) {
            arr.push(dataId.toString());
        }
    }
    else {
        row.classList.remove("selected");
        if(arr.includes(dataId.toString()))
        {
             delete dataId.toString();
            arr.splice(arr.indexOf(dataId.toString()),1)
        }
    }
    if(arr.length>0) {
        document.getElementById(hidId).setAttribute("value", arr.toString());
    }
    else
        document.getElementById(hidId).setAttribute("value", "");
}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜