Get Dropdown value when Textbox receives focus

Asked

Viewed 177 times

1

What can I do to get the value that is selected in a DropDownList and move on to a TextBox only when the Textbox receive the focus (when the user clicks the field)?

I had already put one Autopostaback in the DropDownList to send it value to TextBox But I didn’t like the performance.

Any suggestions?

  • Hello, To be in C# you have to call the server so you have to use Postback. It can be in javascript or jquery?

  • Hello, it can be yes, javascript or jquery, how would it look? how can I get the "Focus" event in javascript?

1 answer

1


Minimal example

$(document).ready(function(e) {
  $('#txt1').on('focus', function() {
    var element = $("#select1 option:selected");
    var text = $(element).text();    
    var value = $(element).val();
    if (text === '-Selecione-')
    {
      text = "";
      value = "";
    }
    $(this).val(value + ' ' + text);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <select id="select1" name="select1">
    <option value="">-Selecione-</option>
    <option value="1">Stackoverflow</option>
    <option value="2">Meta</option>
  </select>
</div>
<br />
<div>
  <input type="text" id="txt1" name="txt1" />
</div>

In the example the selected value and the text of the select as is in the example, can be used either or both.

Example in ASP.Net Webforms

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="DropDownListItens" runat="server">
                <asp:ListItem Text="-Selecione-" Value=""></asp:ListItem>
                <asp:ListItem Text="Stackoverflow" Value="1"></asp:ListItem>
                <asp:ListItem Text="Meta" Value="2"></asp:ListItem>
            </asp:DropDownList>
        </div>
        <div>
            <asp:TextBox ID="TextBoxItens" runat="server"></asp:TextBox>
        </div>
    </form>
    <script>
        $(document).ready(function (e) {
            $('#<%=TextBoxItens.ClientID%>').on('focus', function () {
                var element = $("#<%=DropDownListItens.ClientID%> option:selected");
                var text = $(element).text();
                var value = $(element).val();
                if (text === '-Selecione-') {
                    text = "";
                    value = "";
                }
                $(this).val(value + ' ' + text);
            });
        });
    </script>
</body>
</html>
  • 1

    Very good! was exactly what I needed, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.