【问题标题】:JavaScript OnClick Select Tag Doesn't Work on Mobile BrowserJavaScript OnClick 选择标签在移动浏览器上不起作用
【发布时间】:2013-01-18 21:06:55
【问题描述】:

我有这样的html和js(带有jquery)代码:

<label>Nationality</label>
<select name="user_nationality" class="input">
    <option value="1" selected onclick="$('#userphonearea').val('+62');">Indonesia</option>
    <optgroup label="Other Countries">
      <option value="2" onclick="$('#userphonearea').val('+44');">United Kingdom</option>
      <option value="3" onclick="$('#userphonearea').val('+1');">United States of America</option>
    </optgroup>
</select>

<label>Phone Number</label>
<input type="text" name="user_phone_area" id="userphonearea" maxlength="5" size="5" value="" placeholder="+" required />
<input type="text" name="user_phone_number" maxlength="30" size="10" required />

如果我选择 user_nationality,我想自动输入 user_phone_area。 我使用了onclick,它适用于桌面浏览器。但它不适用于 android 或 iphone 等移动浏览器。

我尝试使用 OnSelect 更改 OnClick,但它在桌面和移动设备上都不起作用

<select name="user_nationality" class="input">
    <option value="1" selected onselect="$('#userphonearea').val('+62');">Indonesia</option>
    <optgroup label="Other Countries">
      <option value="2" onselect="$('#userphonearea').val('+44');">United Kingdom</option>
      <option value="3" onselect="$('#userphonearea').val('+1');">United States of America</option>
    </optgroup>
</select>

【问题讨论】:

  • 这在许多浏览器中不起作用,您应该将事件处理程序附加到 select 本身而不是 options。

标签: javascript jquery select onclick onselect


【解决方案1】:

找到我自己问题的答案

<select name="user_nationality" id="changecountry" class="input">
<option value="1" phonecode="+62">Indonesia</option>
<optgroup label="Other Countries">
    <option value="2" phonecode="+44">United Kingdom</option>
    <option value="3" phonecode="+1">United States of America</option>
</optgroup>

<script>
$('#changecountry').on('change', function() {
    var phonecode = $('option:selected', this).attr('phonecode');
    $('#userphonearea').val(phonecode);
});
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2021-11-13
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多