Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

use state of checkbox to [en|dis]able text input

Status
Not open for further replies.

Wolfie7873

Technical User
Jan 15, 2004
94
US
I'm trying to enable a text input if a checkbox is checked. The default state on page load should be disabled.

Here is my code

Code:
<script type='text/javascript'>
document.getElementById('count_box').disabled = true;

function chgCountBox(str)
{
if (str=='true')
  {
  document.getElementById("count_box").disabled=false;
  document.getElementById("countprompt").innerHTML="How Many?";
  }
if (str=='false')
    {
    document.getElementById("count_box").disabled=true;
    document.getElementById("countprompt").innerHTML="";
    }
}
</script>

</head>
<body>

<form>
<input type="checkbox" id="cbox1" onchange="chgCountBox(this.checked)">
Create Correlation(s):
<span id="countprompt"></span>
<input type='text' id='count_box'>
</form>

When I render the page, the textbox is enabled and changing the state of the checkbox has no effect.

What gives?
 
Short script, but practically problem every a couple of lines.

[1] >document.getElementById('count_box').disabled = true;
This is a barely exposed line in script sector. Either you put the line below the element with id count_box in tbe body or you have to put it inside a window.onload handler. The latter approach looks like this.
[tt] window.onload=function() {document.getElementById('count_box').disabled = true; };[/tt]

[2] Pay attention to the data types, string and boolean.
>if (str=='true')
>if (str=='false')
>onchange="chgCountBox(this.checked)
Either ways.
[2.1]
[tt]if (str==true)
if (str==false)
onchange="chgCountBox(this.checked)[/tt]
[2.1.1]
[tt]if (str)
if (!str)
onchange="chgCountBox(this.checked)[/tt]
[2.2]
[tt]if (str.toString()=='true')
if (str.toString()=='false')
onchange="chgCountBox(this.checked)[/tt]
[2.3]
[tt]if (str=='true')
if (str=='false')
onchange="chgCountBox(this.checked.toString())[/tt]

[3] onchange will be executed only after the control lost focus. Use onclick in this case would lead to a much better user's surfing experience.
><input type="checkbox" id="cbox1" onchange="chgCountBox(this.checked)">
[tt]<input type="checkbox" id="cbox1" onclick="chgCountBox(this.checked)">[/tt]
 
Thanks, Tsuji - I'm pretty new to JS. I feel like a dope over the datatypes -- I've been using perl too much!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top