Issue with .change function in jQuery form

前端 未结 4 559
囚心锁ツ
囚心锁ツ 2021-01-24 15:57

I am working on a script that changes the span text value depending on user input in the select menu.

I have a fault with my current script. How do I fix it so when I cl

相关标签:
4条回答
  • 2021-01-24 16:29

    Hope this will help you.

    Give id for span like:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="" method="post">
      <input type="hidden" id="myhidden3" name="quantity" value="1" />
      <select id='usertype'>
            <option value='1'>Start Date</option>
            <option value='2'>End Date</option>
            <option value='3'>End Date</option>
          </select>
      <span id='span_text'>Start Date</span>
    </form>
    

    Jquery:

    $(function() {
      $('#usertype').change(function() {
        $('#span_text').val($('#usertype  option:selected').text());
    
      });
    });
    
    0 讨论(0)
  • 2021-01-24 16:32

    You need to determine the selected option and then the text inside that option.

     $(function() {         
        $('#usertype').change(function() { 
            var selectedText = $("#usertype option[value='"+ $(this).val() +"']").text();
            $(this).next("span").text(selectedText);
        });     
    }); 
    

    Check out this jsfiddle JSFIDDLE

    0 讨论(0)
  • 2021-01-24 16:43

    This will do

    $(function() {
      $('#usertype').change(function() {
         $(this).next("span").text($('#usertype option:selected').text());
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="" method="post">
      <input type="hidden" id="myhidden3" name="quantity" value="1" />
      <select id='usertype'>
            <option value='1'>Start Date</option>
            <option value='2'>End Date</option>
            <option value='3'>End Date</option>
          </select>
      <span>Start Date</span>
    </form>

    0 讨论(0)
  • 2021-01-24 16:47

    Like this:

    $(function() {         
        $('#usertype').change(function() {        
            let text=$(':selected',this).text();
            $(this).next("span").text(text);
        });     
    }); 
    
    0 讨论(0)
提交回复
热议问题