简体   繁体   中英

checkbox to disable/enable input

I am using js to , onclick of a checkbox, it enables or disables text input.

It works, until I put it into a live form with google jquery api.

Weird but.. must be a conflict somewhere.

The form element is: ( code isnt adding to this post properly )

<input type="checkbox" name="others" onclick="enable_text(this.checked)" class="medium" /></div>

Name on credit card if different from above

The js is:

function enable_text(status)
{
status=!status;
document.form1.other_name.disabled = status;
}

What am I doing wrong, I have used body onload handler.

<body onload=enable_text(false);>

JS FIDDLE : http://www.jsfiddle.net/ozzy/H8VPY/4/

Here, a jQuery solution:

$("input:checkbox").click(function() {
    $("input:text").attr("disabled", !this.checked); 
});

Just replace these generic selectors with your more specific ones.

In addition to this code, you will probably also want to make the text-box disabled (initially).

<input type="text" disabled="disabled" />

Working demo: http://www.jsfiddle.net/H8VPY/11/

There are several problems in your jsfiddle demo.

  • The <script> and the comment there around should be removed.
  • A <form name="form1"> is missing which caused document.form1 to return nothing.
  • The onLoad option on left menu should be a no wrap (head) since it's just a function.

Updated demo: http://www.jsfiddle.net/PPZYm/

Live Example

function enable_text(status) {
    status = (status) ? false : true; //convert status boolean to text 'disabled'
    document.form1.other_name.disabled = status;
}

Note

You also need to wrap your div in the jsfiddle example with a <form> tag with the name form1 for it to properly work

<div class="controlset-pad">
    <input type="checkbox" name="others" onclick="enable_text(this.checked)" class="medium" />
</div>
<form name="form1">
    <div class="field4">
        <label>Name on credit card if different from above</label><input type="text" name="other_name" class="medium" disabled="disabled" />
    </div>
</form>

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