简体   繁体   中英

Select multiple items with javascript / asp.net

This is what I have so far I have a view that displays date that I have not reported a time for.

My idea is to tick the dates I want to report a time, so I can report time for multiple dates, and if I did check a date I do not want to report for I just uncheck that box.

I have that working, (kinda) The problem is if i want to select a date, i'll always have to select the first in the list before I can check any other date.

Like this: 在此处输入图片说明

That works great as long as I always choose the first date in the list.

But that is not what I am looking for, I want the option so I can report any data without having to check the first date first. This would not work because I did not check the first date: 在此处输入图片说明

This is my script:

var dateArr=new Array();
function SetDate(dt) {
   if(document.getElementById("isoDate").checked) {
       if(dateArr.indexOf(dt)<0){ //Check if date is already added. if not add it to array.
          dateArr.push(dt);
    }
    else{
         var index=dateArr.indexOf(dt);
         if (index > -1) {
            dateArr.splice(index, 1);//Remove from array if checkbox uncheck
    }
  }
     $('#date').val(dateArr.join(" ")); //Add space separated string to the #date element.
 }
}

And this is my view where I get the dates:

@foreach (var date in ViewBag.MissingDays)
{
    var isoDate = date.ToString("yyMMdd");
    <div class="col-md-1">
        <input type="checkbox" id="isoDate" name="isoDate" value="@isoDate"onclick="javascript:SetDate('@isoDate');" />
        @isoDate
    </div>
}

There are some observations regarding your code, like is not a good practice to have multiple items with the same id(i could actualy say that is a bad practice, i am talking about the checkboxes, the same name should be enough) or lines like:

if(document.getElementById("isoDate").checked) 

that ruins everything(this i think it is the real source of your problem since the result is the first element and not being checked will step to else)

Seeing that you use jquery, here you have a small sample of how this should look like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM