I'm using selectize for my drop down menus and I'm trying to do form validation. Each of the menus has class .code_select, and I want to know if an option has been selected on all of them. My code should determine if something is selected, and if not add the ID of the dropdown to an array called empty_fields. However, my dropdowns are all ending up in the array whether they have a selected option or not. This is my code:
$(".code_select").each(function(){
if ($(this).find('option:selected').length === 0) {
empty_fields.push($(this).attr("id")+'-selectized');
submitForm=false;
}
});
An example of one of the inputs:
<div class='col-4'>
<input type='text' class='form-control code_select' id='5-tree-Betpap-stdCodeSelect' name='5-tree-Betpap-stdCode' aria-label='Tree Metric Field 5 Standard Code select'>
</div>
And my selectize initialization:
// initialize newCodes selectize control
newCodesSelect[index] = $(this).selectize({
valueField: 'id',
labelField: 'label',
create: false,
hideSelected: false,
options: listOptions[listType],
searchField: 'label',
placeholder: "Choose " + listType + " codes (type to search)",
maxItems: 1,
});
//This stores the selectize object to a variable
newCodesSelectize[index] = newCodesSelect[index][0].selectize;
How do I determine if the select is still on the "placeholder" when my placeholder has a variable?
Thank you!
OK, here is what worked for me. I had to use .selectize-control as the selector and find if any of the items have data-attribute=null.
$('#nextBtn').click(function() {
console.log("Next Button - adding hidden fields");
//remove any left over error formatting
$('.requiredField').removeClass('requiredField');
var fld_text="";
$('#error-messages').html(fld_text);
// validate form before submit
var empty_fields=[];
var submitForm=true;
$(".code_description").each(function(){
if ($(this).val()==="") {
empty_fields.push($(this).attr("id"));
submitForm=false;
}
});
$(".selectize-control").each(function(){
if ($(this).find(".item").attr('data-value') == null) {
empty_fields.push($(this).prev("input").attr("id")+'-selectized');
}
});
empty_fields.forEach(function(element) {
if (element!=="undefined-selectized") submitForm=false;
});
if (submitForm===true) {
$('#nextForm').submit();
}
else {
fld_text="<p>Review required fields</p>";
$('#error-messages').html(fld_text);
empty_fields.forEach(function(element) {
if (element!=="undefined-selectized") $("#"+element).addClass("requiredField");
});
}
});
Related
I want to enable/disable a kendo combobox based on the user's selection from a checkbox, which I am storing in a variable.
I already tried setting the variable to the enable property, but this is useful only when the control is being built-in.
Does anybody know If I can do this while creating the control?
<div id="fund" class="col-xs-3">
input class="required" data-bind="title: $parent.selectedFund,
kendoComboBox: {
placeholder: 'Start typing to search...',
value: $parent.test,
widget: $parent.searchSource,
dataTextField: 'managerName',
dataValueField: 'managerId',
filter: 'contains',
autoBind: false,
minLength: 3,
enable: overrideGlobalMapping, //this does not work for me even though the variable holds the correct value
change: function(){ if(this.value() && this.selectedIndex == -1)
{
setTimeout(function () {$parent.selectedManagerId(null);}, 100);}},
dataSource: {
serverFiltering: true,
transport: {
read: $parent.retrieveManager
}
}
}" />
</div>
I ended up wrapping the kendo combox definition in a function, so it now looks likes this:
<input type="checkbox" id="overrideGlobalMappingCheck" onclick="SetFundsCombobox()" data-bind="checked: overrideGlobalMapping, enable: $root.canConfirmMapping" />
The kendo combobox is still wrapped and has an id, which I later use to manipulate it in javascript:
<div class="col-xs-3" id="funds">
<input class="required" data-bind="title: $parent.selectedFund,
kendoComboBox: {
placeholder: 'Start typing to search...',
value: $parent.selectedManagerId,
...
}" />
</div>
And this is the JavaScript function bound to the onclick checkbox's event:
function SetFundsCombobox() {
var fundsDiv = document.getElementById('funds');
var inputSelector = fundsDiv.getElementsByClassName('k-input');
var span = fundsDiv.getElementsByTagName('span');
if (document.getElementById('overrideGlobalMappingCheck').checked) {
document.getElementById('funds').disabled = false;
inputSelector[0].disabled = false;
span[1].classList.remove("k-state-disabled");
} else {
document.getElementById('funds').disabled = true;
inputSelector[0].disabled = true;
span[1].classList.add("k-state-disabled");
}
};
I'd have rather preferred to perform this via the view model, but it works for now.
EDIT:
I've been able to do this the right way (following the MVVM pattern), so now rather than wrapping the kendo combo box in a function, I added the following function in the view model:
$scope.overrideGlobalMappingChecker = ko.computed(function () {
if ($scope.entityMapping()) {
var checkboxChecked = $scope.entityMapping().overrideGlobalMapping();
$("#funds .k-input").prop('disabled', !checkboxChecked);
if (!checkboxChecked) {
$scope.selectedFundId(null);
}
}
});
So now, what the html only needs is the definition of the id in the div containing the combo box:
<div class="col-xs-3" id="funds">
<input data-bind="title: $parent.selectedFundName, kendoComboBox: {
autoBind: false,
...
}" />
</div>
And that's it, it's a much cleaner/correct way to handle this.
I have a web application using asp.net and C#. I have a ListBox where the user can select multiple items. They are grouped using the attribute property. I need this property in the code behind in the button click event. I thought I could set the attribute values on the client side and they would be available on the server side and have learned that is not the case.
I don't know the best way to go about this. Each ListItem has a Name, Value and Group that I would like to have on the server side. The name and value are already available on the server side. I need the group associated with each selected item. Should I create a hidden field for each selected item? Should there be one hidden field with the grouping and value associated with each grouping? I have a jquery function that sets the grouping attribute. I would like to use that to set the hidden field but I am not sure if I should use one hidden field or as many as items selected.
This is the javascript that I have already:
$(document).ready(function () {
//Create groups for recipient dropdown list
$(".chosen-select option[grouping='GlobalGroups']").wrapAll("<optgroup label='Global Groups'>");
$(".chosen-select option[grouping='PersonalGroups']").wrapAll("<optgroup label='Personal Groups'>");
$(".chosen-select option[grouping='Individuals']").wrapAll("<optgroup label='Individuals'>");
//Configure the ListBox using the 'chosen' jquery plugin
$(".chosen-select").chosen({
search_contains: true,
no_results_text: "Sorry, no match!",
allow_single_deselect: true
});
$('.chosen-container').css('width', '600px');
//set attribute property for selected list
$(".chosen-select").chosen().change(function (evt) {
$(".chosen-select").find("option:selected").each(function () {
var label = $(this).closest('optgroup').prop('label');
if (label == "Global Groups") {
$(this).attr("grouping", "GlobalGroups");
}
else if (label == "Personal Groups") {
$(this).attr("grouping", "PersonalGroups");
}
else {
$(this).attr("grouping", "Individuals");
}
});
});
});
This is the HTML:
<asp:ListBox ID="lstBoxTo" runat="server" SelectionMode="Multiple"
data-placeholder="Choose recipient(s)…" multiple="true" class="chosen-select">
</asp:ListBox>
For any with this problem...I went with a hidden field, asp:HiddenField, and adding all of the selections in a semicolon delimited string.
I parsed the string in the code behind to determine the recipients that were groups and ones that were individuals.
This was my final jquery script:
$(".chosen-select").chosen().change(function (evt) {
$("#hdnRecipientAttr").val("");
$(".chosen-select").find("option:selected").each(function () {
var label = $(this).closest('optgroup').prop('label');
var currentHdnValue = $("#hdnRecipientAttr").val();
if (label == "Individuals") {
var attrText = "Individuals-" + $(this).prop('value') + ";";
$("#hdnRecipientAttr").val(currentHdnValue + attrText);
}
else {
var attrText = "Group-" + $(this).prop('value') + ";";
$("#hdnRecipientAttr").val(currentHdnValue + attrText);
}
});
//remove ending semicolon
var hdnValue = $("#hdnRecipientAttr").val();
$("#hdnRecipientAttr").val(hdnValue.slice(0, -1));
});
I have a chunk of javascript that looks like this:
$(document).ready(function() {
var listident = "#list3";
// ...
var children = //get one or more "child" objects as JSONArray
$.each(children, function(i){
jobGridColNames.push(children[i] + "");
jobGridColModel.push({name: children[i], index: children[i], align: 'center',
editable: false, edittype: 'checkbox', formatter: 'checkboxFormatter',
formatoptions: {disabled : false}, editoptions: { value:"true:false"}, sortable: true
});
});
// ...
$("#compareButton").button({text: true}).click(function(){
var selectedRows = getSelectedRows("list3");
if(selectedRows.length == 0){
alert("Please select at least one row");
return;
}
$.each(selectedRows,function(i, row){
// ...? Here is where I need help
});
});
});
checkboxFormatter: function checkboxFormatter(cellvalue, options, rowObject) {
if(cellvalue == "different"){
return "<input offval='on' type='checkbox' value='false' >";
}else{
return cellvalue
}
}
I don't know in advance how many columns I will have, nor will I know the name of the column. All I know is that each dynamic column will have either a checkbox or some text in it.
When I click the #compareButton, I need to know the row and column of all the checkboxes that were checked anywhere in the grid (there might be multiple checkboxes checked in a row). I don't see anything in the row object that tells me what column I am looking at when I find all the checked checkboxes.
The only thing I can think of is to have an onChecked event that saves the rowXcolumn pair to a local variable. That seems gross. But I can't find anything else that might work.
Thanks in advance!
I am getting data from server and loading them to JQuery auto suggest. It's works fine. But I don't know how to configure it. I Initialize my text box to it. Now i need when user select one value from it, He will be not able to choose another value of he cant enter a word, except he can delete old value.
Here is my code :-
$(document).ready(function(e){
//handle auto suggestion when compose message
var user_ids = {};
//var hidden_user_ids = $('input:hidden[name=user_ids]');
var url = '/account/insiderName';
var conf = {
selectedItemProp: 'name',
searchObjProps: 'name',
asHtmlID: 'insider_ids',
neverSubmit: true,
multiSelect: false,
preFill: ',' //, {{attributes: {name: 'joe', value: '12345'}, num: '1'}},
};
$('.insiderUser').autoSuggest(url, conf);
});
Here is my text Box Code:-
<div class="field to"><input type="text" name="toInsider" value="" class="insiderUser"/></div>
Add this configuration option also:
selectionLimit: 1
since it defaults to false, which means no limit.
From the docs: https://github.com/wuyuntao/jquery-autosuggest
I use select2 plugin and get values when user typing least 3 character. Get data from php as json like this;
"1":"val1" , "5":"val2" , "19":"val3"....
I want to store id values of selected items at hidden input and when user remove any selected item, the id of removed item also remove from hidden input. For example;
When val1 and val2 items are selected like below, value of hidden input (id which 'hdn-id') change like below, also.
<input type="hidden" id="hdn-id" val="1,5" />
And when val1 is removed, id of this item (1) removed from hidden input like this ;
<input type="hidden" id="hdn-id" val="5" />
But I can't do this. My codes;
SELECT2:
function selectAjax(element,url,hiddenElement) {
var selectedItemsArray = []
$('#'+element).select2({
multiple: multi,
id: function(element) {
return element
},
ajax: {
url: url,
dataType: 'json',
data: function(term,page) {
return {
term: term,
page_limit: 10
};
},
results: function(data,page) {
var titleArr = [];
$.each(data, function(k,v){
titleArr.push(k+':'+v);
});
return {
results: titleArr
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
});
function formatResult(data) {
return '<div>'+data.substr(data.indexOf(':')+1)+'</div>'
};
function formatSelection(data) {
var id = data.split(':',1),
text = data.substr(data.indexOf(':')+1),
hiddenElementValue = eval([jQuery('#'+hiddenElement).val()]);
selectedItemsArray.push(id);
jQuery('#'+hiddenElement).val(selectedItemsArray);
return '<div data-id="'+id+'" class="y-select2-selected-items">'+text+'</div>';
};
}
selectAjax('select2-element','ajx.php','hdn-id');
HTML:
<input type="text" id="select2-element" />
<input type="hidden" id="hdn-id" />
I can store ids at hidden input with above code but when remove an item I can't remove id from hidden input. Because plugin assign 'return false' to element's onclick event. I handed the job with above codes, I think.How can I be a better solution?
You can use the change event of the select2 plugin and there write some code that will update the value of the hidden input.
$("#select2-item").select2({
//options go here
});
$("#select2-item").on("change", function(e) {
//update hidden input value
});