Forum Moderators: open

Message Too Old, No Replies

Checkbox adds value to text input

Checkbox adds value to text input

         

jcolgate

3:53 am on Feb 12, 2009 (gmt 0)

10+ Year Member



Thank you to Webmaster World for past assistance as I grow and learn.

I am looking to add a value to a text input when someone clicks a checkbox. I currently can disable the textbox but I wanted to add a value to it first so when the form is processed it can pass the value along. My hope is the have the text box hold the value called "Fill".

<input type="checkbox" onclick="document.getElementById('thebox').disabled=(this.checked)?1:0">
<input type="textbox" id="thebox">

The text box will normally be open to anything they want to type. But if they click the check box we force the value and lock it. Make sense?

Thanks,
J Colgate

Lang

5:19 am on Feb 12, 2009 (gmt 0)

10+ Year Member



<input type="checkbox" onclick="document.getElementById('thebox').enabled=(this.checked)?'disabled':'enabled';">

Try that.

[edited by: Lang at 5:19 am (utc) on Feb. 12, 2009]

jcolgate

12:15 pm on Feb 12, 2009 (gmt 0)

10+ Year Member



Thanks

Both seem to work fine locking the text field. But I just can't find a way to force a word into the box before it locks.

The process would be:
1. Check box
2. Make the text box say "****".
3. Then lock the text field.

Thanks

JC

Fotiman

6:34 pm on Feb 12, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Disabled input elements will never be submitted with the form submission. Instead, you would need to set the 'readonly' attribute. Also, you should consider keeping JavaScript out of your HTML markup (that is, don't use "onclick" attributes for event handlers).

<script type="text/javascript">
window.onload = function () {
// Attach event handlers
var cb = document.getElementById('theCheckBox');
var thebox = document.getElementById('thebox');
cb.onclick = function () {
if (cb.checked) {
thebox.value = '****';
}
thebox.readonly = cb.checked;
};
};
</script>

And then your markup:

<input type="checkbox" id="theCheckBox">
<input type="text" id="thebox">

Note, you had the type as "textbox", which is not an actual type (should be "text").

jcolgate

9:03 pm on Feb 12, 2009 (gmt 0)

10+ Year Member



Works like a charm! Yeah, I saw the textbox vs text error too. Thanks.

I also like the idea of taking the JavaScript out of the HTML markup. Much cleaner.

Thanks,
JC