0

I convert an array php to json like this:

var jsoncsv = '<?php echo json_encode($csvData); ?>';
console.log(jsoncsv);

The output of those json like this :

{"1":
{" NO":"    1",
 "EIR IN":"1545053   ",
 "CONT":"EOLU 1111111",
 "TYPE":"XXXX",
 "INDEPO":"21-11-2015",
 "JAM":"13:00",
 "KODE VSL":"ABO",
 "VESSEL":"ALBERT OLDENDORFF   ",
 "VOY":"N001   ",
 "CONSIG":"ASTABUMI CIPTA      ",
 "COND IN":"DMG",
 "CLEAN":"DIRTY",
 "TARE":"  2400",
 "GROSS":" 20000",
 "KAPASITAS":"  5000",
 "EX CARGO":"FOOD                ",
 "LAST AIR)":"  -  -    ",
 "LAST HIDRO":"  -  -    ",
 "MANU":"10-11  ",
 "BUILDER":"                    ",
 "OWNER":"APL                 "},

"2":
{" NO":"    2",
 "EIR IN":"1545052   ",
 "CONT":"EOLU 1234567",
 "TYPE":"IM04",
 "INDEPO":"21-11-2015",
 "JAM":"10:00",
 "KODE VSL":"202",
 "VESSEL":"WAN HAI 202         ",
 "VOY":"N 001  ",
 "CONSIG":"ANUGERAH AGUNG LUMIN",
 "COND IN":"AVL",
 "CLEAN":"DIRTY",
 "TARE":"  2400",
 "GROSS":" 20000",
 "KAPASITAS":"  1000",
 "EX CARGO":"MAKANAN             ",
 "LAST AIR)":"  -  -    ",
 "LAST HIDRO":"  -  -    ",
 "MANU":"11-13  ",
 "BUILDER":"                    ",
 "OWNER":"APL                 "}}

And I have select option ON HTML:

<select data-placeholder="Masukkan EIR"  id="search" >
     <?php
        foreach ($csvData as $v) {
             echo '<option value ='. $v['NO'].' >' . $v['EIR IN'] . '- ' . $v['CONT'] . '</option>';
         }
     ?>
</select>

With jquery, I manage the select option. The code is looked like this :

$(document).on("change", '#search', function(){ 
        var selected = $('#search').val() ;
        /*Passed the selected data, search in json*/
});

Assumed, select option.val is 2, how can I get all the "2"'s element of the json like NO, EIR IN ?

1 Answer 1

1

This works:

$(document).on("change", '#search', function(){ 
        var selected = $('#search').val();
        var json = <?php echo json_encode($csvData) ?>;
        alert(json[selected]['EIR IN']);
});

Your HTML part should be like this:

<select data-placeholder="Masukkan EIR"  id="search" >
     <?php
        foreach ($csvData as $v) {
             echo '<option value ='. $v[' NO'].' >' . $v['EIR IN'] . '- ' . $v['CONT'] . '</option>';
         }
     ?>
</select>

Notice that you have gap here -> " NO", so there is no "NO" element in your json

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry Mr@Sam, it gives a undefined
@FadlyDzil I've tested the code, that is because your $v['NO'] has no value, so $('#search').val() is undefined. You should modify your json: " NO" -> "NO" or change $v['NO'] to $v[' NO']. Notice the gap before NO
Owh, my bad. Thank you so much @Sam

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.