简体   繁体   中英

jQuery, text match defaults select

Using: Rails and jQuery

I have a form with a Url textbox input in which a user can put a url such as:

http://www.webshop.com/article/123

url is an attribute of @product.

In the same form I also have a dropdown populated with stores (Store.all). The store has an attribute store.short_url that could be "www.webshop.com".

I want to use jQuery so that when a user types in http://www.webshop.com/article/123 in the url-textbox I want to compare that with the Store objects and see if that store is in the database which short_url matches the domain name and if so, default that Store in the dropdown.

The string matching should not be a problem but how do I handle this in jQuery?

  1. Fill out the url field
  2. When text field is out of focus do:
  3. Find Store with matching url
  4. Set that store as default

Any help would be much appreciated!

basic gist:

$(document).ready(function(){
    $('#url_input').change(function(){
    var urlPattern = /(http|ftp|https):\/\/([\w-]+(\.[\w-]+)+)([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/
        if(urlPattern.test($(this).val())){
            alert('hurray');
            url = ($(this).val().match(urlPattern))[2].toLowerCase();
            $('option[value="'+url+'"]','#available_types').each(function(){$(this).attr('selected',true)});
        }
    });
    });
    ​

http://jsfiddle.net/sScma/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM