在点击div更改输入值

时间:2017-01-06 11:59:00

标签: jquery html

基本上我尝试做的是当你点击1 div时它会将隐藏值设置为1,如果你点击第2个div则将隐藏值设置为2。

    <input type="hidden" name="amount" value="5">
        <div class="container text-center">
            <div class="col-md-3">
            </div>  
            <?php
                //Fetch products from the database
                $results = $db->query("SELECT * FROM products");
                while($row = $results->fetch_assoc()){
                echo '
                    <div class="col-md-3 product" id="rankid'.$row['id'].'">
                        <h2>'.$row['name'].'</h2>
                        '.$row['pricename'].'<br><br>
                        '.$row['desc'].'<br><br>
                    </div>';
                }
            ?>

继承我的Javascript

document.getElementById("rankid1").onclick = function() {changeAmount1()};
document.getElementById("rankid2").onclick = function() {changeAmount2()};

function changeAmount1() {
    document.getElementById('amount').value = '5';
}
function changeAmount2() {
    document.getElementById('amount').value = '20';
}

What It looks like

2 个答案:

答案 0 :(得分:0)

<input type="hidden" name="amount" value="5">  <-- has a name
document.getElementById('amount').value  <-- looking for an element with an id.

名称不等于id。

所以要么将id="amount"添加到输入

或按名称引用它。

document.formName.amount.value

还要确保在页面上呈现元素后添加事件处理程序。

document.getElementById("rankid1").onclick = function() {
  changeAmount1()
};
document.getElementById("rankid2").onclick = function() {
  changeAmount2()
};

function changeAmount1() {
  document.getElementById('amount').value = '5';
}

function changeAmount2() {
  document.getElementById('amount').value = '20';
}
.product {
  border: 1px solid black;
  width: 40%;
  display: inline-block;
  }
<input type="text" name="amount" id="amount" value="5">
<div class="container text-center">
  <div class="col-md-3">
  </div>
  <div class="col-md-3 product" id="rankid1">
    <h2>1</h2>
    1 abc<br><br>
    1 def<br><br>
  </div>

  <div class="col-md-3 product" id="rankid2">
    <h2>2</h2>
    2 ghi<br><br>
    2 jkl<br><br>
  </div>

答案 1 :(得分:0)

Working Fiddle

 $('div').on('click', function() {
   if ($(this).next('div').length === 1)
   // Set hidden field value 1
   else
   // Set hidden field value 2
 });