Skip to content
Advertisement

How can I disable all the duplicate Texbox having same Id using Javascript?

I have different number of TextBoxes with same Id.I am compelled to use same Id.I Do not have permission to use Class. I need to enable only the first TextBox and disable the rest.

Here is my code with 3 different TextBox :

<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">

<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">

<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">

I need output like this , I need to enable the first one and disable the rest :

<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">

<input type="Textbox" id="abc" data-templatefieldid="12" disabled="disabled" required="required" placeholder="Son">

<input type="Textbox" id="abc" data-templatefieldid="12" disabled="disabled" required="required" placeholder="Son">

Advertisement

Answer

ID‘s must be unique in an HTML page.

That being said, if there is no other option for you because your company has a set of stupid norms, then you can use this. But using same id for different elements is not recommended.

jQuery solution.

$(function() {
  $('[id=abc]').slice(1).prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">
<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">
<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">

JavaScript solution:

ele = document.querySelectorAll('[id="abc"]');
for (i = 0; i < ele.length; i++){
  ele[i].disabled = true;
}
<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">
<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">
<input type="Textbox" id="abc" data-templatefieldid="12" required="required" placeholder="Son">
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement