Avatar of jazz__man
jazz__man
 asked on

How do you add items to a listbox with javascript?

Hi

I have the following code.....

<script language="javascript" type="text/javascript">
    function openbrWindow() {
        var RetVal = window.showModalDialog("Popup/popupFrame.aspx?qs=../Pickers/TestForm.aspx",
        'PopupPage',
        'dialogHeight=300px;dialogWidth=700px,toolbar=no,unadorned=yes,directories=no,status=no,menubar=no,scrollbars=no,resizable=no ,modal=yes',
        '',
        true);

        var LstItems = document.getElementById("<%= lstItems.ClientID %>");



The code up to here works, but the following code is what I am trying to fix...



        //LstItems.add(new Option(RetVal, 1));

        var newOption = document.createElement('option');
        newOption.value = RetVal;
        newOption.innerHTML = RetVal;
        LstItems.appendChild(newOption);

    }
</script>


As you can see, I am trying to add the window return value to a listbox control. The problem is the item displays for a second then disappears from the control.
ASP.NETJavaScript.NET Programming

Avatar of undefined
Last Comment
jazz__man

8/22/2022 - Mon
Gregg

jazz__man,

Were you successful at getting the return value from the modal window?

change newOption.innerHTML to newOption.text. Also consider using the add method you have commented out.

var newOption= document.createElement('option');
newOption.text = RetVal;
newOption.value = RetVal;

//if i remember correctly, variables declarations are left associative so this may work. just for fun.
//newOption.text = newOption.value = RetVal;

var mySelect = document.getElementById('mySelectListName');

  try {
    mySelect.add(newOption, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    mySelect.add(newOption); // IE only
  }
}

Open in new window


Please give a try. Gregg
Gregg

Just a note, i believe the try catch block is not great programming practice. The best method is detecting the browser and using something like below. but its quick.

if (!ie)
   //standard compliant code.
else
  //ie code.
jazz__man

ASKER
Hi,

Yes I am getting the return value ok.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Zvonko

That goes like this:
<script language="javascript" type="text/javascript">
    function openbrWindow() {
	/*
        var RetVal = window.showModalDialog("Popup/popupFrame.aspx?qs=../Pickers/TestForm.aspx",
        'PopupPage',
        'dialogHeight=300px;dialogWidth=700px,toolbar=no,unadorned=yes,directories=no,status=no,menubar=no,scrollbars=no,resizable=no ,modal=yes',
        '',
        true);

        var LstItems = document.getElementById("<%= lstItems.ClientID %>");

*/
var RetVal = "My New Value";
var LstItems = document.getElementById("mySelect");
var opt = LstItems.options;
opt[opt.length] = new Option(RetVal, 1);

    }
</script>
<form>
<select id="mySelect">
</select>
</form>
<script>
openbrWindow();
</script>

Open in new window

Zvonko

Or simply, this is all you need:
opt[opt.length] = new Option(RetVal, 1);

Open in new window

ASKER CERTIFIED SOLUTION
Zvonko

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Kiran Sonawane

In fact this is very simple and just one line of code. Check this below code (Tested)
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  openbrWindow();
});

 function openbrWindow(){
   /*var RetVal = window.showModalDialog("Popup/popupFrame.aspx?qs=../Pickers/TestForm.aspx",
   'PopupPage',
   'dialogHeight=300px;dialogWidth=700px,toolbar=no,unadorned=yes,directories=no,status=no,menubar=no,scrollbars=no,resizable=no ,modal=yes',
   '',
   true);
   */
  var LstItems = document.getElementById("mySelect"); // ***you can use   var LstItems = document.getElementById("<%= lstItems.ClientID %>"); ****
  var RetVal = "My New Value";
  $(LstItems).append('<option value="'+RetVal+'" selected="selected">'+RetVal+'</option>');
}
</script>
</head>
<body>
  <select id="mySelect"><option value="test">test</option></select>
</body>
</html>

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Zvonko

And here my tested example with the two additional Option creation parameters: defaultSelected and currentSelected:
<html>
<head>
<title>Zvonko &#42;</title>
<script>
function addOptionItem() {
  var LstItems = document.getElementById("mySelect");
  var opt = LstItems.options;
  var optionText = "My New Text "+opt.length;
  var optionValue = "My New Value "+opt.length;
  var defaultSelected=false;
  var nowSelected=true;
  opt[opt.length] = new Option(optionText, optionValue, defaultSelected, nowSelected);
}
</script>
</head>
<body>
<form>
<select name="mySelect" id="mySelect" multiple="TRUE" >
<option value="oldOpt">oldOpt</option>
</select>
<input type="button" value="add" onClick="addOptionItem()" >
<input type="reset" value="reset form" >
</form>
</body>
</html>

Open in new window

Most people do not get the defaultSelected parameter. To see that parameter effect I have added the button type="reset".
jazz__man

ASKER
var opt = LstItems.options;
        opt[opt.length] = new Option(RetVal, 1);

Hi this works but again the text only lasts in the box for a split second and then disappears.
Kiran Sonawane

Have you tried my code
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
jazz__man

ASKER
sonawanekiran

Hi, yes I have tried your code but it gives an object expected error.

Thanks
Kiran Sonawane

Have you added below line in head tag

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
jazz__man

ASKER
It kind of worked and then flagged the following error...

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Kiran Sonawane

jazz__man

ASKER
I am going with one of the earlier solutions that are a bit more simple. The problem has kind of changed now anyway. I have the code to load the listbox but the value disappears directly after loading it. I will open another question to tacle this next problem.