You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript判断输入值(不触发提交)及实现浮动标签效果

Hey there! Let's break down and solve your two technical requirements step by step:

1. 判断输入文本是否有值且不触发表单提交

To check if input fields have values without triggering form submission, you'll need to prevent the form's default submit behavior first, then validate each input's content. Since you're already using jQuery, here's a straightforward implementation:

  • First, listen for the form's submit event and call event.preventDefault() to stop the form from submitting.
  • Then, iterate over each input field, use trim() to ignore whitespace, and check if the value is non-empty.

Example code snippet:

$('form').on('submit', function(e) {
  // Stop form from submitting
  e.preventDefault();
  
  // Flag to track if all inputs are filled
  let allInputsFilled = true;
  
  // Check each text input in the form
  $(this).find('input[type="text"]').each(function() {
    const inputValue = $(this).val().trim();
    if (inputValue === '') {
      allInputsFilled = false;
      console.log('Empty input:', $(this).siblings('label').text());
      // You can add custom feedback here, like highlighting the empty input
    }
  });
  
  if (allInputsFilled) {
    console.log('All inputs have values!');
    // If you want to submit the form programmatically later, uncomment below
    // $(this).unbind('submit').submit();
  }
});
2. 实现浮动标签(Floating Labels)效果

Your existing code has a solid foundation, but we need to adjust it to handle focus, blur, and input content states properly. Let's fix the small issues and add the necessary logic:

Step 1: Fix CSS and add the active state

First, correct the typo input-conatiner to input-container (you missed an 'n'). Then add a .active class to control the label's position:

.form {
  width: 600px;
  margin: auto;
}
/* Fixed class name */
.input-container {
  width: 320px;
  margin: 60px auto;
  text-align: center;
  height: 35px;
  position: relative;
}
.input-container input {
  position: absolute;
  background: none;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  /* Add border and padding for better visibility */
  border: 1px solid #ccc;
  padding: 0 10px;
  box-sizing: border-box;
}
.input-container label {
  position: absolute;
  top: 8px; /* Align with input text vertically */
  left: 10px;
  z-index: 9;
  transition: 300ms ease;
  color: #666;
}
/* Active state for label */
.input-container.active label {
  color: red;
  transform: translateY(-100%); /* Move up by 100% as requested */
}

Step 2: Add JavaScript to handle interactions

We need to toggle the .active class based on input focus and content. Here's the reusable logic:

$(document).ready(function() {
  // Reusable function to update label state
  function updateLabelState(input) {
    const container = $(input).closest('.input-container');
    const hasValue = $(input).val().trim() !== '';
    
    if ($(input).is(':focus') || hasValue) {
      container.addClass('active');
    } else {
      container.removeClass('active');
    }
  }
  
  // Listen for focus, blur, and input events
  $('.input-container input').on('focus blur input', function() {
    updateLabelState(this);
  });
  
  // Initialize state for pre-filled inputs (if any)
  $('.input-container input').each(function() {
    updateLabelState(this);
  });
});

Step 3: Full Working Code

Here's the complete code combining both requirements:

<html>
<head>
  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
  <style>
    .form {
      width: 600px;
      margin: auto;
    }
    .input-container {
      width: 320px;
      margin: 60px auto;
      text-align: center;
      height: 35px;
      position: relative;
    }
    .input-container input {
      position: absolute;
      background: none;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      border: 1px solid #ccc;
      padding: 0 10px;
      box-sizing: border-box;
    }
    .input-container label {
      position: absolute;
      top: 8px;
      left: 10px;
      z-index: 9;
      transition: 300ms ease;
      color: #666;
    }
    .input-container.active label {
      color: red;
      transform: translateY(-100%);
    }
  </style>
</head>
<body>
  <form class="form">
    <div class="input-container">
      <input type="text"/>
      <label>HI there</label>
    </div>
    <div class="input-container">
      <input type="text"/>
      <label>HI there</label>
    </div>
    <div class="input-container">
      <input type="text"/>
      <label>HI there</label>
    </div>
    <button type="submit" style="display: block; margin: 0 auto;">Submit</button>
  </form>

  <script>
    $(document).ready(function() {
      // 1. Form validation without submission
      $('form').on('submit', function(e) {
        e.preventDefault();
        let allFilled = true;
        
        $(this).find('input[type="text"]').each(function() {
          if ($(this).val().trim() === '') {
            allFilled = false;
            alert(`Please fill in: ${$(this).siblings('label').text()}`);
          }
        });
        
        if (allFilled) {
          alert('All inputs are filled! Form would submit now.');
        }
      });

      // 2. Floating labels logic
      function updateLabelState(input) {
        const container = $(input).closest('.input-container');
        const hasValue = $(input).val().trim() !== '';
        
        if ($(input).is(':focus') || hasValue) {
          container.addClass('active');
        } else {
          container.removeClass('active');
        }
      }

      $('.input-container input').on('focus blur input', function() {
        updateLabelState(this);
      });

      $('.input-container input').each(function() {
        updateLabelState(this);
      });
    });
  </script>
</body>
</html>

Key Changes Explained:

  • Fixed the CSS class name typo for proper targeting
  • Added input styling to make fields visible and user-friendly
  • Created a reusable function to handle label state changes across all events
  • Covered all interaction scenarios: focus, blur, and real-time input
  • Integrated form validation and floating labels into one cohesive script

内容的提问来源于stack exchange,提问作者Sumit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:52:33