0

I have really put efforts in searching for possible answers here and on Google. I did find some answers but when I apply them to my code and my situation, it just doesn't work.

I tried:

$("select#city option['City, ST']").attr('selected', 'selected');

I also tried:

$("select#city").val('City, ST');

as suggested somewhere.

I tried putting this code to a document.ready function - to no avail. I then tried placing it at the top (not in the head section though) with no document.ready but still the same.

What could be the reason for this function to fail? Is the moment when it's called important (I mean, does it matter if my select box with values render first and then the function gets called? Or could it be something else?

HTML code:

<div class="ui-widget">
            <h3>Location</h3>
            <form id="chooseCity" class="" action="" method="post">
                <select id="city" name="city">

                    <option value="Select Town">Select Town</option>
                    <option value='Acworth, NH'>Acworth, NH</option>
                    <option value='Alstead, NH'>Alstead, NH</option>
                    <option value='Alton, NH'>Alton, NH</option>
                    <option value='Alton Bay, NH'>Alton Bay, NH</option>
                    <option value='Amherst, NH'>Amherst, NH</option>
                    <option value='Andover, NH'>Andover, NH</option>
                    <option value='Antrim, NH'>Antrim, NH</option>
                    <option value='Concord, NH'>Concord, NH</option>
                </select>
            </form>
        </div>

Could this loop be the culprit? Maybe it's somehow interferring:

                <option value="Select Town">Select Town</option>
                    <?php foreach($arr as $city):
                        echo "<option value='{$city}'";
                        echo ($_POST['city-hp'] == $city) ? 'selected' : '';
                        echo ">".$city."</option>".PHP_EOL;
                    endforeach; ?>

IMPORTANT EDIT:

I've discovered that this piece of code:

$(function() {
    $( "#city" ).combobox();
    $( "#toggle" ).click(function() {
        $( "#city" ).toggle();
    });
});

is preventing my combobox to programmatically select desired value. But this piece of code is crucial for styling the select box. I've downloaded the example from the jQuery UI website and integrated it into my website.

How can the above code be modified to retain its appearance while allowing for the desired functionality?

Sara
  • 8,222
  • 1
  • 37
  • 52
developer10
  • 1,450
  • 2
  • 15
  • 31
  • 3
    Are you trying to figure out which one is selected, or preselect one? Can you include an example of the select? – saml Oct 04 '12 at 22:17
  • 2
    It's not clear to me what "get back value back to my select box" means. Please explain exactly what you want to do. – Erik Funkenbusch Oct 04 '12 at 22:19
  • 2
    Please, post more code. Better, put in JSFiddle. – Alcides Queiroz Oct 04 '12 at 22:19
  • 1
    Judging by the question title, I'm pretty sure he's trying to set the selected value programmatically. – Sara Oct 04 '12 at 22:20
  • I have a search page. Non-logged users are sent to the login screen. When logged in, they're being redirected back to the search results. As I'm using totalStorage jquery plugin, I'm able to fetch pre-stored values to rebuild my db query and get my results but my select box is showing Select City – developer10 Oct 04 '12 at 22:30
  • @Sara I tested it in a separate function with lines of code I wrote in the question. That function was on document.ready – developer10 Oct 04 '12 at 22:32
  • As per [this answer](http://stackoverflow.com/a/292620/1684247), also make sure the value in the option tag matches the value you're trying to set exactly (showing us the dropdown HTML might also improve answer quality). – Sara Oct 04 '12 at 22:35
  • @Sara I'm testing by manually entering the value, which is for example, 'Berlin, NH' and that's how it appears in my select box, so no mistake there – developer10 Oct 04 '12 at 22:40
  • @denny911 If you still haven't received an answer that works, I would really suggest posting the HTML. – Sara Oct 04 '12 at 22:42
  • @Sara HTML code added Note: I'm even able to get selected="selected" in my HTML markup but the value of select box is not actually changed! Also, my select box is jquery select box, with styling and stuff. – developer10 Oct 04 '12 at 22:49
  • Just tested on jsFiddle some line of code, then tried again on my localhost - to no avail. but see the screenshot: http://screencast.com/t/oQLbGMlXXv3 There actually is selected="selected" but no value is actually selected – developer10 Oct 04 '12 at 23:01

5 Answers5

2

You may try this to select an option programmatically

HTML

<select id="city">
    <option value=1>CityOne</option>
    <option value=2>CityTwo</option>
</select>

JS

$('#city').val(2); // will select the item which has value=2

or

$('#city').prop("selectedIndex",1); // will select second item/index, first is 0

DEMO.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • Hi again, I've discovered that this piece of code: $(function() { $( "#city" ).combobox(); $( "#toggle" ).click(function() { $( "#city" ).toggle(); }); }); is preventing my selectbox to programmatically select desired value. But this piece of code is crucial for styling the select box. I've downloaded the example from the jQuery UI website and integrated it into my website. How can the above code be modified to retain its appearance while allowing for the desired functionality? – developer10 Oct 05 '12 at 08:54
1

Try this

  $('select#city').find('option[value*="City"][value*="ST"]').attr('selected', 'selected');

OR

$("select#city option[value='City, ST']").attr('selected', 'selected');

CHECK DEMO

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • How can I have this function run isolated from my other scripts at the page bottom? Will it work at the top? Does it have to be on document.ready? – developer10 Oct 04 '12 at 22:38
1

Your jQuery works - something else is interfering.

I would suggest poking through other plugins you may have installed to see if they're overriding the selected index, probably just with the first <option> in the select.
Alternatively, if you want to elaborate on which technologies you're using, someone might be able to help you further.

Edit:

See the answers on this related question - it looks like you will have to edit the plugin's source.

Find this line in the combobox plugin:

.addClass("ui-widget ui-widget-content ui-corner-left");

and add this line immediately after it:

input.val( $(select).find("option:selected").text());

Source

Community
  • 1
  • 1
Sara
  • 8,222
  • 1
  • 37
  • 52
  • I'm using PHP (Concrete5 CMS). As I stated in another comment, I even get the string selected="selected" in the right place but the select box doesn't show that value as selected. – developer10 Oct 05 '12 at 07:23
  • Hi again, I've discovered that this piece of code: $(function() { $( "#city" ).combobox(); $( "#toggle" ).click(function() { $( "#city" ).toggle(); }); }); is preventing my selectbox to programmatically select desired value. But this piece of code is crucial for styling the select box. I've downloaded the example from the jQuery UI website and integrated it into my website. How can the above code be modified to retain its appearance while allowing for the desired functionality? – developer10 Oct 05 '12 at 08:51
  • Which combobox plugin are you using? – Sara Oct 05 '12 at 16:07
  • Okay, I've updated my answer. In the future, try to include as much detail as possible in your original post - it will really help you get fast, accurate answers. – Sara Oct 06 '12 at 01:41
0

I stumped this error and cannot fix it OnLoad event whatever I coded (Probably on 3 hours). At last luckily I acrossed http://www.onemoretake.com/2011/04/17/a-better-jquery-ui-combo-box/ web page(Thx for @Dan for solving my headache) and saw the real missing part is not on "OnLoad", on ui definition function itself. Standart definition function on the official Jquery Ui web page does not contain programmatically select option.

Here is the function should added to definition function :

//allows programmatic selection of combo using the option value
        setValue: function (value) {
            var $input = this.input;
            $("option", this.element).each(function () {
                if ($(this).val() == value) {
                    this.selected = true;
                    $input.val(this.text);
                    return false;
                }
            });
        }

also i produced another function to change selection via option text not option value

//allows programmatic selection of combo using the option text
            setValueText: function (valueText) {
                var $input = this.input;
                var selectedText;                   
                $("option", this.element).each(function () {
                    if ($(this).text() == valueText) {
                        this.selected = true;
                        $input.val(this.text);                                                    
                        return false;
                    }
                });                        
            }

You can use these functions on OnLoad or another function as :

$("#yourComboBoxID").combobox("setValue", "Your Option Value");

or

$("#yourComboBoxID").combobox("setValueText", "Your Option Text");
Tarık Özgün Güner
  • 1,051
  • 10
  • 10
-2

test is javascript object.

test.controlid is id of widget instance.

test.value is the string you want to select.

you don't need test object, you can use id and value directly.


$("#" + test.controlid).parent().find("span").children("input").val(test.value);

var newObject = new Object();

newObject.item = new Object();

newObject.item.option = $('#' + test.controlid +' > option[value="' + test.value + '"]')[0];

$("#" + test.controlid).parent().find("span").children("input").trigger("autocompleteselect", newObject);

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
msj
  • 1
  • 2
  • Welcome to Stack Overflow! This came to me to review as your first answer. There are a couple of problems with it. Firstly - you need to [format the code correctly](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks). Secondly, as this is an old question with an accepted answer - it would really need some extra test to explain why it does something better than (or is a totally different method to) the accepted answer. – J Richard Snape Feb 10 '15 at 16:10