Issue with .change function in jQuery form

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 click 'End Date' and then click 'Start Date' again, it displays 'Start Date' in the span?

Demo: http://jsfiddle.net/197ncb10/

$(function() {
  $('#usertype').change(function() {
    $(this).next("span").text("End Date");
  });
});
<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>

Answers:

Answer

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>

Answer

Like this:

$(function() {         
    $('#usertype').change(function() {        
        let text=$(':selected',this).text();
        $(this).next("span").text(text);
    });     
}); 
Answer

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

Answer

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());

  });
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.