Click here to Skip to main content
15,900,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to clear items in select tag,
I am trying to clear items before adding new adding new item, so the old items dont show up only the new items,

Using this code,
document.getElementById("myDivResultSelect").options.length = 0;

It removes all items, but we say for ex,

if i onClick, First show items,

Items1
========
2014-12-12 20:00
2014-12-12 21:00
2014-12-12 22:00
2014-12-12 23:00
========

Second time onClick i dont wont to show that Items1 i want to delete them and on next round display new Items2

Items2
========
2014-12-13 20:00
2014-12-13 21:00
2014-12-13 22:00
2014-12-13 23:00


JavaScript
for (var j = 0; j < bookedFreeTimes.length; j++) {
                free = bookedFreeTimes[j];
                var array = new Array(free);
               

                var myDivRem = document.getElementById("myDivResultSelect");

                var lengths = myDivRem.options.length;
                for (var ms = 0; ms < lengths; ms++) {
                    myDivRem.options[ms] = null;
                }
                while (myDivRem.hasChildNodes()) {
                    myDivRem.removeChild(myDiv.firstChild);
                }
               
                for (var k = 0; k < array.length; k++) {
                   
                    var option = document.createElement("option");
                        option.text = array[k];
                        option.value = array[k];
                        myDiv.appendChild(option);
                    

                }

                }

========


UPDATE
==================
C#
var free = "";
          for (var j = 0; j < bookedFreeTimes.length; j++) {
              free = bookedFreeTimes[j];
              var array = new Array(free);

              var select = document.getElementById("myDivResultSelect");
              var lengths = select.options.length;
              if (lengths > 0) {
                  for (i = 0; i < length; i++) {
                      select.options[i] = null;
                  }

              } else {
                  for (var k = 0; k < array.length; k++) {

                      var option = document.createElement("option");
                      option.text = array[k];
                      option.value = array[k];
                      myDiv.appendChild(option);


                  }
              }



              }


UPDATE
==
My App.js file

JavaScript
var mili;
var increase = 0;
function addNewDateFrom() {
    getListCalender = document.getElementById('CalenderListDrop').value;
    spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
    context = new SP.ClientContext.get_current();
    parentContext = new SP.AppContextSite(context, spHostUrl);
    web = parentContext.get_web();
    list = web.get_lists().getByTitle(getListCalender);
    context.load(list);

    var fromDate08 = "T08:00:00Z"; // Geting time between 8-17 from an sharepoint list
    var toDate17 = "T17:00:00Z";
    var listItemCustom = document.getElementById('datepicker').value;
    var listItemFromTime = document.getElementById('timepicker').value;
    var listItemtoDate = document.getElementById('datepickerto').value;
    var listItemToTime = document.getElementById('timepickerTo').value;
    var result = listItemCustom + "T" + listItemFromTime + ":00" + "Z";
    var result2 = listItemtoDate + "T" + listItemToTime + ":00" + "Z";
    fromTime = new Date(result);
    toTime = new Date(result2);
    mili = toTime - fromTime;
    fromTime.setDate(fromTime.getDate());
    fromTimeConverted = fromTime.toJSON().split('T')[0] + fromDate08;
    increase = increase + 1;
    toTime.setDate(toTime.getDate() + increase);
  
    if (toTime.getDay() == 6) { //Saturday
        toTime.setDate(toTime.getDate() + 2);
        increase = increase + 2;}
    else  if (toTime.getDay() == 0) { //Sunday
         toTime.setDate(toTime.getDate() + 1);
         increase = increase + 1;
     }

    toTimeConverted = toTime.toJSON().split('T')[0] + toDate17;
    var camlQuery = new SP.CamlQuery('<View><Query><Where><And><Geq><FieldRef Name=\'EventDate\' /><Value IncludeTimeValue=\'TRUE\' Type=\'DateTime\'>' + fromTimeConverted + '</Value></Geq><Leq><FieldRef Name=\'EndDate\' /><Value IncludeTimeValue=\'TRUE\' Type=\'DateTime\'>' + toTimeConverted + '</Value></Leq></And></Where></Query></View>');
    camlQuery.set_viewXml();
    collListItem = list.getItems(camlQuery);
    context.load(collListItem);
    context.executeQueryAsync(onQuerySucceededaddNewDateFrom, onQueryFailedaddNewDateFrom);
}
function onQuerySucceededaddNewDateFrom() {
    var myDiv = document.getElementById("myDivResultSelect");
    var length = myDiv.options.length;
    for (var m = 0; m < length; m++) {myDiv.options[m] = null;}
    while (myDiv.hasChildNodes()) {myDiv.removeChild(myDiv.firstChild);}
    var dtstartCon = new Date(fromTimeConverted);
    var dtEndCon = new Date(toTimeConverted);
    var convertUtctoFromtime = new Date(dtstartCon.getTime() + dtstartCon.getTimezoneOffset() * 60 * 1000);
    var start = new Date(convertUtctoFromtime);
    var convertUtcToTime = new Date(dtEndCon.getTime() + dtEndCon.getTimezoneOffset() * 60 * 1000);
    var end = new Date(convertUtcToTime);
    var listItemEnumerator = collListItem.getEnumerator();
    var bookedTimes = [];
    var bookedFreeTimes = [];

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var eventDate = new Date(oListItem.get_item('EventDate'));
        var endDate = new Date(oListItem.get_item('EndDate'));
        bookedTimes.push([eventDate, endDate]);
    }
 while (start.getTime() < end.getTime()) {
        var timeFree = true;
        var firstnewDate = (start.setTime(start.getTime()));
        var firstNewDt = new Date(firstnewDate);
        var newDate = start.setTime(start.getTime() + mili);
        start = new Date(newDate);
        for (var i = 0; i < bookedTimes.length; i++) {
            var time = bookedTimes[i][0];
            var time2 = bookedTimes[i][1];
            if (firstNewDt.getTime() != time.getTime() && start.getTime() != time2.getTime()) {
            } else {
                bookedTimes.splice(i, 1);
                timeFree = false;
                break;
            }
        }

        if (timeFree) {
            var from = new Date(firstNewDt);
            var to = new Date(start);
            var day = from.getDate();
            if (from.getHours() <= 16 && from.getMinutes() <= 30 && from.getHours() >= 8 && !(from.getDay() == 0 || from.getDay() == 6)) {
                if (day <= 9) {day = "0" + day;}
                var month = from.getMonth() + 1;
                if (month <= 9) { month = "0" + month;}
                var year = from.getFullYear();
                var hours = from.getHours();
                if (hours < 10) {hours = "0" + hours;}
                var minutes = from.getMinutes();
                if (minutes < 30) {minutes = "0" + minutes;}
                var dayto = to.getDate();
                if (dayto <= 9) {dayto = "0" + dayto;}
                var monthto = to.getMonth() + 1;
                if (monthto <= 9) {monthto = "0" + monthto;}
                var yearto = to.getFullYear();
                var hoursto = to.getHours();
                if (hoursto < 10) { hoursto = "0" + hoursto;}
                var minutesto = to.getMinutes();
                if (minutesto < 30) {minutesto = "0" + minutesto;}
                bookedFreeTimes.push(year + "-" + month + "-" + day + " " + hours + ":" + minutes + " , " + yearto + "-" + monthto + "-" + dayto + " " + hoursto + ":" + minutesto);        

            }
        }
    }
    $(function() {
            $("#dialog").dialog({
                autoOpen: false,
                modal: true,
                width: 400,
                height: 400,

            });


            $("#dialog").dialog("open");
            var free = "";
            for (var j = 0; j < bookedFreeTimes.length; j++) {
                free = bookedFreeTimes[j];
                var array = new Array(free);

                var select = document.getElementById("myDivResultSelect");
                var lengths = select.options.length;
                if (lengths > 0) {
                    for (i = 0; i < length; i++) {
                        select.options[i] = null;
                    }

                } else {
                   
                    for (var k = 0; k < array.length; k++) {

                        var option = document.createElement("option");
                        option.text = array[k];
                        option.value = array[k];
                        myDiv.appendChild(option);


                    }
                }
              
                

                }


        }

    );
   
}

function onQueryFailedaddNewDateFrom(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


My Default aspx.

ASP.NET
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <p id="message">
        <!-- The following content will be replaced with the user name when you run the app - see App.js -->
        initializing...
    </p>
    <div id="content">
        <h2>Boka möte</h2>
        <br />
        Välj Kalender
        <br />
        <select id="CalenderListDrop">
        </select>
        <br />
        Rubrik
        <br />
        <input type="text" name="txtTitle" id="Textrubrik" />
        <br />
        Starttid<br />
        <input type="text" size="10" readonly="readonly" id="datepicker" /><input type="text" readonly="readonly" size="8" id="timepicker" />
        <br />
        Sluttid<br />
       <input type="text" size="10" readonly="readonly" id="datepickerto" /><input type="text" readonly="readonly" size="8" id="timepickerTo" />
        <br />
        Beskrivning<br />
        <textarea name="txtTitle" id="Textbeskrivning" cols="40" rows="5"></textarea>
        <br />
        <br />
        <br />
         <button onclick="createItem();return false;">Boka tid</button><br /><br /> <div id="freetime">Lediga tider idag</div>
          <select id="LedigTiderDrop">
        </select>
           
        <div id="dialog">
            <div id="bokningupptagentext"></div>
		<div id="textresultfree"></div>
       
            <select id="myDivResultSelect">
        </select>
            <br/>
          
            <div id="buttonResultPlus"></div><div id="buttonResultMinus"></div>
           
             <br/>
        <div id="buttonResultpopup"></div>
	</div>
    <div id="dialogBokninggenomford">
      <div id="text"></div>  

    </div>
   </div>
    

</asp:Content>
Posted
Updated 12-Dec-14 1:44am
v5
Comments
Thanks7872 12-Dec-14 6:09am    
So? Once you clear items,bind option with new values. Whats issue here?
Kurac1 12-Dec-14 6:36am    
The problem is that i only get 2014-12-13 20:00 on Items2 and not the other items
Kurac1 12-Dec-14 6:41am    
The problem is that it also deleted all items, and not just the ones that i want
Kurac1 12-Dec-14 6:44am    
i will update my code, i dont now how i could break so it don't removes after deleting Items1

Quote:
You can use the following to clear all the elements. Note that

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
select.options[i] = null;
}
 
Share this answer
 
Comments
Kurac1 12-Dec-14 7:02am    
i already have that snippet in my code.
ShortProgrammer 12-Dec-14 7:09am    
var length = select.options.length;
if(length>0)
{
for (i = 0; i < length; i++)
{
select.options[i] = null;
}

}
else{ your code for add item again.}
for (var k = 0; k < array.length; k++) {

var option = document.createElement("option");
option.text = array[k];
option.value = array[k];
myDiv.appendChild(option);


}
ShortProgrammer 12-Dec-14 7:11am    
while you adding new item ,before add you make condition and check if its have item or not..if have then clear its. and after clear recall your method which add the item..
you got its??
Kurac1 12-Dec-14 7:14am    
It does the same only 1 value get displayed , should be more dates
Kurac1 12-Dec-14 7:19am    
i will update in the top what i have done.
Quote:
jQuery

var list = $("#selectList");
$.each(items, function(index, item) {
list.append(new Option(item.text, item.value));
});
pure javascript

var list = document.getElementById("selectList");
for(var i in items) {
list.add(new Option(items[i].text, items[i].value));
}
 
Share this answer
 
Comments
Kurac1 12-Dec-14 9:53am    
Its not working
From what I can see it appears as though the for logic on the bookedFreeTimes is not working as expected.
JavaScript
//populate dummy data 
    var bookedFreeTimes = [];
    bookedFreeTimes.push('data 001');
    bookedFreeTimes.push('data 002');
    bookedFreeTimes.push('data 003');
    bookedFreeTimes.push('data 004');
    bookedFreeTimes.push('data 005');


    var myDiv = document.getElementById("myDivResultSelect");
    var lengths;

//put the remove option logic here outside of the for loop
//not sure if removing the options works, didn't remove all in fiddle
/*
    lengths = myDiv.options.length;
    if (lengths > 0) {
        for (i = 0; i < lengths; i++) {
            myDiv.options[i] = null;
        }
    }
*/
//jQuery method of removing option from select
    $('#myDivResultSelect option').detach();

//modified for logic
    lengths = bookedFreeTimes.length;
    for (var j = 0; j < lengths; j++) {
        var option = document.createElement("option");
        option.text = bookedFreeTimes[j];
        option.value = bookedFreeTimes[j];
        myDiv.appendChild(option);
    }

created a fiddle here: http://jsfiddle.net/0f2nvse3/[^]
 
Share this answer
 
Comments
Kurac1 15-Dec-14 2:19am    
hi, i need first to remove the items, and to find out the items i have i need first to have an for loop that finds the items, and then delete them, and after deleting them i want to create new ones. My problem is that my new items that i create are aldready created before i am trying to delete all my items, so my new items also gets deleted, thats why it dont display the new items.
jaket-cp 15-Dec-14 4:15am    
Have you tried out my solution?
And is it doing what you are expecting?

What your bookedFreeTimes 'for loop' is doing is looping through the values stored in bookedFreeTimes.
For each item in bookedFreeTimes an if check is performed to find number of items/options within the select, if exist then remove them otherwise add the bookedFreeTimes item to the select.
So in this case:
First item in bookedFreeTimes is not added to the select as select has items/options and so the items/options are removed from the select.
Second item in bookedFreeTimes is added as select item/option.
Third item in bookedFreeTimes is not added to the select as select has items/options and so the items/options are removed from the select.
Four item in bookedFreeTimes is added as select item/option.
And so on until all the items in bookedFreeTimes are looped through.

Also within the loop code, I believe variables are mis-named.
var select = document.getElementById("myDivResultSelect");
But myDiv.appendChild(option); used later to add to the var select.
Another one var lengths = select.options.length;, but length without (s) used in for (i = 0; i < length; i++) {

Hope that helps out.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900