【问题标题】:HTML Form Input with Radio and Text - Selection带有单选和文本的 HTML 表单输入 - 选择
【发布时间】:2012-03-05 17:25:15
【问题描述】:

我在 HTML 表单中的单选按钮上附加了一个文本输入区域,如下所示:

    <fieldset class="w100">
                        <div class="rowElem align-left">
                          <input type="radio" id="plan_height" name="plan_height" value="standard6'2&quot;" checked >
                          <label>Standard 6'2"</label>
                        </div>
                        <div class="rowElem align-left">
                          <input type="radio" id="other_text" name="plan_height" value="Other height" onclick="document.getElementById('other_height').focus();" >
                          <input type="text" id="other_height" name="plan_height" value="Enter custom height" onFocus="if(this.value=='Enter custom height') this.value='';" onBlur="if(this.value=='') this.value='Enter custom height';">
                          <label for="other_text">Other</label>
                        </div>
                       </fieldset>

如果用户选择“其他”的第二个单选选项,我希望文本框自动成为焦点,以便他们输入值。此外,如果用户单击文本框输入值,我希望自动为他们选择单选按钮。

我尝试在表单元素上使用 onBlur 或 onChange 或 onKeyup,但似乎无法正常工作。

【问题讨论】:

  • 你愿意使用 jQuery 吗?
  • 当然可以,但如果可能的话,我想让它更简单,只包含在 onKeyup 或 onChange 表单事件中。
  • 您能展示一下您是如何尝试使用 onBlur/onChange/onKeyup 的吗?另外,你能确认一下第一个遥控器的ID和值吗?
  • 我尝试在 onBlur 事件中添加document.form.other_text.checked = true;,但没有成功
  • 我更新了表单...我现在只需要在用户输入文本/单击文本输入框时选择单选按钮。

标签: javascript forms


【解决方案1】:

你试过onclick事件吗:onclick="document.getElementById('other_height').focus();"

【讨论】:

  • 当单选按钮被点击时,它可以专注于文本字段!!!但是 - 如果用户只是单击文本框,我需要它自动选择单选按钮(与您刚刚给我的代码几乎相反)
【解决方案2】:

看看这个http://jsfiddle.net/tzj6Z/7/

对于跨浏览器支持,您必须像这样添加浏览器检测

if(navigator.userAgent.indexOf('Firefox')>=0) { // Firefox
  focus_event = 'focus';
} else if (navigator.userAgent.indexOf('Safari')) {  // Opera, Safari/Chrome
  focus_event = 'DOMFocusIn';
} else {  // IE
  focus_event = 'onfocusin';
}

【讨论】:

  • 这似乎没有任何作用..?
  • 我需要把 JS 放到我的 JS 文件中吗?或者只是表单中的代码?
  • 如果您有一个外部 js 文件...然后将其包含在其中,或者将其包含在页面脚本标记部分中。此外,最好不要将 javascript 内联包含在标记中,以保持它的清洁和可管理性。
  • 嗯...它在 jsfiddle 中运行良好,但在我的网站上不适合我。我将&lt;script&gt; var other_radio = document.getElementById('other_text'), other_height = document.getElementById('other_height'); other_height.addEventListener('focus',function(){ other_radio.checked = true; }); other_radio.addEventListener('change',function(){ other_height.focus(); }); &lt;/script&gt; 放在文档底部的结束正文标记之前,并设置了onFocus 事件,当我单击文本字段时它不会检查单选按钮。
  • 如果您在 IE 中查看它,那么它将不起作用,因为您必须更改事件名称,即焦点将更改为 onfocus,更改将更改为 onchange
猜你喜欢
  • 2011-08-04
  • 2018-08-27
  • 2011-05-03
  • 1970-01-01
  • 2016-01-30
  • 2011-01-30
  • 2020-12-08
  • 2022-07-02
  • 1970-01-01
相关资源
最近更新 更多