in jquery can i add a readonly attribute to a input that the only property i can touch is a function?

216 views Asked by At

I have multiple inputs like that (unknow number)

<INPUT id="ctl00_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px" name=ctl00$ContentPlaceHolder$txtSOPurchaserSapID>

there are not on the same page of the app, the id's and the names are dynamically loaded i cannot add a class because there are so many and i don't know the location of all this inputs.

My question is, can i attach a attribute of readonly with jquery to this inputs by the only thing that is the same on each of them onkeydown="return scriptReadonly();

1

There are 1 answers

0
T.J. Crowder On BEST ANSWER

Yes, you can, using an attribute equals selector:

$('input[onkeydown="return scriptReadonly();"]').prop("readonly", true);

Live Example:

function scriptReadonly() { }
$('input[onkeydown="return scriptReadonly();"]').prop("readonly", true);
<INPUT id="ctl00_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px" name=ctl00$ContentPlaceHolder$txtSOPurchaserSapID>
<INPUT id="ctl01_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px" name=ctl01$ContentPlaceHolder$txtSOPurchaserSapID>
<INPUT id="ctl02_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px" name=ctl02$ContentPlaceHolder$txtSOPurchaserSapID>
<INPUT id="ctl03_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return scriptReadonly();" style="WIDTH: 150px" name=ctl03$ContentPlaceHolder$txtSOPurchaserSapID>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

If the text of the onkeydown attribute varies a bit, you can use filter instead to make things more fuzzy:

$('input').filter(function() {
  return $(this).attr("onkeydown").indexOf("scriptReadonly") != -1;
}).prop("readonly", true);

Live Example:

function scriptReadonly() { }
$('input').filter(function() {
  return $(this).attr("onkeydown").indexOf("scriptReadonly") != -1;
}).prop("readonly", true);
<INPUT id="ctl00_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return /*0*/scriptReadonly();" style="WIDTH: 150px" name=ctl00$ContentPlaceHolder$txtSOPurchaserSapID>
<INPUT id="ctl01_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return /*1*/scriptReadonly();" style="WIDTH: 150px" name=ctl01$ContentPlaceHolder$txtSOPurchaserSapID>
<INPUT id="ctl02_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return /*2*/scriptReadonly();" style="WIDTH: 150px" name=ctl02$ContentPlaceHolder$txtSOPurchaserSapID>
<INPUT id="ctl03_ContentPlaceHolder_txtSOPurchaserSapID" onkeydown="return /*3*/scriptReadonly();" style="WIDTH: 150px" name=ctl03$ContentPlaceHolder$txtSOPurchaserSapID>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>