asp dropdownlist dynamic value from javascript issue

I have a dropdownlist with 5 items. Value of last item is “other”. By choosing “other” appears popup with input. The value of this input i set to this item by javascript. So value becoms inserted text. When i submitting the form, it doesn’t work with this dynamic value, but other items of select works. Any ideas? Thanks very much!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here is a quick example of using Request.Params collection to read dynamically added value.

Here is the client side code.

<!-- Server Control - Drop Down List -->
<asp:DropDownList ID="ddList" runat="server">
    <asp:ListItem Text="A" Value="A"></asp:ListItem>
    <asp:ListItem Text="B" Value="B"></asp:ListItem>
    <asp:ListItem Text="C" Value="C"></asp:ListItem>
</asp:DropDownList>

<!-- Control to fire JS event to add a new item to the Drop Down List above -->
<input type="button" value="Add Item D" id="AddItem" />

<!-- jQuery event to add a new option to the list on the click (no postback) -->
$('#AddItem').click(function ()
{
    $('#<%= ddList.ClientID %>').append('<option value="D">D</option>');
});

Here is the server side code to read the value.

var ddlListSelectedValue = Request.Params["ddList"];

Method 2

Rather than set this value as droupdown list item value, you can use hiden field

<input type="hidden" id="hiddenField" runat="server" />

set value using JavaScript as below

document.getElementById ("hiddenField").value = "inputValue";

hiddenField value can access from code behind as below

string inputValue = hiddenField.Value;

Method 3

Just Update you Function

$('#AddItem').click(function ()
{
var dropdown= document.getElementById("<%= ddList.ClientID %>");
dropdown.options[dropdown.options.length] = new Option('YOUR TEXT', 'YOUR VALUE');
});

Cheers

I have tested it myself, it works. Following is a complete example:

<html>
<head>
<title>Test ddl Item Addition By IuR</title>
</head>
<body onload="add_dditem()">
<script type="text/javascript">
function add_dditem()
{
var dropdown= document.getElementById("ddList");
dropdown.options[dropdown.options.length] = new Option('YOUR TEXT', 'YOUR VALUE');
}
</script>

<select id="ddList">
</select>
</body>
</html>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x