Sahitya Sahitya - 6 months ago 9
HTML Question

Disable/Enable a text box based on radio/select option selected Javascript

I am trying to disable an input field in HTML if a radio button has a particular value. I have used Javascript functions for the same.

CODE SNIPPET 1 : (HTML RADIO BUTTON)

<div class="element-radio">
<label class="title">Children</label>
<div class="column column2">
<label>
<input type="radio" name="children" value="Yes" onChange="findselected()"/>
<span>Yes</span>
</label>
</div>
<span class="clearfix"></span>

<div class="column column2">
<label>
<input type="radio" name="children" value="No" checked="checked" onChange="findselected()"/>
<span>No</span>
</label>
</div>
<span class="clearfix"></span>
</div>

<div class="element-number">
<label class="title">No of children</label>
<div class="item-cont">
<input class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />
<span class="icon-place"></span>
</div>
</div>


CODE SNIPPET 2 : (JAVASCRIPT FUNCTION)

<script type="text/javascript">
function findselected() {
if (document.form.children.value == 'No') {
document.form.no_children.disabled=true;
// return false; // not sure this line is needed
} else {
document.form.no_children.disabled=false;
// return false; // not sure this line is needed
}
}
</script>


This does not work in the required way. Is there a better way to go about doing the same? I'm fairly new to Javascript so I wouldn't be able to implement a complicated code.

Answer

Update your script with the following code:

function findselected() { 
    var result = document.querySelector('input[name="children"]:checked').value;
    if(result=="Yes"){

        document.getElementById("inputtext").setAttribute('disabled', true);
    }
    else{
        document.getElementById("inputtext").removeAttribute('disabled');
    }
}

And add id attribute in your input control as id="inputtext".

<input id="inputtext" class="large" type="text" min="0" max="100" name="no_children" placeholder="If YES, Number of Children?" value="<?php echo $no_children?>" />
Comments