tags:

views:

24

answers:

3
<script type="text/javascript">
var area = {'Mongkok': 1001,'Wan Chai': 1002, 'Sai Kung' : 1003};
</script>
<select id="area">
<option value='0'>choose an area</option>
<option value='1001'>Mong kok</option>
<option value='1002'>Wan Chai</option>
<option value='1003'>Sai Kung</option>
</select>
<input id='address' type='text' />

When I enter text (16 Argyle Street, Mongkok) the text box #address; How to use jquery auto select Mongkok option(value:1001) in #area

According to the address text matching area

thanks a lot..

eg

//when #address's value='16 Argyle Street, Mongkok' 

//addres var match Mongkok
//then <option value="1001" selected="selected">Mong kok</option>
A: 

Try this

$("#address").keyup(function(){
        var val = this.value.replace(/ /g,"");
        $.each($("#area option"), function(){
            var optVal = $(this).text().replace(/ /g,"");   
            if(optVal == val){
                (this).attr("selected","selected");
            }
        });
    });
Chinmayee
@Chinmayee nice script,Thank you
LNXA
If you want entered address as substring, you can change if condition to if(val.indexOf(optVal) != -1)
Chinmayee
You should add a `return false` so that you don't loop over every element once you selected one.
Felix Kling
Yes you are right. Thanks.
Chinmayee
A: 

Updated version:

$("#address").keyup(function() {
    var adress = $(this).val();
    for (var v in area) {
        if (adress.indexOf(v) >= 0) {
            $("#area").val(area[v]);
            break;
        }
    }
});

Working example

Note that this probably does not scale very well. It has to loop over every element in area and if you have a lot, this might become a problem. Also, you might want to add some kind of timeout, so that the code is only run after the user has not typed some text for a short time. See this question.

Felix Kling
when #address's value='16 Argyle Street, Mongkok' ,addres var match Mongkok then <option value="1001" selected="selected">Mong kok</option>
LNXA
@LNXA: oh sorry...
Felix Kling
Thanks for your help
LNXA
@LNXA: See my updated version.
Felix Kling
@Felix Kling unbelievable script,Thank you!
LNXA
A: 

He wants to search for a matching select option when the address is being entered.

Maybe someone can get my jsfiddle example to work. I'm not exactly sure how to check if one string is within another string. http://jsfiddle.net/gSBWw/

Keyo