Im trying to Enable/Disable read-only property of textboxes in a colum with the same ID by clicking only one button but my code doesnt seem to work. Im still not familiar on how PHP works
code in PHP:
<input type='text' name='nTotal[$i]' value='$row->Total' size='5' readonly='true' id='ntotal[$i]'>
code in javascript:
var a = document.getElementById(ntotal); //ntotal[$i] is the ID name of textbox in PHP
for (var i=0;i<a.length;i++){
if (a[i].readonly == 'false' ) {
a[i].readonly = 'true';
}
else if(a[i].readonly == 'true'){
a[i].readonly = 'false';
}
}
}
Can anyone give me a hint on why it doesnt work? Ive tried using name instead of ID but same outcome.
Try to fix naming convention (ID must be unique and not only numbers) and use the getAttribute, setAttribute and remov eAttribute functions.
<input type='text' name='nTotal' value='1' size='5' readonly='readonly' id='text_1'>
<input type='text' name='nTotal' value='2' size='5' id='text_2'>
var a = document.getElementsByName("nTotal");
for (var i=0;i<a.length;i++){
isreadonly = a[i].getAttribute("readonly");
if (isreadonly) {
a[i].removeAttribute("readonly");
}
else
{
a[i].setAttribute("readonly", "true");
}
}
Just have set up a working demo at: http://jsfiddle.net/wXbzq/
Or even better, use jQuery ( http://jquery.com ) ... you'll love it !
To disable in jQuery:
$('nTotal').removeAttr('readonly');
To enable in jQuery:
$('nTotal').attr('readonly', true);
Try:
var arr = document.querySelectorAll('[id="'+ntotal+'"]');
for(var i=0;i<arr.length;i++){
if(arr[i].getAttribute('readonly')=='readonly')
arr[i].removeAttribute('readonly');
else
arr[i].setAttribute('readonly', 'readonly');
}
As others have mentioned, you should use classes and getElementsByClassName
instead of getElementById
as the latter will only return at most one element, based on the spec that says ids are unique. Also, the readOnly
(case sensitive, with a capital O) property is boolean, so comparing it to a string won't work.
var a = document.getElementsByClassName(ntotal);
for (var i=0;i<a.length;i++) {
a[i].readOnly = !a[i].readOnly;
}
You should use properties instead of attributes like every other answer suggests. Much terser and more predictable. The readonly
attribute is boolean, so its presence alone is what matters, not the value.