0

I have a web application which replaces content. This content has jquery ui check buttons. When I replace the content if a button already exists then don't add it again:

if(!$('label[for=checkWeekM]').hasClass('ui-button'))
      $('.checkWeek').button();

If I push the button (its state is checked) and if I replace the content, the button starts locked until the same content is replaced again.

I use Backbone.js to replace the content

jsfiddle

How can I unlock the check button?

4

2 に答える 2

3

You are duplicating id attributes and that leads to bad HTML, bad HTML leads to frustration, frustration leads to anger, etc.

You have this in your template that you have hidden inside a <div>:

<input type="checkbox" class="checkWeek" id="checkWeekM" />
<label for="checkWeekM">L</label>

Then you insert that same HTML into your .content-central. Now you have two elements in your page with the same id attribute and two <label> elements pointing to them. When you add the jQuery-UI button wrapper, you end up with a slightly modified version of your <label> as the visible element for your checkbox; but, that <label> will be associated with two DOM elements through the for attribute and everything falls apart.

The solution is to stop using a <div> to store your templates. If you use a <script> instead, the browser won't parse the content as HTML and you won't have duplicate id attributes. Something like this:

<script id="template-central-home" type="text/x-template">
    <div data-template-name="">
        <input type="checkbox" class="checkWeek" id="checkWeekM" />
        <label for="checkWeekM">L</label>
    </div>
</script>

and then this to access the HTML:

content.view = new ContentView({
    model: content,
    template: $('#template-' + template_name).html()
});

Demo: http://jsfiddle.net/ambiguous/qffsm/

There are two quick lessons here:

  1. Having valid HTML is quite important.
  2. Don't store templates in hidden <div>s, store them in <script>s with a type attribute other than text/html so that browser won't try to interpret them as HTML.
于 2013-02-07T05:46:40.017 に答える
0

I took a detailed look at your fiddle after you mentioned this problem. The solution I suggested here was more like a quick fix.

If you want to follow the right thing to avoid long term problems and side effects you should consider what is mentioned here. This way your problem is solved and there are no other bugs.

于 2013-02-07T05:39:20.010 に答える