简体   繁体   中英

How to get last character of .val() in Javascript

I want to apply different background color to my select elements based on the selected option.

I have this piece of code that I want to apply to my case:

$('select').on('change', function(ev) {
    $(this).attr('class', '').addClass($(this).children(':selected').val());
});

The problem is that in my case I don't want the complete value of selected option. But only the last character of the value returned by .val()

I have tried

$(this).attr('class', '').addClass($(this).children(':selected').val().id.slice(-1));

But it doesn't work

I took this code from this Example This works as I want also, but in my case the value of the option is different for every option, and I have hundreds of selects and options. In this format:

Name - Date - 1 Letter Variable

So I have the CSS like this:

select, option { background: #fff; }
select.P, option[value$='P'] { background: yellow; }
select.O, option[value$='O'] { background: lightblue; }
select.A, option[value$='A'] { background: lightgreen; }
select.R, option[value$='R'] { background: salmon; }

And an example of select:

<select onchange='myFunction()' id='" . $i . "' name='" . $i . "' style='width: 80px;'>
        <option value='' style='background:white' style='width: 80px;'></option>
        <option value='" . $vacationIdP . "' style='background:yellow' style='width: 80px;'>P</option>
        <option value='" . $vacationIdO . "' style='background:lightblue' style='width: 80px;'>O</option>
        <option value='" . $vacationIdA . "' style='background:lightgreen' style='width: 80px;'>A</option>
        <option value='" . $vacationIdR . "' style='background:salmon' style='width: 80px;'>R</option>
</select>

The problem is that you are applying slice on undefined . .val().id is undefined .
In your html you shouldn't get last char.Its not last. Use this

$('select').on('change', function(ev) {
    $(this).attr('class', '').addClass($(this).children(':selected').val().split('.')[1].trim().slice(-1));
});

JS Fiddle

You can use chartAt

 $('select').on('change', function(ev) { let k = $(this).children(':selected').val(); console.log(k.charAt(k.length - 1)) //$(this).attr('class', '').addClass($(this).children(':selected').val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select> <option value='abc'> ABC</option> <option value='def'>DEF</option> <option value='ghi'> GHI</option> </select>

Try val().pop(); Should return the last element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM