How can I select an element by name with jQuery?

前端 未结 14 2525
迷失自我
迷失自我 2020-11-22 05:13

Have a table column I\'m trying to expand and hide:

jQuery seems to hide the td elements when I select it by class but not by element\'s name.

<
相关标签:
14条回答
  • 2020-11-22 06:03

    You can get the name value from an input field using name element in jQuery by:

    var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD
    var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ 
    console.log(firstname);
    console.log(lastname);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form name="form1" id="form1">
      <input type="text" name="firstname" value="ABCD"/>
      <input type="text" name="lastname" value="XYZ"/>
    </form>

    0 讨论(0)
  • 2020-11-22 06:05

    You could get the array of elements by name the old fashioned way and pass that array to jQuery.

    function toggleByName() {
      var arrChkBox = document.getElementsByName("chName");
      $(arrChkBox).toggle();
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
      <head>
        <title>sandBox</title>
      </head>
      <body>
        <input type="radio" name="chName"/><br />
        <input type="radio" name="chName"/><br />
        <input type="radio" name="chName"/><br />
        <input type="radio" name="chName"/><br />
        <input type="button" onclick="toggleByName();" value="toggle"/>
      </body>
    </html>

    note: the only time you would have a reason to use the "name" attribute should be for checkbox or radio inputs.

    Or you could just add another class to the elements for selection.(This is what I would do)

    function toggleByClass(bolShow) {
      if (bolShow) {
        $(".rowToToggle").show();
      } else {
        $(".rowToToggle").hide();
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
      <head>
        <title>sandBox</title>
      </head>
      <body>
        <table>
          <tr>
            <td>data1</td>
            <td class="bold rowToToggle">data2</td>
          </tr>
          <tr>
            <td>data1</td>
            <td class="bold rowToToggle">data2</td>
          </tr>
          <tr>
            <td>data1</td>
            <td class="bold rowToToggle">data2</td>
          </tr>
        </table>
        <input type="button" onclick="toggleByClass(true);" value="show"/>
        <input type="button" onclick="toggleByClass(false);" value="hide"/>
      </body>
    </html>

    0 讨论(0)
提交回复
热议问题