Get DropDown value when Textbox receives focus

1

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

I've already put a Autopostaback into DropDownList to send it to pro TextBox plus I did not like the performance.

Any suggestions?

    
asked by anonymous 28.12.2016 / 12:54

1 answer

1

Minimum 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><selectid="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 shown in the text box, the selected value and the text of select as shown in the example can be used either.

ASP.Net WebForms Example

<!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>
    
28.12.2016 / 13:21