無效無效我試圖做一個網站,有3個字段默認值。如果所有字段都填寫完畢,我想要一個提醒,彈出「確定」,它將帶您到一個新的網站。如果它們留空或者沒有回答,我想要一個提示來填寫所有的字段。問題是,無論在田地裏有什麼,我都會得到「再試一次」的警報。需要一個彈出窗口,說是否有效的表單 - 無論如何
我的JS -
$(function() {
\t \t // when the text field gets focus it gets ride of the default value
\t \t //:text makes the browser check for ALL text fields
\t \t $(':text').focus(function() {
\t \t \t console.log('got focus');
\t \t \t var field = $(this);
\t \t \t //basically asks - is it blank? if not, put default value in
\t \t \t if (field.val()==field.prop('defaultValue')) {
\t \t \t \t field.val('');
\t \t \t }
\t \t });
\t \t
\t \t $(':text').blur(function() {
\t \t \t console.log('lost focus');
\t \t \t var field = $(this);
\t \t \t
\t \t \t //basically asks - is it blank? if not, put default value in
\t \t \t if (field.val()=='') {
\t \t \t \t field.val(field.prop('defaultValue')); \t \t \t \t
\t \t \t }
\t \t });
\t
\t \t //not working....
\t \t $("#questionform").submit(function() {
\t \t \t
\t \t \t if ($("#question1").val() === "" || $("#question1").prop('defaultValue')) {
\t \t \t \t alert("Please fill out all fields");
\t \t \t \t // since there is invalid input returning false will keep us from navigating to the new form
\t \t \t \t return false;
\t \t \t }
\t \t \t else {
\t \t \t \t // input is valid so we'll navigate to the new form
\t \t \t \t alert('Okay');
\t \t \t \t
\t \t \t }
\t \t \t
\t \t \t \t \t if ($("#question2").val() === "" || $("#question2").prop('defaultValue')) {
\t \t \t \t alert("Please fill out all fields");
\t \t \t \t // since there is invalid input returning false will keep us from navigating to the new form
\t \t \t \t return false;
\t \t \t }
\t \t \t else {
\t \t \t \t // input is valid so we'll navigate to the new form
\t \t \t \t alert('Okay');
\t \t \t \t
\t \t \t }
\t \t \t
\t \t \t \t \t if ($("#question3").val() === "" || $("#question3").prop('defaultValue')) {
\t \t \t \t alert("Please fill out all fields");
\t \t \t \t // since there is invalid input returning false will keep us from navigating to the new form
\t \t \t \t return false;
\t \t \t }
\t \t \t else {
\t \t \t \t // input is valid so we'll navigate to the new form
\t \t \t \t alert('Okay');
\t \t \t \t
\t \t \t }
\t \t }); \t \t
\t \t
\t \t \t \t \t \t
\t }); // end ready
我的HTML -
<form action="success.html" id="questionform">
<label for="question1" class="label">Enter your first name</label>
<br>
<input type="text" value="Question" id="question1">
<br>
<label for="question2" class="label">Enter your last name</label>
<br>
<input type="text" value="Question" id="question2">
<br>
<label for="question3" class="label">Enter your favorite color</label>
<br>
<input type="text" value="Question" id="question3">
<br>
<input type='submit' value='Submit' name="submit" id='submitme'>
</form>
<p id="result"></p>
不管我做什麼或不輸入任何框,它出現無效,不會進入下一個屏幕。
爲什麼要檢查'$(「#question1」)。prop('defaultValue')'默認值。它總是會給出'value =「問題」'使情況總是如此。這就是爲什麼'if'語句正在執行。 – Ayush