Solved

need a javascript to move comma separated strings from textbox to listbox

Posted on 2008-10-20
20
822 Views
Last Modified: 2013-12-17
I have a webform with a text box and a listbox  and these buttons  >> ,Delete

The user will enter comma separated strings like 123,abc,345, etc and click >> button . the javascript code should have to move those strings from textbox to the listbox like this

123
abc
345

and also if they select a list item and click delete , it should remove it from the listbox.

Could you please help me on this. If you have some javascript code for this please forward me that. i tried with server side code and since the page is loading each time, the user doesn't like this , so iam looking for a javascript for this functionality, I would appreciate  your help.
0
Comment
Question by:gladstonesheeba
  • 8
  • 6
  • 4
  • +1
20 Comments
 
LVL 16

Expert Comment

by:sh0e
ID: 22759356

<script type="text/javascript">

function updateListBox(text_id, listbox_id){

var arrInput = document.getElementById(text_id).value.split(',');

for(var i=0;i<arrInput.length;i++)

	document.getElementById(listbox_id).innerHTML += "<option>"+arrInput[i]+"</option>";

}

</script>
 

<form>

<input type="text" id="mytext"></input>

<select id="mylistbox">

<option>woot</option>

</select>

<input type="button" onClick="updateListBox('mytext', 'mylistbox');" value="update 
 

listbox"></input>

</form>

Open in new window

0
 
LVL 8

Expert Comment

by:MatthiasVance
ID: 22759412
This also adds a delete button.

Kind regards,

Matthias Vance
<script language="JavaScript">

	function addValues() {

		var lstItems = document.getElementById("lstItems");

		var txtValues = document.getElementById("txtValues");

		var values = txtValues.value.split(",");

		for(var i = 0; i < values.length; i++) {

			var option = document.createElement("OPTION");

			option.setAttribute('value', values[i]);

			var txt = document.createTextNode(values[i]);

			option.appendChild(txt);

			lstItems.appendChild(option);

		}

		txtValues.value = "";

	}
 

	function deleteItem() {

		var lstItems = document.getElementById("lstItems");

		var selectedValue = lstItems.value;

		for(var i = 0; i < lstItems.children.length; i++) {

			var element = lstItems.children[i];

			if(element.value == selectedValue) {

				lstItems.remove(element);

			}

		}

	}

</script>

<form onsubmit="return false;">

<input type="text" id="txtValues" /><br />

<input type="submit" onclick="addValues();" value="Submit">

</form>

<select size="2" style="width: 140;" id="lstItems">

	<option value="1">1</option>

	<option value="2">2</option>

</select>

<br />

<button onclick="deleteItem();">Delete item</button>

Open in new window

0
 

Author Comment

by:gladstonesheeba
ID: 22760830
Iam getting this error 'value' is null or not an object. Here's the code

 function addValues() {
                var lstItems = document.getElementsByName("ItemNumberslist");
                var txtValues = document.getElementsByName("txtproductnos");
                var values = txtValues.value.split(',');
                for(var i = 0; i < values.length; i++) {
                        var option = document.createElement("OPTION");
                        option.setAttribute(values[i], values[i]);
                        var txt = document.createTextNode(values[i]);
                        option.appendChild(txt);
                        lstItems.appendChild(option);
                }
                txtValues.value = "";
        }


 <asp:TextBox ID="txtproductnos" runat="server"></asp:TextBox>
                       
                        <button id="btnmove" value=">>" width="53px" onclick="addValues();"></button>
                          <asp:Button ID="btndelete" runat="server" Height="26px" Text="Delete" />
                        <asp:Button ID="importbutton" runat="server" Text="Import" />
                        <asp:ListBox ID="ItemNumberslist" runat="server" Width="199px"></asp:ListBox>
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22761453
I have only taken a cursory look at your code and the solutions provided, but you may be able to fix your errors by changing these two lines:

    var lstItems = document.getElementsByName("ItemNumberslist");
    var txtValues = document.getElementsByName("txtproductnos");

to

    var lstItems = document.getElementById("ItemNumberslist");
    var txtValues = document.getElementById("txtproductnos");

For one, your textboxes have ID attributes set, not name attributes. Moreover, getElementsByName() returns an array and not a DOM element.
0
 

Author Comment

by:gladstonesheeba
ID: 22761591
I tired getting document.getelementbyid('....') . but still that was giving errors, that's why i tried getting the name.  the id attributes are all set, but its not recognizing the controls. its just giving me null , null is null or not an object. This is the error iam getting.
Please help me on this.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22761598
Can you provide us with a complete View Source listing from the browser?
0
 

Author Comment

by:gladstonesheeba
ID: 22761763
Here i attached a word document with details
asp.doc
0
 
LVL 8

Expert Comment

by:MatthiasVance
ID: 22761875
From a quick look, I see you are still using a modified version of my deleteItem() method. You *have* to use document.getElementById() instead of document.getElementsByName().

Try to copy and paste the methods and see if that works out.

Kind regards,

Matthias Vance
0
 

Author Comment

by:gladstonesheeba
ID: 22761921
if i use the html control <select/> , then its working fine , but if i use the server side control <asp:Listbox/> then its giving me the error "null", null is null or not an object. I want to use the server asp.net listbox not the html select box. what should we do for this.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762124
What I wanted to see was what the code looked like to someone else visiting your site. They probably wouldn't see the <asp:ListBox> tag, I don't think.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:gladstonesheeba
ID: 22762322
  <asp:Label ID="item" runat="server" Text="Enter Item Number(s)"></asp:Label><br />
                       <asp:Label ID="lblinvalid" runat="server" Text="" ForeColor="Red"></asp:Label><br />
                        <input type="text" id="txtproductnos" />
                        <br />
                       <button id="btnmove" onclick="javascript:addValues();" style="width:53px;">>></button>                        <asp:Button ID="btndelete" runat="server" Height="26px" Text="Delete" />
                        <asp:Button ID="importbutton" runat="server" Text="Import" />
               
                    <asp:ListBox ID="itemnos" runat="server"></asp:ListBox>

They'll  see the listbox  on the webpage
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762369
No, I understand that is your code that is run on the server, but it must be rendered using a <select> tag in the final product when a user views your webpage by going to page.asp, for example. That source will help, because then we can do our own tests and see what is going on.
0
 

Author Comment

by:gladstonesheeba
ID: 22762480
nO I NEED TO RETRIEVE THE LIST ITEMS FROM THE CODE BEHIND.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22762498
I understand, but the Javascript only operates on the rendered HTML, which would be a <select> element. It would be much easier to figure out what is wrong if we can see this HTML code, since clearly your <asp:ListBox> id is being ignored.
0
 

Author Comment

by:gladstonesheeba
ID: 22763893
is there anyway i can use the server side control for this, because the user will either enter the numbers through textbox or import it from excel sheet. for importing it from the excel sheet to the listbox , i need to have the server side code. but for textbox to listbox i prefer javascript and so does the user, because the doesn't like the page reloading every time. please help me to find a solution for this.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 22764032
There's no problem, as far as I can tell, with using the server-side control, but it would be easier for me to test if I had the HTML output from the server-side control. When a user visits your site, your server parses your page and replaces the ASP server-side controls with equivalent HTML, then sends it to the user. The user's browser can't parse server-side controls; it only parses the HTML.
0
 
LVL 16

Expert Comment

by:sh0e
ID: 22764290
You need to add code in your *.asp.cs file to bind the delete button to the delete function, and to add in the generated id of the listbox control (listbox.ClientID).
Eg:
(assuming you use
 <asp:Button ID="btnmove" runat="server" Height="26px" Text=">>" />
 <asp:Button ID="btndelete" runat="server" Height="26px" Text="Delete" /> )
btndelete.attributes.Add("onClick", "deleteItem("+itemnos.ClientID+")");
btnmove.attributes.Add("onClick", "addValues("+itemnos.ClientID+")");

When using master pages, the id of the listbox is prepended with the Control Place ID separated by _: (Ct001_ControlPlaceHolder_ListBox)
Which is why the JavaScript returns null when looking for the listbox.  listbox.ClientID holds this generated ID.

Rewrote the JavaScript functions.
It will automatically use the select id based on your current html if you do not give it a selectid, as well as a working deleteItem():
<script type="text/javascript">

        function addValues(selectid) 

        {

			if(typeof selectid == 'undefined')

				selectid="ctl00_BodyContent_itemnos"

            var arrInput = document.getElementById('txtproductnos').value.split(',');

			var x=document.getElementById(selectid);

			for(var i=0;i<arrInput.length;i++)

			{

				var y=document.createElement('option');

				y.text=arrInput[i];

				try{x.add(y,null);}

				catch(e){x.add(y);} // IE

			}

        }
 

		function deleteItem(selectid)

		{

			if(typeof selectid == 'undefined')

				selectid="ctl00_BodyContent_itemnos"

			var x=document.getElementById(selectid);

			x.remove(x.selectedIndex);

		}

</script> 

Open in new window

0
 
LVL 16

Expert Comment

by:sh0e
ID: 22764310
Sorry, made a typo, Attributes should be capitalized.
btndelete.Attributes.Add("onClick", "deleteItem("+itemnos.ClientID+")");
btnmove.Attributes.Add("onClick", "addValues("+itemnos.ClientID+")");
0
 

Author Comment

by:gladstonesheeba
ID: 22767006
Still its not working , the page refreshes and then nothing happens, no items are added to the listbox.
0
 
LVL 16

Accepted Solution

by:
sh0e earned 500 total points
ID: 22771180
It's not supposed to be refreshing.  Do you have a form that is submitting?
You are supposed to click the ">>" button, not the submit button to test this.

Can you also give me the details after trying the code?
If it's possible can I see the source of each part, so I could help better?

Below is code that will search for your listbox, alert it, then modify it.
If you can give the output of this code it would help.
<script type="text/javascript">

function findItemNos(){

  var selects = document.getElementsByTagName('select');

  for(var i=0;i<selects.length;i++)

    if(selects[i].id.search(/itemnos/i) != -1) return selects[i];

}

        function addValues(selectid) 

        {

                        x=findItemNos();

                        alert(x.id);

            var arrInput = document.getElementById('txtproductnos').value.split(',');

                        for(var i=0;i<arrInput.length;i++)

                        {

                                var y=document.createElement('option');

                                y.text=arrInput[i];

                                try{x.add(y,null);}

                                catch(e){x.add(y);} // IE

                        }

        }

 

                function deleteItem(selectid)

                {

                        x=findItemNos();

                        alert(x.id);

                        x.remove(x.selectedIndex);

                }

</script> 

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now