Set select option 'selected', by value

后端 未结 28 2933
攒了一身酷
攒了一身酷 2020-11-22 10:40

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the

28条回答
  •  清歌不尽
    2020-11-22 11:26

    Use:

    $("div.id_100 > select > option[value=" + value + "]").attr("selected",true);
    

    This works for me. I'm using this code for parsing a value in a fancybox update form, and my full source from app.js is:

    jQuery(".fancybox-btn-upd").click(function(){
        var ebid = jQuery(this).val();
    
        jQuery.ajax({
            type: "POST",
            url: js_base_url+"manajemen_cms/get_ebook_data",
            data: {ebookid:ebid},
            success: function(transport){
                var re = jQuery.parseJSON(transport);
                jQuery("#upd-kategori option[value="+re['kategori']+"]").attr('selected',true);
                document.getElementById("upd-nama").setAttribute('value',re['judul']);
                document.getElementById("upd-penerbit").setAttribute('value',re['penerbit']);
                document.getElementById("upd-tahun").setAttribute('value',re['terbit']);
                document.getElementById("upd-halaman").setAttribute('value',re['halaman']);
                document.getElementById("upd-bahasa").setAttribute('value',re['bahasa']);
    
                var content = jQuery("#fancybox-form-upd").html();
                jQuery.fancybox({
                    type: 'ajax',
                    prevEffect: 'none',
                    nextEffect: 'none',
                    closeBtn: true,
                    content: content,
                    helpers: {
                        title: {
                            type: 'inside'
                        }
                    }
                });
            }
        });
    });
    

    And my PHP code is:

    function get_ebook_data()
    {
        $ebkid = $this->input->post('ebookid');
        $rs = $this->mod_manajemen->get_ebook_detail($ebkid);
        $hasil['id'] = $ebkid;
        foreach ($rs as $row) {
            $hasil['judul'] = $row->ebook_judul;
            $hasil['kategori'] = $row->ebook_cat_id;
            $hasil['penerbit'] = $row->ebook_penerbit;
            $hasil['terbit'] = $row->ebook_terbit;
            $hasil['halaman'] = $row->ebook_halaman;
            $hasil['bahasa'] = $row->ebook_bahasa;
            $hasil['format'] = $row->ebook_format;
        }
        $this->output->set_output(json_encode($hasil));
    }
    

提交回复
热议问题