I'm creating text boxes and radio buttons dynamically and fields are fetched from database. For my task, I need to disable some text boxes by ticking of radio buttons using javascript. However radio buttons are visible always. For an example, If i click first radio button, it should disable 2nd and 3rd of text boxes , not radio button.
How could i achieve this using javascript?
HTML:
<input type='radio' name='r1' value="NE" />
<input type='radio' name='r1' value="NW" />
<input type='radio' name='r1' value="SE" />
<input type='textbox' id="txt1" name='txt1' value="NE"/>
<input type='textbox' id="txt2" name='txt2' value="NW"/>
<input type='textbox' id="txt3" name='txt3' value="SE"/>
JavaScript:
// First assign onclick handler to your radio buttons
// Note - this is just a demo. You should encapsulate
// this loop in a page onload initialization method.
var radios = document.forms[0].elements["r1"];
for(var i = 0; i < radios.length; i++) {
radios[i].onclick = DisableTextBoxes;
}
// Disable textboxes based on respective radio click
function DisableTextBoxes(){
var textboxes = [
document.getElementById("txt1"),
document.getElementById("txt2"),
document.getElementById("txt3")]
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
textboxes[i].disabled = false;
} else {
textboxes[i].disabled = true;
}
}
}
A more thorough explanation can be found here .
If you're using jQuery, you can use the :text
or input[type=text]
selectors to choose text boxes for manipulation.
For example, to disable the first text box that immediately follows a checkbox:
<input type="checkbox" name="check1" id="check1" value="Yes">
<input type="text" id="txt1" name="txt1">
<script type="javascript">
$("#check1").change(function(){
if($(this).is(':checked'))
$(this).next(":text").attr('disabled','true');
else
$(this).next(":text").removeAttr('disabled');
});
</script>
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.