Onclick将值设置为输入

时间:2016-12-12 21:44:47

标签: javascript jquery html

我想更改值表单输入onclick。我试过了,但输入值没有变化。找不到错误。例如,当我点击choice-label时,input应该获得value 5

$('.training-niveau .choice-label').click(function() {
  $('#train-niveau').val(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field training-niveau-icon training-niveau">
  <input id="train-niveau" class="train-niveau" name="train-niveau" value="1" type="radio" aria-required="true" autocomplete="off">
  <li class="choice-line thirst-line">
    <div class="choice-wrapper">
      <div class="choice-label">4</div>
      <div class="choice-line"></div>
      <div class="choice-container">
        <div class="choice-inset"></div>
        <div class="choice-bg"></div>
        <div class="choice-bd"></div>
        <div class="choice-overlay"></div>
      </div>
    </div>
  </li>
</div>

4 个答案:

答案 0 :(得分:3)

$('#train-niveau').val(this);

正在设置标签的jquery对象的输入值。

使用$('#train-niveau').val($(this).text());

答案 1 :(得分:2)

只需拨打this,即可获取document object

$('.training-niveau').on('click', '.choice-label', function() {
  console.log($('#train-niveau').val()); //before
  $('#train-niveau').val($(this).text());
  console.log($('#train-niveau').val()); //after
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field training-niveau-icon training-niveau">
  <input id="train-niveau" class="train-niveau" name="train-niveau" value="1" type="radio" aria-required="true" autocomplete="off">
  <li class="choice-line thirst-line">
    <div class="choice-wrapper">
      <div class="choice-label">4</div>
      <div class="choice-line"></div>
      <div class="choice-container">
        <div class="choice-inset"></div>
        <div class="choice-bg"></div>
        <div class="choice-bd"></div>
        <div class="choice-overlay"></div>
      </div>
    </div>
  </li>
</div>

答案 2 :(得分:1)

this不包含值,而是包含一整套函数和值(要验证,请执行console.log(this);如果您想要此值,请改用:

$('#train-niveau').val(this.val());&lt;仅当您的选择标签设置了值时才适用。

答案 3 :(得分:1)

点击功能this内部是普通的javascript DOM元素,它不是jQuery对象。如果您想使用.val(),则需要将this转换为javascript变量

$('.training-niveau .choice-label').click(function(){
    var $this = $(this);
    $('#train-niveau').val($this.val());  
});