0

Firstly, apologize you find this really duplicates with other questions but since I'm already try most of the solutions given, but still stuck in the middle, then this is my last choice for getting the solutions. I've try the examples like this:

var user_dept = val[0].user_dept;
$('#user_dept option:selected').attr('value', user_dept);

and

var user_dept = val[0].user_dept;
$('#user_dept option[value="'+user_dept+'"]').attr('selected', true);

and as well this:

$('#user_dept').append($('<option>',{
        value: val[0].user_dept,
      }));

But couldn't get the issues solved. FYI, I declare all these codes inside if statement on jQuery. Wish to get the answers for jquery if possible since I'm using jquery for my work.

Edited:

As I mention on these comments below, I get the select option generated by this function,

function UserDept()
{
  $.getJSON('user_management_lib.php?mode=getDepartmentList', function(data){
    var list = [];
    $.each(data, function(index, value){
      list += '<option value="'+value['department_id']+'">'+value['department']+'</option>'
    });
    $('#user_dept').html(list);
  });
}

But as for selected option, I need to get this done by value which are equal to user_dept column from distinct table which is totally unrelated to function above. Since I use jQuery and array, I will declare this in $('#user_dept').val(val[0].user_dept);. I will clarify if necessary. Sorry for any inconveniences.

Edited on 30/12/2016: Code below is the callback function using ajax where this question also included. So, it's quite incomplete since I'm playing around to fix this.

$.ajax({
  cache: false,
  url: 'ldap_lib.php',
  data:'mode=findLDAPServerInfo&ldapid=<?php echo $target_lid; ?>',
  type:'POST',
  dataType:'json',
  success: function(val){
    UserDept();
    UserRole();
    GlobalDept();
    $('#mode').val('editLDAPServer');
    $('#l_name').val(val[0].l_name);
    $('#l_desc').val(val[0].l_desc);
    $('#l_ip1').val(val[0].l_ip1);
    $('#l_port1').val(val[0].l_port1);
    $('#l_ip2').val(val[0].l_ip2);
    $('#l_port2').val(val[0].l_port2);
    $('#l_domainname').val(val[0].l_domain);
    $('#l_loginname').val(val[0].l_loginname);
    $('#l_loginpwd').val(val[0].l_loginpwd);
    $('#l_mobile').val(val[0].l_mobile);
    $('#l_basedn').val(val[0].l_basedn);
    $('#l_filter').val(val[0].l_filter);
    $('#l_type').val(val[0].l_type);
    $('#l_loginmode').val(val[0].l_loginmode);
    $('#l_scope').val(val[0].l_scope);
    $('#sync_frequency').val(val[0].sync_frequency);
    $('#sync_time').val(val[0].sync_hour);

    if(val[0].sync_ul == 't'){
      $('#l_sync_ul').prop('checked', true);
      $('#tip_ul_dept').attr('style','display:block');
      var user_dept = val[0].user_dept;
      var user_role = val[0].user_role;
      //$('#user_dept option[value="'+user_dept+'"]').attr('selected', true);
      //$('#user_role option[value="'+user_role+'"]').attr('selected', true);
      //$('#user_dept option:selected').attr('value', user_dept);
      console.log($("#user_dept option"));
    } else{
      $('#l_sync_ul').prop('checked', false);
      $('#tip_ul_dept').attr('style','display:none');
    }
    if(val[0].sync_gab == 't'){
      $('#l_sync_gab').prop('checked', true);
      $('#tip_gab_dept').attr('style','display:block');
      // $('#gab_dept').val(val[0].gab_dept);
    } else{
      $('#l_sync_gab').prop('checked', false);
      $('#tip_gab_dept').attr('style','display:none');
    }
    //$('#gab_dept').val(val[0].gab_dept);
    $('#user_dept').val(val[0].user_dept);
  },
  error: function(){
    alert('Failed To Retrieve Server');
  }
});
Wafie Ali
  • 228
  • 9
  • 24
  • are you using any plugin for select ? – mr. Dec 29 '16 at 08:39
  • I used bootstrap-template for my project but no idea if any plugin used for this. sorry for unsatisfied answer. – Wafie Ali Dec 29 '16 at 08:41
  • can you copy your html code of select here? – mr. Dec 29 '16 at 08:43
  • if your select code is totally like that this solves the problem http://stackoverflow.com/questions/4680075/set-selected-option-of-select-box or the cause of not working is somewhere else in your html. Maybe there is also given id #user_dept in your code – mr. Dec 29 '16 at 08:47
  • @WafieAli what exactly is it you're trying to do? The code samples you've provided all do different things, and none of them do what you've described in the post title. – Simon Robb Dec 29 '16 at 08:47
  • since I use jquery, most of process is doing in jquery inside – Wafie Ali Dec 29 '16 at 08:50
  • jQuery wraps all the selection mechanics for you. Just use `val()` on the `select` to get or set the current selection option value. – iCollect.it Ltd Dec 29 '16 at 08:55
  • It's still not clear to me. Are you trying to populate the select box with option elements corresponding to the rows in your database? – Simon Robb Dec 29 '16 at 08:55
  • If I understand your questions, I need to make one of the options gets selected based on column value from database table. – Wafie Ali Dec 29 '16 at 09:03

1 Answers1

1

If you are simply trying to get the value of the select element, that is, the value of the currently selected option element belonging to the select element, you can use jQuery's .val() function: $('#user_dept').val().

If you are trying to get the option element which has a given value, as your post title indicates, use $('#user_dept option(value="' + val + '")').

The above assumes that val is a string/string-like value - you've used val[0] in your code sample which indicates val is an array. Use val[0] if that's the case.

Edit You are trying to set the value of the select element before the select options have been created (they're generated asynchronously from a JSON request).

Make sure that the options have been generated before doing this - I've updated your JSFiddle with an example of how you might do this.

Simon Robb
  • 1,668
  • 1
  • 14
  • 25
  • is inside .val() need to put value, like .val('sc123455')? – Wafie Ali Dec 29 '16 at 08:45
  • I've try the answers above & make it like this `$('#user_dept').val(val[0].user_dept);` but still doesnt work. Here is my html code related to this `` – Wafie Ali Dec 29 '16 at 09:02
  • no errors but no option selected. supposedly val is equal to `val[0].user_dept`. `user_dept` is a column in database table. but the whole select option is generated by this syntax: `function GlobalDept() { $.getJSON('user_management_lib.php?mode=getDepartmentList', function(data){ var list = []; $.each(data, function(index, value){ list += '' }); $('#gab_dept').html(list); }); }` Do I have to make any conditions to match the value from database to the value from this functions? – Wafie Ali Dec 29 '16 at 09:15
  • We need the actual value of that variable. Do `console.log(val)` and let us know the result. – Simon Robb Dec 29 '16 at 09:17
  • here's the result from `console.log(val[0].user_dept);` : CC162981257010951 – Wafie Ali Dec 29 '16 at 09:21
  • The `option` elements have to be present in the DOM when you use the `.val(val[0].user_dept)` statement. If there are no options present, there'll be nothing for that function to select. A possibility is that since you're loading the options asynchronously (using `getJSON`), the options are being loaded after you try to select the option. Move the `.val(...` to the end of the `getJSON` callback function and see if that works. – Simon Robb Dec 29 '16 at 09:31
  • I try this `$('#user_dept').val(val[0].user_dept);` as you said to end off callbacks but still doesn't work. I expected all select options to be appeared but just one to be selected based on `.val(val[0].user_dept);` – Wafie Ali Dec 29 '16 at 09:36
  • We need to see what the state of the DOM is when you use that `.val` function. Do `console.log($("#user_dept option"))` – Simon Robb Dec 29 '16 at 09:44
  • Here is the result : `Object { length: 0, prevObject: Object, context: HTMLDocument → ldap_edit.php, selector: "#user_dept option" } ldap_edit.php:427:7` – Wafie Ali Dec 29 '16 at 09:47
  • Ok that means there are no option elements present when you try to make the selection (`length: 0`). Check the final line of code in your comment above, it uses the ID `gab_dept`, did you intend this to be `user_dept`? – Simon Robb Dec 29 '16 at 09:50
  • I'm really sorry buddy for wrong function posted. here is the right one, `function UserDept() { $.getJSON('user_management_lib.php?mode=getDepartmentList', function(data){ var list = []; $.each(data, function(index, value){ list += '' }); $('#user_dept').html(list); }); }` gab_dept is for another select element, but for this case, I want to focus for user_dept first. – Wafie Ali Dec 29 '16 at 09:56
  • Ok. Can you confirm you've moved `.val(val[0].user_dept)` to the end of the callback function, after `$('#user_dept').html(list);`? Make sure that `val[0].user_dept` is still the value you expect when used in this new location. – Simon Robb Dec 29 '16 at 10:19
  • sorry I will continue this tomorrow on Malaysia Time since I gotta go. Really appreciated your great support. I will try to make this solve ASAP. – Wafie Ali Dec 29 '16 at 10:21
  • I've done you said but still didn't manage to work. Is there anything I'm still missing? – Wafie Ali Dec 30 '16 at 02:13
  • Can you put your code into a JSFiddle? I'll take a look at it there if you like. – Simon Robb Dec 30 '16 at 02:17
  • As suspected you are trying to set the value of the select box before the option elements are loaded. `UserDept()` returns immediately, but the option elements are generated until after the JSON request it fires is completed. See the [updated fiddle](https://jsfiddle.net/afkjm2rg/1/). – Simon Robb Dec 30 '16 at 02:46
  • still the same, not working. is it because it looks for option value text, not value attribute instead? Console are showing this error: `ReferenceError: val is not defined[Learn More] UserDept/< n.Callbacks/i n.Callbacks/j.fireWith z .send/c/< ` – Wafie Ali Dec 30 '16 at 03:02
  • 1
    As above, "Make sure that `val[0].user_dept` is still the value you expect when used in this new location. [Updated fiddle](https://jsfiddle.net/afkjm2rg/2/) – Simon Robb Dec 30 '16 at 03:09
  • it's worked as I amend this in this [updated fiddle](https://jsfiddle.net/afkjm2rg/3/). I will try this example to another select element. feel free to edit your main answer to this solutions, so I can credit you. this is the way I can appreciate all your helps to way out from this. – Wafie Ali Dec 30 '16 at 03:24