Pergunta

I have a problem using the selected value from a form in jquery. It is closely related to:

I have tried for hours getting this work using the above (and other) examples.

I have a drop down list with account numbers:

    <form id="accounts">
        <select>
            <option value="">Select one</option>
            <c:forEach var="custAccount" items="${customerAccounts}">
                <option value=${customerAccount}>${customerAccount.accountId}</option>
            </c:forEach>
        </select>
    </form>

I want to use the selected account in an href:

            <a href="Controller?&accountid='+selectedAccount+'&username=${username}&userid=${userid}&command=customerNewTransaction">Start new transfer</a>

And here is my script:

    <script type="text/javascript">
      $(document).ready(function() {
        var selectedAccount;
        $("#accounts").change(function() {
           selectedAccount = $(this).text();
        });
      });
    </script>

This doesn't work and the selected text is empty every time. I have also tried calling .val() aswell with the same (lack of) result.

What am I missing?

Foi útil?

Solução

<form id="accounts">
    <select id="account-select">
        <option value="">Select one</option>
        <c:forEach var="custAccount" items="${customerAccounts}">
            <option value=${customerAccount}>${customerAccount.accountId}</option>
        </c:forEach>
    </select>
    <div id="transfer-container">

    </div>
</form>

<script type="text/javascript">
  $(document).ready(function() {
      $("#account-select").change(function() {
          $('#transfer-container').html( '<a href="Controller?&accountid='+ $(this).val() +'">Start new transfer</a>' );
    });
  });
</script>

Outras dicas

You have added an change handler on the form, instead of the select. You might want something like this:

<form id="accountForm">
  <select id="account">
    ..
  </select>
</form>

and then in your jQuery script:

$(document).ready(function () {
    $('#account').on('change', function (event) {
      $('#accountForm').append($(this).val());
    });        
});

Ah, I see MackieeE beat me to it, but just to offer a slightly different example:

    <script type="text/javascript">
        function updateLink() {
            var selectedAccount = $('#account').val();
            var uri = 'Controller?&accountid='+selectedAccount+'&command=customerNewTransaction';

            $('#account-link').attr('href', uri);
        }
    </script>

    <form>
      <select id="account" onchange="updateLink();">
        <option value="0" selected disabled>Select one</option>
        <c:forEach var="custAccount" items="${customerAccounts}">
          <option value=${customerAccount}>${customerAccount.accountId}</option>
        </c:forEach>
      </select>
    </form>

    <a id="account-link" href="#">Start a new transfer</a>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top