简体   繁体   中英

Onclick set value to input

I want to change the value form input onclick . I've tried it but the input value don't change. Can't find the error. For example when I click on the choice-label the input should get the 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> 

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

is setting the value of the input to the jquery object of the label.

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

Just calling this only pulls in the 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> 

this doesn't contain the value, but rather a whole set of functions and values (to verify, do console.log(this); If you want the value of this, use this instead:

$('#train-niveau').val(this.val()); < Which only applies if a value is set to your choice label.

Inside the click function this is the normal javascript DOM element, it is not a jQuery object. If you want to use .val() you need to convert this to a javascript variable

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM