开发者

Add or remove input field, depending on checkbox, using JavaScript

I have <form> element with some textfields and selections, so I want several new <input type="text"> to be added, when a checkbox is checked and delete them, when it's unchecked.

What is best way to do so?

Is it possible to assign new element to variable or object and then use this variable or object as a reference to delete new elements, because it's supposed several elements to be added at the same time (e.g. <br><inpit type="text">), and I think, that adding them separately is not the best way, so deleting too.

I'm using JQuery as a framework.

<form name="add_subject">

<table cellspacing="1">
    <tr>
        <td class=开发者_如何学Go"key">Day</td>
        <td class="value">
            <select size="7" name="day">
                <option value="1">...</option>
                <option value="2">...</option>
            </select>
        </td>
    </tr>
    <tr>
        <td class="key">Groups</td>
        <td class="value">
            <input type="checkbox" name="sg">
        </td>
    </tr>
    <tr>
        <td class="key">Lecture</td>
        <td class="value">
            <input type="text" size="50" maxlength="50" name="lec1"> /***/
        </td>
    </tr>
    <tr>
        <td class="key">Auditory</td>
        <td class="value">
            <input type="text" size="4" maxlength="4" name="aud1"> /***/
        </td>
    </tr>
</table>

I want to add <br><input type="text"> : <input type="text"> after existing <input> field, where /***/ is given, when the checkbox is cheked and remove, when it's not.

What is the best way?

Thanks!


I would already put the input fields in the markup, for example:

<td class="value">
  <input type="text" size="50" maxlength="50" name="lec1">
  <div class="some-class">
    <input type="text"> : <input type="text">
  </div>
</td>

etc. Then make them hidden by default with this CSS rule:

div.some-class {
    display: none;
}

Now add an event handler to your checkbox, that simply toggles the visibility of your some-class divs whenever the checkbox is clicked:

$(document).ready(function() {
    var visible = false;
    $('input[name="sg"]').click(function() {
        var divs = $('div.some-class'); 
        if (visible) {
            divs.each(function() {
                this.style.display = 'none';
            });
            visible = false;
        }
        else {
            divs.each(function() {
                this.style.display = 'block';
            });
            visible = true;
        }
    });
});


Try to debug the next please if does not work properly (there is an idea):

$( '.value>[type=checkbox]' ).click(
  function()
  {
    if( $( this ).is(':checked') )
    {
      $( 'td.value' ).append( '<br id="myinput"><input type="text"> : <input type="text">' );
    }
    else
    {
      $( '#myinput' ).remove();
    }
  }

)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜