选择文本输入上的单选按钮

时间:2020-03-13 10:33:38

标签: javascript html forms radio-button

访问者以另一种输入形式输入文本时,是否可以自动选择单选按钮?我已经搜索过了,但是没有成功。

我有这个带有3个单选按钮的表单,它们允许用户选择大小,最后一个单选按钮用于自定义大小(宽度和高度)。在最后一个单选按钮下,有用于输入自定义高度和宽度的文本输入。

<form action="#" method="post">
   <label for="original-size">Original
       <input type="radio" id="original_size" name="size" value="original" checked="checked">
   </label>
   <label for="medium-size">Medium
        <input type="radio" id="medium-size" name="size" value="medium">
    </label>                   

   <label for="custom-size">Custom
         <input type="radio" id="custom-size" name="size" value="custom">
   </label>

        <input id="custom-width" type="number" name="custom-width" placeholder="Custom width">
         <label for="custom-width">custom width</label>
           and 
          <input id="custom-height" type="number" name="custom-height" placeholder="Custom height">
          <label for="custom-height">custom height</label>
          <br>
          <button name="submit" type="submit">Submit</button>
          </form>

如果用户单击自定义宽度或自定义高度的文本输入,如何选择自定义尺寸的单选输入?是否有没有Java脚本的选项,如果没有,那么使用Java脚本的小代码就可以了(我不使用jQuery)?

1 个答案:

答案 0 :(得分:1)

设法挖掘出这个,这是您要找的东西吗?

<form>
<p>Original: <input type="text"></p>
<p>Medium: <input type="text"></p>

<div id="customWrapper">
  <p>Custom: <input type="radio" id="customSize"></p>
  <p>Custom Width: <input type="text"></p> 
  <p>Custom Height: <input type="text"> </p> 
</div>
</form>
const div = document.getElementById('customWrapper');

// When the custom width or custom height are clicked on
div.addEventListener('focus', (event) => {
  document.getElementById('customSize').checked = true;   
}, true);

// When clicked somewhere out of the form
div.addEventListener('blur', (event) => {
  document.getElementById('customSize').checked = false;    
}, true);

https://jsfiddle.net/mLvt9ubz/

它基本上会在div内搜索任何输入,当事件发生变化然后发生某些事情时。 在这种情况下,标识为ID的单选按钮将选择属性。

相关问题