简体   繁体   中英

jQuery click or touchstart event is not working on mobile

I am using intl-tel-input to get peoples phone code and country. When they select the flag and code I have some jQuery with gets the country and code separately and populates hidden fields...

Here is the entire object which handles these operations:

var telInput = {
    init: function(){
        this.setTelInput();
        this.cacheDOM();
        this.bindEvents();
    },
    cacheDOM: function(){
        this.$countryCode = $('input[name=country_code]');
        this.$countryName = $('input[name=country_name]');
        this.$country     = $('.country');
    },
    bindEvents: function(){
        this.$country.on('click', this.getTelInput.bind(this));
    },
    setTelInput: function(){
        $('input[name=phone]').intlTelInput({
            preferredCountries: [
                'gb'
            ],
        });
    },
    getTelInput: function(e){
        var el          = $(e.target).closest('.country');
        var countryCode = el.attr('data-dial-code');
        var countryName = el.find('.country-name').text();
        this.$countryCode.val(countryCode);
        this.$countryName.val(countryName);
    },
}

Problem

The problem is the click event in the bindEvents method... the phone picker works but the onclick event is not being triggered to populate my hidden fields.

You need to make sure that you cache the DOM after it has been rendered. Here's a simplified example.

View on jsFiddle

var telInput = {
  init: function(){
    this.cacheDOM();
    this.bindEvents();
  },
  cacheDOM: function() {
    this.$country = $('.country');
  },
  bindEvents: function() {
    this.$country.on('click', function() {
      // console.log('Triggered');
    });
  }
}

$(document).ready(function() {
  telInput.init();
});

Also, plugin's event countrychange could be useful in your case.

$("#country-select-element").on("countrychange", function(e, countryData) {
    // do something with countryData
});

I would also suggest you to have a look at the public methods . It has some useful methods that you could use to achieve the same result.

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