Skip to content Skip to sidebar Skip to footer

Getting The Parent Div Of A Button

I am trying to get the parent div of the 'button1' and enable all the inputs in that div (I currently have them disabled'

Solution 1:

I'd do it a little different (without the setTimeout):

function myFunc(elm){
   for( var inputs = elm.parentNode.querySelectorAll('input[type="text"]')
      ,          L = inputs.length
      ; L--
      ; inputs[L].disabled = false  //enable inputs
      ); //end loop
}
<div id="wrapper">
  <div id="gameInfo">
    <input type="text" ID="gameTitle" disabled="disabled" />
    <input type="text" ID="gameType" disabled="disabled" />
    <input type="text" ID="gameprice" disabled="disabled" />
    <input type="button" id="button1" value="enable" onclick="myFunc(this)" />
  </div>
</div>

Alternative for browsers that don't support querySelectorAll (and optionally support disabled):

function myFunc(elm){
   for( var inputs = elm.parentNode.getElementsByTagName('input')
      ,          L = inputs.length
      ; L--
      ; inputs[L].type.toLowerCase()==='text' && (inputs[L].disabled = false)
      ); //end loop
}
<div id="wrapper">
  <div id="gameInfo">
    <input type="text" ID="gameTitle" disabled="disabled" />
    <input type="text" ID="gameType" disabled="disabled" />
    <input type="text" ID="gameprice" disabled="disabled" />
    <input type="button" id="button1" value="enable" onclick="myFunc(this)" />
  </div>
</div>

The idea of both the above functions is that you pass the element that is clicked (the button) to the function: onclick="myFunc(this)".
This will also work for multiple divs ('rows') without need to hardcode the id.

This should get you started!


Solution 2:

You just aren't calling myFunc correctly - you need brackets to actually call it:

<input type="button" id="button1" value="enable" onClick="myFunc()"/>

function myFunc() {
  setTimeout(function() {
    var inputs = document.getElementById("button1").parentNode.querySelectorAll('input[type="text"]');
    [].forEach.call(inputs, function(input) {
      input.disabled = false;
    });
  });
}
<input type="text" disabled="disabled" value="another box" />
<div id="wrapper">
  <input type="text" disabled="disabled" value="ignore me" />
  <div id="gameInfo">
    <input type="text" ID="gameTitle" disabled="disabled" />
    <input type="text" ID="gameType" disabled="disabled" />
    <input type="text" ID="gameprice" disabled="disabled" />
    <input type="button" id="button1" value="enable" onClick="myFunc()" />
  </div>
</div>

Solution 3:

If you were using jquery for DOM traversal, you could do the following:

 $('#<%= button1.ClientID %>').on('click', function() {
      $(this).parent().find('input[type=text]').removeAttr('disabled');
 });

Solution 4:

You aren't calling the function the right way, you should use braces:

onClick="myFunc()"

Post a Comment for "Getting The Parent Div Of A Button"