按类名获取输入字段的值,其中类名是变量。

3

我有多组文本字段和提交按钮,每组都有一个 id 用于提交按钮和一个 class 用于文本字段,但每组的 idclass 都不同。因此,我想在按钮点击后将文本字段中输入的值传递给 ajax 函数。

    function update_rate(id){
      // var price = document.getElementsByClassName(id)[0].innerHTML;
    
      var price = document.getElementsByClassName(id);
      console.log(price);
      $.ajax({
        type: "POST",
        url: "update_rate.php", // Name of the php files
        data: {subcategory : id , price: price},
        success: function(res)
          {
            // console.log(html);
            alert(res);
          }
      }); 
    }
first pair:

    <div class="form-group">
        <input type="text" class="form-control" name="a" placeholder="Your task rate excl. taxes">
    </div>
    <button type="submit" id="a" onclick="update_rate(this.id)" class="btn btn-primary">Update</button>



    <div class="form-group">
        <input type="text" class="form-control" name="b" placeholder="Your task rate excl. taxes">
    </div>
    <button type="submit" id="b" onclick="update_rate(this.id)" class="btn btn-primary">Update</button>

但是我无法将文本字段的值存入变量中。


这里id是函数的参数,也是文本字段的类名,那么我该如何获取输入的值呢? - Intern
看看我下面的答案,有更简单的方法。 - Scott Marcus
3个回答

2
这可以通过一种不同且更简单的方式完成。通过id和class连接按钮和文本字段不是可扩展的解决方案,并且需要不断更新代码以保持所有命名的同步。只需获取位于按钮之前的文本字段的值即可。如果修改HTML结构,使文本字段和按钮在同一个div中,将更容易实现。 请参见下面的注释。

// Do your event handling in JavaScript, not with inline HTML event handling attributes
// Also, set up just one handler at a parent level of the items that might trigger
// the event (event delegation).
$(".wrapper").on("click", update_rate);

function update_rate(event){
  // See if it was a submit button that got clicked
  if(event.target.classList.contains("btn")){
    // A submit button was pressed.
    // Locate the nearest ancestor element that has the form-group class
    // (event.target references the actual element that triggered the event).
    let formGroup = event.target.closest(".form-group");
    
    // and then, from there, find the first input (which is the one you want).
    var input = formGroup.querySelector("input");
 
    // The following code is already added to the success handler below and
    // that's where it should be. It's only added here to be able to see the
    // effect since the AJAX call won't run in Stack Overflow. The next 3 lines
    // should be removed when used for real.
    input.classList.add("hidden");
    formGroup.querySelector("button").classList.add("hidden");
    formGroup.querySelector("span").classList.remove("hidden");
    
    console.log(input.value);
    $.ajax({
      type: "POST",
      url: "update_rate.php", // Name of the php files
      // Use the dataset API to extract the custom attribute on the input
      data: {subcategory : input.dataset.category , price: input.value},
      success: function(res){
        alert(res);
        
        // Hide the input and the button and show the updated message
        input.classList.add("hidden");
        formGroup.querySelector("button").classList.add("hidden");
        formGroup.querySelector("span").classList.remove("hidden");
      }
    });
  }
}
.hidden { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="form-group">
    <input type="text" class="form-control" data-category="a" placeholder="Your task rate excl. taxes">
    <button type="submit" class="btn btn-primary">Update</button>
    <span class="hidden">Updated</span>
  </div>

  <div class="form-group">
    <input type="text" class="form-control"  data-category="b" placeholder="Your task rate excl. taxes">
    <button type="submit" class="btn btn-primary">Update</button>
    <span class="hidden">Updated</span>
  </div>
</div>

最终,您没有需要匹配的id或唯一的class名称,您的HTML更简化了,而且只需要设置一个事件处理程序。

请注意,我的HTML是通过Ajax调用动态加载的。 - Intern
谢谢,我试了你的方法。一开始它没起作用,因为我也在动态加载包装类,所以我把它改成静态的,并添加到编辑中。 - Intern
请问您如何访问此类型中的元素,例如我想在按钮单击时隐藏文本字段和按钮,并用文本“已更新”替换。我阅读了文档但无法实现。 - Intern
@实习生 这只是一个显示和隐藏事物的问题,我已经在答案中添加了。 - Scott Marcus

1
几件事情 var price = document.getElementsByClassName(id);是复数形式,你需要值,所以如果必要,可以使用var price = document.getElementsByClassName(id)[0].value; 但是这不是一个类,而是一个名称,如果必要,可以使用var price = document.getElementsName(id)[0].value; 但是,如果您有jQuery,为什么不使用它呢?
这里我用按钮ID查找名称输入框
我还改变了type="button" - 当您使用Ajax时,您不想提交。

$(function() { // on page load
  $("#container").on("click","[type=button]",function() { // click on type="button" you can use a Class here too
    const id = $(this).attr("id");
    const price = $("[name="+id+"]").val(); // get the input by name
    console.log(id, price)
    if (price) {

      $.ajax({
        type: "POST",
        url: "update_rate.php", // Name of the php files
        data: {
          subcategory: id,
          price: price
        },
        success: function(res) {
          // console.log(html);
          alert(res);
        }
      });
    }
  })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">

first pair:
<div class="form-group">
  <input type="text" class="form-control" name="a" placeholder="Your task rate excl. taxes">
</div>
<button type="button" id="a" class="btn btn-primary">Update</button>

<div class="form-group">
  <input type="text" class="form-control" name="b" placeholder="Your task rate excl. taxes">
</div>
<button type="button" id="b" class="btn btn-primary">Update</button>
</div>


我看到你的答案完美地运作了,但在我的情况下却不起作用。通过ajax调用动态加载html是否有任何区别? - Intern
是的,非常重要。那是重要的信息-然后我们需要从容器中委派-请展示您在哪里附加新数据。 - mplungjan
看一下我添加的容器。 - mplungjan
感谢您的解决方案和时间。我之前应该添加有关动态加载的信息。 - Intern

0

既然你已经在函数中传递了id,那么使用jQuery,你可以这样做:

var selector = 'input[name="' + id + '"]' // Compose the selector string for jQuery
var value = $(selector).val()             // Get input value

就像我已经做的那样。请重新加载页面以查看我的答案。 - mplungjan
我看到你的答案很好,但在我的情况下不起作用。通过ajax调用动态加载html是否会有任何影响? - Intern

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接