2011-12-13 44 views
1

我有一些代碼,創建一個下拉框,一堆選項,我不知道選項。我試圖用jQuery來說明是否選擇了idk,alert(「可能需要額外的時間來發送請求」);如果選擇了特定的選項,顯示警告

我想使用嵌套在條件語句內的.focusout事件觸發警報。我甚至不知道我能做到這一點,但這是真正做我想做的最好的方式,因爲我不想看到任何選中選項的警報。

這裏是我的小提琴鏈接http://jsfiddle.net/JustJill54/ye8rG/

理想我很樂意能說 - 但我不能。有什麼我做錯了嗎?

$("option[value='idk']").focusout(function(){ 
    alert("If no organizational element is selected, additional time may be required to route this request"); 
}); 

很多謝謝!

回答

3

您需要監聽select元素上的事件,而不是option。還有一些語法錯誤。我有updated your fiddle here

請注意,從用戶體驗的角度來看,可能會有更微妙的方式通知用戶,而不是突然出現在他們面前的侵入式警報框。例如,可能會出現新的文本範圍,或者其他可視指示符不會中斷其工作流程。

$(document).ready(function(){ 
    // Attach to the focusout event of the select, if that's when 
    // you want to check the value 
    $("select[title='organizationalElement']").focusout(function(){ 
     // Now see if it's the value you want 
     if ($(this).val() === 'idk'){ 
      alert("If no organizational element is selected, additional time may be required to route this request"); 
     } 
    }); 
}); 
+0

上午在使用小提琴。
其實有點想警惕入侵,讓用戶不會錯過它。
感謝您的協助! – jg100309 2011-12-13 20:42:35

1

我發現了兩個問題,你的jsfiddle(包括在這裏供參考):

$(document).ready(function(){ 
    if ($("select[title='organizationalElement']").val() == "idk') { 
    $(this).focusout(function(){ 
     alert("If no organizational element is selected, additional time may be required to route this request"); 
    }); 
    }); 
}); 
  1. 語法錯誤
  2. 你結合的情況下,而不是內部之前,運行條件事件本身

這是一個過於簡化的工作示例:

$(document).ready(function(){ 
    $('select').focusout(function(){ 
    if ($(this).val() == 'idk') { 
     alert('Some message'); 
    } 
    }); 
}); 

這不同於在兩個關鍵方面你:

  1. 需要注意的是你要與});,而不是僅僅}關閉一個if塊。可能只是一個錯字。也有一些不匹配的單引號和雙引號。
  2. 事件綁定是第一個問題,條件是第二個問題。在您的版本中,基本上是這樣說的:「當頁面第一次加載時,如果select的值爲idk,那麼將此事件綁定到它,它將顯示警報。」注意不同之處。頁面第一次加載時,該值永遠不會爲idk,並且該代碼將永遠不會再次執行。相反,當元素失去焦點並檢查事件中的條件時,綁定事件總是會觸發。
2

我有點晚,但很好哦,這是我稍有不同的答案:

$(document).ready(function(){ 
    $('.org').focusout(function(){ 
     if($(this).val() == 'idk') 
     { 
       alert("If no organizational element is selected, additional time may be required to route this request"); 
     } 
    }); 
}); 

但我的2美分補充的是:我不知道人們爲什麼決定使用精心選擇在具有特定類或ID的對象上。在這種情況下,您可以選擇類.org,而不必評估元素的標題。更好的是,爲它分配一個id,以便jquery在遇到該元素時停止遍歷。

+0

+1包含選擇器建議。 – 2011-12-13 20:41:53

相關問題