skip to Main Content

Let’s say I have a select field

$('#myselect').on('change' , function() {
  var a = $('#result'); 
  select = $(this).val();  // Get the value  
  selectValue=$(this).find(':selected').data("value");   
  a.find('.b').html(selectValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<select id="myselect" style="" name="select[]" class="select">
         <option data-value="ABC">My product</option>
         <option data-value="BCD">My second product</option>
   </select>

   <div id="result">
   <span class="b"></span>
   </div>

So the results would be "ABC" and "BCD" and instead I want to display "BCD" for the first one, and "CDE" for the second.. so the next letters of the displayed value in english alphabet..

Any help would be appreciated …

Edit :
In the answers given below, when there is a Z in the options, it displays ]. The function that returns -26 if it’s a z doesn’t seem to work. So I mixed up the code snippets and came up with a result that seems to work.

$('#myselect').on('change', function() {
  let result = [...$(this).find('option:checked').data('value')].map(
    (letter) => {
      if (letter == "z") {
          return "a";
        } else if (letter == "Z") {
          return "A";
        } else {
          return String.fromCharCode(letter.charCodeAt(0) + 1);
        }
    }).join('');
    
  $('#result .b').text(result)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<select id="myselect" style="" name="select[]" class="select">
         <option data-value="ABC">My product</option>
         <option data-value="XYZ">My second product</option>
   </select>

   <div id="result">
   <span class="b"></span>
   </div>

3

Answers


  1. I don’t know if I understood your request correctly but the code below, from what I understood of course, should be able to help you.

    $(function(){
    
    $('#myselect').on('change' , function() {
    
        let nbLetter    = 3;
        let beginCode   = $(this).find(':selected').data("value").charCodeAt(0);
        let myValue     = "";
    
        // Construct New Value
        for(let i=0;i<nbLetter;i++) myValue += String.fromCharCode(beginCode+1+i);
    
        console.log(myValue);
    });
    
    });
    
    Login or Signup to reply.
  2. One approach is as follows, with explanatory comments in the JavaScript code:

    // we select the element with the id of 'myselect', and
    // bind the anonymous function of the on() method as the
    // event-handler for the 'change' event:
    $('#myselect').on('change', function() {
    
      // we use the spread syntax, with an Array-literal, to
      // we use the CSS selector 'option:checked' to find the
      // <option> element that has been selected, retrieve its
      // value and then convert that iterable String into an
      // Array using the spread syntax with an Array-literal;
      // we then call Array.prototype.map() to create a new
      // Array based on the first:
      let result = [...$(this).find('option:checked').val()].map(
        // within the map() method, we use an anonymous Arrow
        // function to pass in the current letter of the String:
        (letter) => {
          // we use String.prototype.charCodeAt() to retrieve the
          // the char-code of the current letter (passing an index
          // of zero to do so, as it's the only letter and
          // JavaScript is zero-based):
          let characterCode = letter.charCodeAt(0),
              // to retrieve the char-code of the next letter
              // I assumed that we should wrap around to 'A'/'a'
              // if the current letter is 'Z'/'z':
              // we first find if the Array of numbers 90 and 122
              // (the char codes for 'Z' and 'z' respectively);
              // if so we subtract 26 from the character code (to
              // return the 'A' of the relevant case, or if not
              // we return the character-code + 1:
              nextCode = [90, 122].includes(characterCode) ? characterCode - 26 : characterCode + 1;
              
          // here we return the next letter through the use of
          // String.prototype.fromCharCode() and passing in the
          // nextCode variable:
          return String.fromCharCode(nextCode);
        // we then use Array.prototype.join() to create a String
        // from the Array of letters:
        }).join('');
        
      // selecting the element(s) with a class-name of 'b' that are
      // nested within the element with an id of 'result':
      $('#result .b').text(result)
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <select id="myselect" name="select[]" class="select">
      <option value="ABC" data-value="ABC">My product</option>
      <option value="BCD" data-value="BCD">My second product</option>
    </select>
    
    <div id="result">
      <span class="b"></span>
    </div>

    JS Fiddle demo.

    This is, of course, perfectly possible in plain JavaScript without use of a library, as follows:

    // utility functions to reduce repetetive typing (I don't enjoy typing 'document.querySelector...'
    // all that much:
    const D = document,
        get = (selector, context = D) => context.querySelector(selector),
        getAll = (selector, context = D) => [...context.querySelectorAll(selector)];
    
    // here we retrieve the element with an id of 'myselect' and use EventTarget.addEventListener()
    // to bind the anonymous function as the event-handler for the 'change' event:
    get('#myselect').addEventListener('change', function(evt) {
      // here we retrieve the element within the evt.currentTarget (the element
      // to which the event-handler is bound) that matches the 'option:checked'
      // CSS selector, retrieve its value and then trim() leading and trailing
      // white-space:
      let result = [...get('option:checked', evt.currentTarget).value.trim()].map(
        // as above, we use the anonymous function of the Array.prototype.map() 
        // method, passing in a reference to the current letter of the Array of
        // letters:
        (letter) => {
          // retrieve the char-code of the current letter:
          let characterCode = letter.charCodeAt(0),
              // determine if the current letter is a 'Z'/'z', and if so we
              // subtract 26 (to get an 'a' of the correct case), otherwise
              // we add a 1 to get the next char-code:
              nextCode = [90, 122].includes(characterCode) ? characterCode - 26 : characterCode + 1;
          // returning the String created from that nextCode value:
          return String.fromCharCode(nextCode);
        // and join the Array of letters back to an Array:
        }).join('');
      // retrieving the first - if any - element(s) that match the supplied
      // CSS selector, and update the textContent of that element to be
      // equal to the newly-created String:
      get('#result .b').textContent = result;
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <select id="myselect" name="select[]" class="select">
      <option value="ABC" data-value="ABC">My product</option>
      <option value="BCD" data-value="BCD">My second product</option>
    </select>
    
    <div id="result">
      <span class="b"></span>
    </div>

    JS Fiddle demo.

    Of course the use of change does require that the user select a value other than the starting value (assuming that they wish the starting value to be their choice), so I’d suggest an adjusted HTML:

    $('#myselect').on('change', function() {
      let result = [...$(this).find('option:checked').val()].map(
        (letter) => {
          let characterCode = letter.charCodeAt(0),
              nextCode = [90, 122].includes(characterCode) ? characterCode - 26 : characterCode + 1;
              
          return String.fromCharCode(nextCode);
        }).join('');
        
      $('#result .b').text(result)
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <select id="myselect" name="select[]" class="select">
      <!-- here we use an <option> element that is both selected, so that it's shown on
           page-load, and disabled so that it can't be selected by the user once the
           select has been opened; forcing them to choose one of the other options: -->
      <option selected disabled>Please select:</option>
      <option value="ABC" data-value="ABC">My product</option>
      <option value="BCD" data-value="BCD">My second product</option>
    </select>
    
    <div id="result">
      <span class="b"></span>
    </div>

    JS Fiddle demo.

    References:

    *CSS:

    Login or Signup to reply.
  3. I am not sure if you mean get value for next element or what , if i understand right this code will work for you

        $(document).ready(function() {
          $("#myselect").change(function() {
            var selectedOption = $(this).find("option:selected");
            var nextOption = selectedOption.next();
        var a = $('#result');
        a.find('.b').html(nextOption.data("value"));
    
          });
        });
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <select id="myselect" style="" name="select[]" class="select">
                 <option data-value="ABC">My product</option>
                 <option data-value="BCD">My second product</option>
                 <option data-value="CDE">My Third product</option>
           </select>
    
           <div id="result">
           <span class="b"></span>
           </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search