2017-08-09 124 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();