在所有标签中查找单词并将其替换为jQuery

时间:2020-06-11 20:11:52

标签: javascript html jquery jquery-ui xhtml

我有多个带有标签的输入字段,标签以单词“ Shop”开头,即 店铺信: 店铺编号: 店铺信函文件: 我有一个下拉菜单,其中有两个选项“商店”和“商店”。我想从下拉菜单中选择“存储”时更改为“存储”。

这是我到目前为止所做的;

<form action="" id="form_type">
    <label for="type">Choose a type:</label>
    <select id="type">
        <option value="shop">Shop</option>
        <option value="store">Store</option>
    </select><br><br>
    <label for="Shop_Letter">Shop Letter :</label>
    <input type="text" id="Shop_Letter" name="Shop_Letter"><br><br>
    <label for="Shop_Letter_No">Shop Letter No :</label>
    <input type="text" id="Shop_Letter_No" name="Shop_Letter_No"><br><br>
    <label for="Shop_Letter_File">Shop Letter File :</label>
    <input type="text" id="Shop_Letter_File" name="Shop_Letter_File"><br><br>
</form>


$("#type").on('change', function(){
        var shop_letter = $("label[for='Shop_Letter']").html(); //Get the text
        var shop_letter_no = $("label[for='Shop_Letter_No']").html(); //Get the text
        if (this.value == 'store'){
            $("label[for='Shop_Letter']").html(shop_letter.replace("Shop", "Store"));
            $("label[for='Shop_Letter_No']").html(shop_letter_no.replace("Shop", "Store"));
        }else{
            $("label[for='Shop_Letter']").html(shop_letter.replace("Store", "Shop"));
            $("label[for='Shop_Letter_No']").html(shop_letter_no.replace("Store", "Shop"));
        }
    });

当我手动选择标签并分配var时,它确实以这种方式工作,但是我想选择所有标签并使用适当的方法对其进行更改。我似乎无法自己解决这个问题。 谢谢

1 个答案:

答案 0 :(得分:1)

请考虑以下内容。

$(function() {
  function changeLabel(tObj, v) {
    tObj = $(tObj);
    tObj.html(v + tObj.text().slice(tObj.text().indexOf(" ")));
  }
  $("#type").on('change', function() {
    var sel = $(this).val();
    sel = sel.charAt(0).toUpperCase() + sel.slice(1);
    $("#form_type label").each(function(i, el) {
      if (i !== 0) {
        changeLabel(el, sel);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="form_type">
  <label for="type">Choose a type:</label>
  <select id="type">
    <option value="shop">Shop</option>
    <option value="store">Store</option>
  </select><br><br>
  <label for="Shop_Letter">Shop Letter :</label>
  <input type="text" id="Shop_Letter" name="Shop_Letter"><br><br>
  <label for="Shop_Letter_No">Shop Letter No :</label>
  <input type="text" id="Shop_Letter_No" name="Shop_Letter_No"><br><br>
  <label for="Shop_Letter_File">Shop Letter File :</label>
  <input type="text" id="Shop_Letter_File" name="Shop_Letter_File"><br><br>
</form>

如果您有一个字符串:"Shop Letter File :",并且想将Shop替换为Store,则可以使用.slice()。我们使用Slice从第一个" "获取文本,并在新字符串前添加前缀。我将此功能移至一个函数,以使其易于反复使用。

然后,我们需要遍历每个需要更改的Label(跳过第一个),并将其和新值传递给函数。