在click to div上添加不同的值来输入

时间:2016-09-23 08:52:55

标签: javascript jquery input onclick addeventlistener

如何根据金额客户端点击将值添加到输入字段?对于每个具有不同金额的div,应该输入50,100,200,500值来输入字段onclick事件。我尝试用纯js实现。它也可能在jquery上

 <form>
 <div class="form-row">
   <label>Donate</label>
      <div class="doner-prices">50</div>
      <div class="doner-prices">100</div>
      <div class="doner-prices">200</div>
      <div class="doner-prices">500kr</div>
  </div>
 <fieldset class="form-row">
    <div class="form-col doner-price">
       <label for="donate-price">
         eller angiv dit eget
        <input type="text" id="donate-price" name="name"   pattern="\d+" value="" required>

        </label>
    </div>
    </fieldset>
   </form>   

   document.addEventListener("DOMContentLoaded", function () {
var amount_list = document.querySelectorAll('.form-row .doner-      prices'); //node-list
var amount_array = [].slice.call(document.querySelectorAll(".form-row   .doner-prices")); //node-list to array
var donerForm = document.getElementById('doner-hidden');
var inputDonateField = document.getElementById('donate-price');
var inputNumber = /^[0-9]+$/;
var onClickFormVisible = function () {
    donerForm.style.display = "block";
};
var onInputTypeNumber = function () {
    if (inputNumber.test(inputDonateField.value)) {
        donerForm.style.display = "block";
    } else {
        return false;
    }
};
//onclick event for each amount images
var amoutn_array = amount_array.map(function (e) {
    return e.addEventListener('click', onClickFormVisible, false);
});
//input event only if value === number
inputDonateField.addEventListener("keyup", onInputTypeNumber, false);
});

1 个答案:

答案 0 :(得分:2)

请使用以下代码来满足您的要求。

$(".doner-prices").click(function(){
  $("#donate-price").val($(this).attr("data-amount"));
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
 <div class="form-row">
   <label>Donate</label>
      <div data-amount="50" class="doner-prices">50</div>
      <div data-amount="100" class="doner-prices">100</div>
      <div data-amount="200" class="doner-prices">200</div>
      <div data-amount="500kr" class="doner-prices">500kr</div>
  </div>
 <fieldset class="form-row">
    <div class="form-col doner-price">
       <label for="donate-price">
         eller angiv dit eget
        <input type="text" id="donate-price" name="name"   pattern="\d+" value="" required>

        </label>
    </div>
    </fieldset>
   </form>