2017-08-09 77 views
-2

我有一個「再試一次!」當在我的下拉選擇列表中存在所插入的值出現的消息,這是我的代碼:JQuery從父項中移除元素

//I am trying to remove this message once the user starts typing again: 
 

 
    $('#new_day').on('input', function(){ 
 
    //Get input value 
 
    var input_value = $(this).val(); 
 
    
 
    //Remove disabled from the button 
 
    $('#new_day_save').removeAttr('disabled'); 
 
    
 
    //iterate through the options 
 
    $(".days > option").each(function() { 
 
     //If the input value match option text the disable button 
 
     if(input_value == $(this).text()){ 
 
      $('#new_day_save').attr('disabled', 'disabled'); 
 
      $('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>"); 
 
     }else{ 
 
     $('#new_day_save').parent().remove("#error_message"); 
 
     } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
    <select class="days"> 
 
     <option>Monday</option> 
 
     <option>Friday</option> 
 
    </select> 
 
    <p>You have another proposition? Add it to the list.</p> 
 
    <div> 
 
     <input id="new_day" type="text" /> 
 
    </div> 
 
    <input id="new_day_save" type="button" value="save new day"/>

+0

如果你想刪除的消息?像'$('#error_message')。remove()'? – David

回答

0

你可以remvoe的#error_message加給你的事件處理程序選項 $('#new_day_save').parent().find('#error_message').remove() 並且您可以刪除else條件。

$('#new_day').on('input', function(){ 
 
    //Get input value 
 
    var input_value = $(this).val(); 
 

 
    //Remove disabled from the button 
 
    $('#new_day_save').removeAttr('disabled'); 
 
$('#new_day_save').parent().find('#error_message').remove(); 
 
    //iterate through the options 
 
    $(".days > option").each(function() { 
 
    //If the input value match option text the disable button 
 
    if(input_value == $(this).text()){ 
 
     $('#new_day_save').attr('disabled', 'disabled'); 
 
     $('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>"); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<select class="days"> 
 
    <option>Monday</option> 
 
    <option>Friday</option> 
 
    </select> 
 
    <p>You have another proposition? Add it to the list.</p> 
 
    <div> 
 
    <input id="new_day" type="text" /> 
 
    </div> 
 
    <input id="new_day_save" type="button" value="save new day"/>

0

這條線$('#new_day_save').parent().remove("#error_message");將刪除父元素。

要在jQuery的你輸入值與之前刪除特定的元素,這樣做只是因爲它是一個id選擇是唯一的元素,

$("#error_message").remove();