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
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.
One approach is as follows, with explanatory comments in the JavaScript code:
JS Fiddle demo.
This is, of course, perfectly possible in plain JavaScript without use of a library, as follows:
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:JS Fiddle demo.
References:
*CSS:
:checked
*JavaScript:
Array.prototype.includes()
.Array.prototype.join()
.Array.prototype.map()
.String.prototype.charCodeAt()
.String.prototype.fromCharCode()
.I am not sure if you mean get value for next element or what , if i understand right this code will work for you