I need to remove the existing html when the selectbox val == 0. Here is my HTML,
<div class="info-cont">
<ul class="map-list">
<li>
<span class="left">
<label>Name 1</label>
</span>
<span class="right">
<select class="combo">
<option selected="selected" value="0"></option>
<option value="1">F name</option>
<option value="2">M name</option>
<option value="3">L name</option>
</select>
</span>
</li>
</ul>
</div>
Note : There are about 10 selectboxes in my page like the above,
and jquery for the above is,
$(document).ready(function () {
$('#save').click(function () {
var comboLength = $('.combo').length;
var selectedLength = $('.combo option:selected[value!=0]').length;
if (comboLength == selectedLength) {
alert('Thanks all the fields are selected');
return false;
}
if ($('.combo option:selected[value==0]')) {
$("div.info-cont ul.map-list li span.right").append("<br>Please select an appropriate value").addClass('validerror');
} else {
$("div.info-cont ul.map-list li span.right").html("");
$("div.info-cont ul.map-list li span.right").removeClass('validerror');
}
return false;
})
});
What i need to do in the else condition?(My else part is not funct). Also when i click the submit button for the second time, I should not append a html to which i already received in my first click. Any help? Thanks...
Change the if
to
if($('.combo option:selected').val() === '0'){
All issues can be resolved with
$(document).ready(function(){
$('#save').click(function(){
var combo = $('.combo'), // get all combo elements
selected = $('.combo').filter(function(){
return $(this).find('option[value!="0"]:selected').length;
}), // get all valid combo elements
unselected = combo.not(selected); // get all non-valid combo elements
// clear previous error messages
combo
.closest('.right') // find containing .right element
.removeClass('validerror') // remove error class
.find('.errormessage') // find error message
.remove(); // remove error message
// chech if all combos are valid
if (combo.length === selected.length) {
alert('Thanks all the fields are selected');
return false;
}
// highlight non-valid elements
unselected
.closest('.right')
.addClass('validerror')
.append('<div class="errormessage">Please select an appropriate value</div>');
return false;
});
});
demo at http://jsfiddle.net/gaby/Y3RrH/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.