Smudger
Smudger

Reputation: 10809

Make select option 'selected' based on database query result

Have a script which queries a database and highlights the returned result in the select field.

I am using codeigniter with jquery, jquery mobile and jquery ui.

my view syntax is:

<select id="defaulttreated" name="defaulttreated" data-mini="true" data-theme="a">
    <option value="0" selected></option>
    <option value="yes">Yes</option>
    <option value="no">No</option>
</select>

my view jquery is:

function gettreating() {
    //populate treating  start
    var deliveryaddress = $("#deliveryaddress").val();
    //populate treating end
    $.post('gettreatingdefault', {
        deliveryid: deliveryaddress
    }, function (result) {
        alert(result);
        var el = $('#defaulttreated');
        el.val(result).attr('selected', true).siblings('option').removeAttr('selected');
        el.selectmenu("defaulttreated", true);
    });
}

I have verified that the value of result is working. currently the alert returns 'yes'.

How do I make yes selected in the defaulttreated select box?

Currently the error message is:

Error: no such method 'defaulttreated' for selectmenu widget instance and points to line 3 of jquery.min.js

Upvotes: 0

Views: 2260

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34217

var el = $('#defaulttreated');
var result = "yes";// just to fix the value
el.val(result);
alert(el.val() + el.find('option:selected').text());//show the selected option and its text

NOTE: You do not have to "unselect" the other options unless this select has multiple on. working example: enter link description here

Upvotes: 1

StackSlave
StackSlave

Reputation: 10617

Try something like:

function gettreating(){
  $.post('gettreatingdefault.php',
    {deliveryid: $("#deliveryaddress").val()},
    function(result){
      $('#defaulttreated option').each(function(){
        $(this).removeAttr('selected');
        if($(this).val() === result){
          $(this).attr('selected', 'selected');
        }
      });
    }
  });
}

Upvotes: 1

Related Questions