YVS1102
YVS1102

Reputation: 2748

same function run 4 times jquery and adding onchange

Good day,

<script>
$('#selparents option').each(function() {
    var type=$('#selparents').val();
        alert(type);
        $.post('<?php echo base_url();?>index.php/user_controll/show_detail/'+type,{
            type:type
        },
        function(data) 
        {
                $('#result').html(data);
        }); 
});
</script>

Above is my simple jquery.

Ok, what i want to do is. When the page has been executed the session will be made.

    public function show_detail($type)
        {
                extract(populateform());
                $this->session->set_userdata(array('tipe_pilihan' => $type));
                /////////

but when the page has not been executed the session must be empty . Onchange needed. How can i add onchange because my script above only work, if value has been set from session.

<select id="selparents" class="form-control select2" name="parent">
                                 <option value="0">None</option>
                                    <?php
                $s = "";
            $type_pilihan = $this->session->userdata('tipe_pilihan');
                                        foreach($tipe as $hslnya)
                                        {   if($type_pilihan == $hslnya->id_tipe)
                                            {
                                echo "<option selected value='".$hslnya->id_tipe."'>".$hslnya->deskripsi."</option>";
                                                }else{
                                                    echo "<option value='".$hslnya->id_tipe."'>".$hslnya->deskripsi."</option>";
                                                }
                                        }
                                    ?>
                                </select>

sorry for my bad english.

Thanks to @Barmar my loop alert fixed. But, not like my older script when select box already select some option from session the alert isn't show up (When reloaded).

Upvotes: 2

Views: 70

Answers (1)

Barmar
Barmar

Reputation: 782066

I'm not totally sure what you're asking, but I think this may be what you're looking for:

$("#selparents").change(function() {
    var type = $(this).val();
    $.post('<?php echo base_url();?>index.php/user_controll/show_detail/'+type,{
        type:type
    },
    function(data) 
    {
            $('#result').html(data);
    }); 
});        

Your code is performing the AJAX calls repeatedly when the page is loaded, not when the user selects from the menu.

Upvotes: 1

Related Questions