문제

I'm trying to fill a form input when a checkbox is checked using JQuery. Here's what I've tried:

HTML:

<input type="checkbox" class="reply_author_check"> I'm the CEO, bitch

<div class="form-group" class="reply_username">
<div class="col-sm-3">
<input type='text' class="form-control" name='username' placeholder="What's your name?">
</div>
</div>

Ideally, when the checkbox is checked, the form input would be filled with "I'm the CEO, bitch" and become locked.

JQuery:

if($('.reply_author_check').prop('checked')){

$('.reply_username').html(

    "<div class='form-group' class='reply_username'>
    <div class='col-sm-3'>
    <input type='text' class='form-control' name='username' disabled>"+ "I'm the CEO, bitch"
    </div>
    </div>"
    );

};

However it's not working and I can't get error msgs from firebug. Any advice would be hugely helpful.

도움이 되었습니까?

해결책 2

Don't overwrite the HTML of the DIV, just modify the input element as needed.

$(".reply_author_check").click(function() {
    if (this.checked) {
        $(".form-control").val("I'm the CEO, bitch").prop("disabled", true);
    } else {
        $(".form-control").removeProp("disabled");
    }
});

다른 팁

Try with this:

  $('.reply_author_check').on('change', function() {
    if  ($('.reply_author_check').is(':checked')) {
     $('input.reply_username').val('I\'m the CEO, bitch')
   });

You already have all that HTML ready, so why overwrite it with the same stuff? Grab the input by it's name attribute and alter what you wish.

if($('.reply_author_check').prop('checked')){
    var $input = $('input[name="username"]'); //cache the jQuery object
    $input.prop("disabled",true);
    $input.prop("placeholder","");
    $input.val("I'm the CEO, bitch.");
}

You're problem is you have two class attributes on your .reply_username div. You can only have one, you need to separate multiple classes by spaces. That will make your code work, but a better way to accomplish this would be this:

$('.reply_author_check').change(function () {
    if ($(this).is(':checked')) {
        $('input[name="username"]').prop('disabled', true).val("I'm the CEO, bitch"); 
    } else {
        $('input[name="username"]').prop('disabled', false).val('');
    }
});

jsfiddle here.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top