预填充文本字段基于链接选择

时间:2017-08-02 19:28:06

标签: javascript

拥有一个带有空文本字段的表单。上面将是4个html按钮。当选择前三个中的任何一个时,它应该使用该值预填充空输入并将焦点放在该字段上。例如,如果我点击$ 10,它应该填充值为$ 10的空字段并将焦点带到该字段。如果我然后单击$ 100,它将用$ 100替换字段值并将焦点带到该字段。

最后,如果选择其他,它应该将焦点带到该字段,但是如果该字段有值,则将该字段留空或使其为空。

使用jQuery找到了一些选项但是却试图用javascript找到一个干净的选项。否则可以在必要时添加jQuery。

我完全掌控了班级,ids等。假设该选项将涉及onclick。在SO上找到了几个选项,但它们似乎比必要的要复杂得多。

<a href="" class="" id="" />$1</a>
<a href="" class="" id="" />$10</a>
<a href="" class="" id="" />$100</a>
<a href="" class="" id="" />Other</a>

<form action="" method="post">
  <input type="text" name="" value="">
  <input type="submit" name="submit">
</form>

2 个答案:

答案 0 :(得分:1)

这是一种简单的JavaScript方式:

var linx = document.querySelectorAll("a")
for (i = 0; i < linx.length; i++) {
  linx[i].addEventListener('click', function(e) {
    e.preventDefault();
    document.querySelector('[type="text"]').value = (this.innerHTML != 'Other') ? this.innerHTML : '';
    document.querySelector('[type="text"]').focus()
  });
}
<a href="" class="" id="">$1</a>
<a href="" class="" id="">$10</a>
<a href="" class="" id="">$100</a>
<a href="" class="" id="">Other</a>

<form action="" method="post">
  <input type="text" name="" value="">
  <input type="submit" name="submit">
</form>

答案 1 :(得分:0)

我发布了一个jQuery解决方案(为了简单起见),虽然这个更改对于no-jQuery来说是微不足道的(但需要更多的按键

&#13;
&#13;
$('.predefined').on('click', function(e){
  e.preventDefault();
  var value = $(this).data('value');
  
  $('.predefined-target').val(value).focus();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a href="#" class="predefined" data-value="1"/>$1</a>
<a href="#" class="predefined" data-value="10" />$10</a>
<a href="#" class="predefined" data-value="100" />$100</a>
<a href="#" class="predefined" data-value="" />Other</a>

<form action="" method="post">
  <input type="text" class="predefined-target" name="whatever" value="">
  <input type="submit">
</form>
&#13;
&#13;
&#13;

相关问题