In a drop down menu, I have each option displayed like below as an example:
scomp23 - Jack Turner
Now with this code below:
var text = $(this).find('option:selected').text();
var split = text.split(' - ');
$('#currentAdminAlias').val( split[0] );     
$('#currentAdminForename').val( split[1] );   
$('#currentAdminSurname').val( split[2] );  
What I am trying to do is display scomp23 in #currentAdminAlias text input (this works fine), display Jack in #currentAdminForename text input and  display Turner in #currentAdminSurname text input.
The problem I am having is that it displays both forename and surname in the #currentAdminForename text input only.
Now I know why this happens but my question is how can I display the forename and surname in separate text inputs?
        var split = text.split(' ');
        $('#currentAdminAlias').val( split[0] );     
        $('#currentAdminForename').val( split[2] );   
        $('#currentAdminSurname').val( split[3] );  
        var text = $(this).find('option:selected').text();
        var split = text.split(' - ');
        var names = split[1].split(' ');
        $('#currentAdminAlias').val( split[0] );     
        $('#currentAdminForename').val( names[0] );   
        $('#currentAdminSurname').val( names[1] );
Or consider attaching each of the values you want to the option element as an HTML 5 data attribute. Which would give you
        var element = $(this).find('option:selected');
        $('#currentAdminAlias').val(element.data('alias'));
        $('#currentAdminForename').val(element.data('forename'));
        $('#currentAdminSurname').val(element.data('surname'));
With a sample option element looking like
        <option data-alias="scomp23" data-forename="Jack" data-surname="Turner">
          scomp23 - Jack Turner
        </option>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With