Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display forename and surname in separate text inputs?

Tags:

jquery

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?

like image 999
Manixman Avatar asked Dec 19 '12 00:12

Manixman


2 Answers

        var split = text.split(' ');
        $('#currentAdminAlias').val( split[0] );     
        $('#currentAdminForename').val( split[2] );   
        $('#currentAdminSurname').val( split[3] );  
like image 108
Sam Sussman Avatar answered Oct 07 '22 18:10

Sam Sussman


        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>
like image 36
SamStephens Avatar answered Oct 07 '22 16:10

SamStephens