【问题标题】:Get value of input field by class name, wherer class name is varible通过类名获取输入字段的值,其中类名是变量
【发布时间】:2021-01-30 02:43:38
【问题描述】:

我有很多对文本字段和提交按钮,id 提交按钮和class 文本字段相同但每对不同。所以我想将按钮单击后在文本字段中输入的值传递给 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 是函数的参数,也是文本字段的类名,那么如何在文本字段中输入值?
  • 请参阅下面的答案,了解更简单的方法。

标签: javascript html jquery ajax


【解决方案1】:

这可以而且应该以不同且更简单的方式完成。通过idclass 将按钮与其文本字段连接起来不是可扩展的解决方案,并且需要不断更新代码以保持所有命名同步。只需获取按钮之前的文本字段的值。如果您修改 HTML 结构,使文本字段和按钮位于同一个 div 中,这将更容易。

参见下面的 cmets。

// 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 调用动态加载的。
  • 谢谢大佬,试了你的方法。一开始它不起作用,因为我也在动态加载包装类,所以只是让它成为静态的。并在编辑中添加。
  • 你能告诉我,我怎样才能访问这种类型的元素,比如我想隐藏文本字段和按钮并在按钮单击时替换为文本updated。我阅读了文档,但无法做到。
  • @Intern 这只是显示和隐藏东西的问题,我已将其添加到答案中。
【解决方案2】:

几件事

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 有什么不同吗?
  • 是的,非常。这是重要的信息——然后我们需要从容器中委派——请显示你在哪里附加新数据
  • 查看我添加的容器
  • 感谢您的解决方案和时间。我之前应该添加有关动态加载的信息。
  • 所以我的解决方案不适合你?它比你接受的更优雅
【解决方案3】:

由于您已经在函数中传递了 id,因此使用 jQuery,您可以执行以下操作:

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

【讨论】:

  • 就像我已经做过的那样。请重新加载页面以查看我的答案
  • 我看到你的这个答案工作正常,但在我的情况下它不起作用,通过 ajax 调用动态加载 html 有什么不同吗?
猜你喜欢
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 2017-07-11
  • 2020-05-12
  • 1970-01-01
相关资源
最近更新 更多