achillix
achillix

Reputation: 479

Get different part of a selected value

I have three different parts in the value, when i choose a country, who are seperated with an Pipe "|". How can i take the values between the seperator in my thre input fields.

Here a demo on jsfiddle

The first value is the City, the second the street of the city and the third is the code postal. How can i get the three values seperated in the inputfields

---------------------------------------
Country Germany
City: Berlin
Street: Musterstrasse 16
Code Postal: 16500
---------------------------------------

THX in advance

Upvotes: 0

Views: 71

Answers (5)

Stefan
Stefan

Reputation: 14883

Get the index with

$(this).prop("selectedIndex");

and split the values with

$(this).val().split('|')[index];

Sample

   $("#country").change(
       function () {
           $("#capital").val($(this).val());
           $("#street").val($(this).val());
           $("#cp").val($(this).val());
       }
   );

Fiddle

Upvotes: 0

silly
silly

Reputation: 7887

$("#country").change(
   function () {
       var pieces = $(this).val().split('|');
       if(pieces.length === 3) {         
           $("#capital").val(pieces[0]);
           $("#street").val(pieces[1]);
           $("#cp").val(pieces[2]);
       }                          
   }
).trigger('change');

make a trigger to initialize!

Upvotes: 1

saraf
saraf

Reputation: 646

you can try something like this

   $("#country").change(
       function () {
           var value = $(this).val().split("|");
           $("#capital").val((value[0]));
           $("#street").val((value[1]));
           $("#cp").val((value[2]));
       }
   );​

Hope this helps..

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56829

Use split("|") to split the value by | character. This assumes that the capital, street and code postal doesn't contain the | character.

$("#country").change(
    function () {
        var selected = $(this).val();
        var tokens = selected.split("|");
        $("#capital").val(tokens[0]);
        $("#street").val(tokens[1]);
        $("#cp").val(tokens[2]);
    }
);

Demo: http://jsfiddle.net/hkKbb/6/

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

Try this:

$("#country").change(
function() {
    $("#capital").val($(this).val().split('|')[0]);
    $("#street").val($(this).val().split('|')[1]);
    $("#cp").val($(this).val().split('|')[2]);
});​

FIDDLE

Upvotes: 0

Related Questions