开发者

Checkbox doesn't work in replaced content

So I'm having some weird behaviours in my code and I don't know why.

I'm using uniformjs so, for example a checkbox is like this:

<label>Check Boxes</label>
    <div class="input_group">
      <div class="checker"><span><input style="opacity: 0;" name="option" value="option 1" type="checkbox"></span></div>First option<br>
      <div class="checker"><span><input style="opacity: 0;" name="option" value="option 2" type="checkbox"></span></div>Second option<br>
      <div class="checker"><span><input style="opacity: 0;" name="option" value="option 3" type="checkbox"></span></div>Third option
    </div>

So, when the check option is checked the parent span add the class "checked".

So I was trying to develop a system in which an user is able to add an user and choose between creating a new address for that user or use the company one.

Both address are loaded in diferent divs and the company one get hidden so that's the function I made:

$('input[name="company_addr"]').change(function(){
            var checked = $(this).is(':checked');
            $('input[name="company_addr"]').each(function(){
   开发者_如何转开发             $(this).attr('checked',checked);
                if (checked)
                    $(this).parent().addClass('checked');
                else
                    $(this).parent().removeClass('checked');
            });
            if (checked){
                newAddrContent = block_new.html();
                block_new.html(block_company.html());
            }
            else{
                block_new.html(newAddrContent);
            }
        });

If I delete the last if ... else and unhide the company address I see how both checks change so that part works flawlessly.

However the checkbox within block_new doesn't work anymore but the block_company one does. If I click on the company (which should be hidden) one the other one doesn't uncheck or check but the content is properly replaced.

What could be going on?


You use check() which is one time function. You must bind a live event with .live(event, function) in order for the handler to work on the future elements.

So simply instead of:

$(elements).change();

use

$(elements).live('change', function() {
...
});


The problem is when you create a new input on the fly the change event is not being rebound. You can fix this by using .delegate Docs

$('.input_group').delegate('input[name="company_addr"]', 'change', function(){
             //do your stuff
});

Reasons to use delegate over live


Finally seems to be a bug with uniformjs commented here: github.com/pixelmatrix/uniform/issues/180

If anyone is interested in how I managed to solve this issue, I just changed the method to show, hide the proper divs so, when submitting the form I check which div is hidden and handle the form with this into account.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜