JQuery Select all fields and check for duplicates, respond with message -
i trying create button selects fields queried inside select. has check duplicates , prompt message if there duplicates allowing user select own fields. appreciated.
$.get_id_num = function(num){ var num_str = num.tostring(); var elements = num_str.split('|'); return elements[0]; } $.select_all_nbrs = function() { $("select[multiple] option").attr('selected', 'selected'); } $( '#id_selectall_btn').click( function() { var nbr = $.get_id_nbr("#id_nbrs"); if($("#id_nbrs option[value='nbr']").length == 0){ show_messages("duplicate!"); }else{ ($.select_all_nbrs("#id_nbrs")); } });
$.select_all_nbrs = function(id) { $("#"+id+" > option").attr('selected', 'selected'); } $( '#id_selectall_btn').click( function() { var nbr = $("#id_nbrs"); var duplicate=false; nbr.find("option").each(function(){ if(nbr.find("option[value='"+$(this).val()+"']").length >1){ duplicate=true; show_messages("duplicate! value "+$(this).val()); } }); if(!duplicate){ ($.select_all_nbrs("#id_nbrs")); } });
as per comment if want select duplicates message try below code
$.select_all_nbrs = function(id) { var nbr = $("#id_nbrs"); var duplicate=false; nbr.find("option").each(function(){ if(nbr.find("option[value='"+$(this).val()+"']").length >1){ duplicate=true; show_messages("duplicate! value "+$(this).val()); }else{ $(this).attr('selected', 'selected'); } }); } $( '#id_selectall_btn').click( function() { ($.select_all_nbrs("#id_nbrs")); });
as per comment op want compare first option duplicates notice changed line if(nbr.find("option[value^='"+$.get_id_num($(this).val())+"|']").length >1){
value^=
means value starts with.. condition mean find options have value starting $.get_id_num($(this).val())+"|"
if length greater 1 means duplicate. need add |
<option value="1|2|3">
not duplicate
of <option value="11|2|3">
duplicate of <option value="1|5|8">
$.select_all_nbrs = function(id) { var nbr = $("#id_nbrs"); var duplicate=false; nbr.find("option").each(function(){ if(nbr.find("option[value^='"+$.get_id_num($(this).val())+"|']").length >1){ duplicate=true; show_messages("duplicate! value "+$(this).val()); }else{ $(this).attr('selected', 'selected'); } }); } $.get_id_num = function(num){ var num_str = num.tostring(); var elements = num_str.split('|'); return elements[0]; } $( '#id_selectall_btn').click( function() { ($.select_all_nbrs("#id_nbrs")); });
Comments
Post a Comment