如何使用循环更改多个输入的边框样式?

时间:2014-12-01 07:59:40

标签: javascript jquery html css ajax

如何使用JavaScript for循环更改多个输入的边框样式?

当我将1填入每个输入type="text",然后按提交按钮。

仅改变边框样式

<input type="text" id="price1" size="20" name="price[]">

但我想用for循环改变所有3个输入的边框样式。

怎么做?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<form onsubmit="return checkform(this);">
<div id="p_scents_price">
    <p>
        <label for="p_scnts_price">
            <input type="text" id="price1" size="20" name="price[]">
        </label>
    </p>
</div>
<div id="p_scents_price">
    <p>
        <label for="p_scnts_price">
            <input type="text" id="price2" size="20" name="price[]">
        </label>
    </p>
</div>
<div id="p_scents_price">
    <p>
        <label for="p_scnts_price">
            <input type="text" id="price3" size="20" name="price[]">
        </label>
    </p>
</div>
<input type="submit" name="submit" value="OK">
</form>

<script language="JavaScript" type="text/javascript">
<!--
function checkform ( form )
{
  var z = 1;
  for(var z=1;z<10;z++) 
  {
    if ((document.getElementById("price"+z).value != "") && (document.getElementById("price"+z).value < "1.5")) {
      document.getElementById("price"+z).style.border = "1px solid red";
      return false ;
    }
    else {
      document.getElementById("price"+z).style.border = "1px solid #d5d5c5";
    }
  }
return true ;
}
//-->
</script>

2 个答案:

答案 0 :(得分:0)

那里有一些问题:

  1. 您不能在多个元素上使用相同的id

  2. for上的label属性必须引用与其相关的表单字段,而不是div

    < / LI>
  3. 您不需要或想要一个for属性label包含与其相关的input

  4. 这:document.getElementById("price"+z).value < "1.5"执行字符串比较。如果您想比较数字,请从1.5中删除引号,<的JavaScript算法会在进行比较之前将value字符串转换为数字。或者,由于数字是由某人输入的,您可能希望使用parseInt(..., 10)明确确保在基数10中解析它,尽管parseInt允许在数字后添加额外的字符。

    < / LI>
  5. 在您的代码中,第一次元素的值为< "1.5"时,您执行return false。这会阻止循环。你可能希望有一个变量isValid或类似的变量,你设置true开始,然后在发现问题时设置false,然后返回。

    < / LI>
  6. 您的循环从1转到10,但您只有三个priceN输入。而不是硬编码循环限制,通常最好让标记驱动代码。

  7. =1中的var z=1如果您在下一行再次执行此操作,则毫无意义;类似地,两次声明变量是没有意义的

  8. 当您发现自己反复调用函数来反复获取相同的内容时(document.getElementById("price"+z")),请考虑只执行一次并将结果保存到变量

    < / LI>

    一些建议(见评论):

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    
    <form onsubmit="return checkform(this);">
    <div><!-- Change: Removed `id` from these divs -->
        <p>
            <label><!-- Change: Removed `for` from these labels -->
                <!-- Change: Changed `id="priceN"` to `class="price"` on these inputs -->
                <input type="text" class="price" size="20" name="price[]">
            </label>
        </p>
    </div>
    <div>
        <p>
            <label>
                <input type="text" class="price" size="20" name="price[]">
            </label>
        </p>
    </div>
    <div>
        <p>
            <label>
                <input type="text" class="price" size="20" name="price[]">
            </label>
        </p>
    </div>
    <input type="submit" name="submit" value="OK">
    </form>
    
    <script language="JavaScript" type="text/javascript">
    // Change: Rewrote; also removed archaic <!-- comments, you don't need them
    function checkform ( form )
    {
      // Get a list of all of the elements with the "price" class
      var list = document.querySelectorAll(".price");
      var z;
      var input;
      var isValid = true;
      var value;
    
      // Loop through the list
      for (z = 0; z < list.length; ++z) {
        console.log("z = " + z);
        // Get this input
        input = list[z];
    
        // Check its value
        if (input.value != "" && parseInt(input.value, 10) < 1.5) {
          // Not valid, set border and flag that the form is invalid
          input.style.border = "1px solid red";
          isValid = false;
        }
        else {
          // Valid, clear any previous red border
          input.style.border = "1px solid #d5d5c5";
        }
      }
    
      // Return result
      return isValid;
    }
    </script>
    

    工作示例:

    // Change: Rewrote; also removed archaic <!-- comments, you don't need them
    function checkform ( form )
    {
      // Get a list of all of the elements with the "price" class
      var list = document.querySelectorAll(".price");
      var z;
      var input;
      var isValid = true;
      var value;
    
      // Loop through the list
      for (z = 0; z < list.length; ++z) {
        console.log("z = " + z);
        // Get this input
        input = list[z];
    
        // Check its value
        if (input.value != "" && parseInt(input.value, 10) < 1.5) {
          // Not valid, set border and flag that the form is invalid
          input.style.border = "1px solid red";
          isValid = false;
        }
        else {
          // Valid, clear any previous red border
          input.style.border = "1px solid #d5d5c5";
        }
      }
    
      // Return result
      return isValid;
    }
    <form onsubmit="return checkform(this);">
      <div><!-- Change: Removed `id` from these divs -->
        <p>
          <label><!-- Change: Removed `for` from these labels -->
            <!-- Change: Changed `id="priceN"` to `class="price"` on these inputs -->
            <input type="text" class="price" size="20" name="price[]">
          </label>
        </p>
      </div>
      <div>
        <p>
          <label>
            <input type="text" class="price" size="20" name="price[]">
          </label>
        </p>
      </div>
      <div>
        <p>
          <label>
            <input type="text" class="price" size="20" name="price[]">
          </label>
        </p>
      </div>
      <input type="submit" name="submit" value="OK">
    </form>

答案 1 :(得分:0)

首先,你的for循环可能只需要三个。

for(var z = 1; z < 3; z++)

此外,您不需要两次定义变量z

var z = 1; // This can go.
for(var z = 1; z < 3; z++)  

其他一些小的重复因子会产生这种效果。

function checkform (form)
{
    var isValidForm = true;
    for(var z = 1; z <= 3; z++) 
    {
        var inputValue = parseFloat(document.getElementById("price" + z).value);

        if (!isNaN(inputValue) && inputValue < 1.5) {
            document.getElementById("price" + z).style.border = "1px solid red";
            isValidForm = false;
        }
        else {
            document.getElementById("price" + z).style.border = "1px solid #d5d5c5";
        }
    }

    return isValidForm;
}

或者你可以使用JQuery:

function checkForm(){

    var isFormValid = true;

    // Get all text inputs that have an ID starting with 'price' and loop through them
    $('input[type=text][id^=price]').each(function(){

         // Get the current loop item.
         var currentItem = $(this);

         // Convert it's value to a number.
         var inputValue = parseFloat(currentItem.val());

         // If it's invalid make it red.
         if (!isNaN(inputValue) && inputValue < 1.5) {
            currentItem.css('border', '1px solid red');
            isValidForm = false;
         }else{
             // Otherwise, make it this colour.
             currentItem.css('border', '1px solid #d5d5c5');
         } 
    });
}