Kendo Validator always says multi-select is invalid - javascript

I have a multiselect that is dynamically created and appended to a template with the following bit of code:
if(fieldMap[i].required == true){
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'*</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" name="'+fieldMap[i].fieldName.toLowerCase()+'" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'">';
} else{
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'">';
}
optString = '';
for(var k = 0; k < fieldMap[i].picklistVals.length; k++){
if(k == 0){
optString += '\''+fieldMap[i].picklistVals[k]+'\'';
}
else{
optString += ',\''+fieldMap[i].picklistVals[k]+'\'';
}
}
//Close the input component as well as the container div
dynamicComponent += optString + ']"/>\n<span class="k-invalid-msg" data-for="'+fieldMap[i].fieldName.toLowerCase()+'"></span></div>\n\n';
I run a validator.validate() on save button click to determine if information should be saved or not, which is dependent on if the multi-select input is required.
This pops up the invalid tooltip message when nothing is selected just fine. The issue is, however, that it will be marked invalid even if a selection is made. I am wondering if anyone has any solutions for how to get a validator to work correctly with the multiselect. Just hiding the pop ups is not really what I am after, as the validate() function will still fail even if the pop up is hidden, and I need the validate() function to pass.

Maybe not the best, but here is what I got.
function Save(){
$("#divTenureContainer .k-invalid").removeClass("k-invalid");
var tenureChecked = $("#chkTenure").prop('checked');
var tenureValid = Configuration_Tenure_Validator.validate();
}
Configuration_ValidateInput = (input) => {
var validationType = $(input).data("validation");
var required = $(input).prop("required") || $(input).hasClass("js-required");
if (!required) return true;
if (validationType) {
if (validationType === "stars") {
return $(input).val() > "0";
}
if (validationType === "hashtags") {
return ($(input).data("kendoMultiSelect").value().length > 0);
}
if (validationType === "required-text") {
return $(input).val() >= "";
}
}
return true;
}
var Configuration_ValidationRules = { rules: { Configuration_ValidateInput }, validationSummary: false };
var Configuration_Tenure_Validator = $("#divTenureContainer").kendoValidator(Configuration_ValidationRules).data("kendoValidator");

Related

Button dissapear when value reaches 0 JAVASCRIPT

This my code:
$('.upgrade-strength').on('click', function () {
var strCount = $('#strId');
var points = $('#points');
var userId = $(this).attr('id');
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
return val*1-1;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
});
$.ajax("/upgrade-strength/"+userId,
{
});
});
<p>Available points: <strong><span id="points">{{Auth::user()->points}}</span></strong></p>
When I clicking the button the counter goes down till 0 and then button dissapears. But what happens more is, when the
points.html(function(i, val) reaches zero the button did not dissapear. You have to click one more time tu buttons dissapear. How to solve this ?
Try this it will work:
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
val = val*1-1;
if(val == 0){
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
return val;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
When val is 1, look at your code, and see what it's doing:
if(val*1>0) - I don't know why you keep using *1 but never mind that. 1 > 0 is true, so we're in the if block.
return val*1-1; - again, what's the deal with *1? Anyway, this returns 0.
The else block is not run.
The next time you click, if(val*1>0) is false so the else gets run, hiding the buttons.
Instead you should do something like:
If the value is 1, hide the buttons
Either way, return val-1;

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

Combining Javascript Validation Functions

Alright I need help combining the two JavaScript Functions... I have tried multiple times and am not coming up with any luck. There almost identical functions except the fact that I change one number so that it thinks there different textboxes. I tried putting a variable in its place but then it always only validates to the ending number of the loop. Please show me how I may be able to combine these two functions. (Its my only work around and I can not find any examples similar to mine)
First:
<script type="text/javascript">
var QnoText = ['abc_1']; // add IDs here for questions with optional text input
function doSubmit_1() {
var ids_1 = '';
flag_1 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_1 = QnoText[i]+'Certificate_1';
if (CkStatus && document.getElementById(ids_1).value == '') {
alert('Please enter certificate number 1.');
document.getElementById(ids_1).focus();
flag_1 = false;
alert('return flag_1');
}
}
return flag_1;
}
</script>
Second:
<script type="text/javascript">
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit_2() {
var ids_2 = '';
flag_2 = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids_2 = QnoText[i]+'Certificate_2';
if (CkStatus && document.getElementById(ids_2).value == '') {
alert('Please enter certificate number 2.');
document.getElementById(ids_2).focus();
flag_2 = false;
alert('return flag_2');
}
}
return flag_2;
}
</script>
You can pass a parameter in your function with the number of the textbox, like this:
var QnoText = ['abc_2']; // add IDs here for questions with optional text input
function doSubmit(n) {
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
alert('return flag_' + n);
}
}
return flag;
}
doSubmit(1); // for your submit 1
doSubmit(2); // for your submit 2
Is this what you wanted? because is not very clear. If is not feel free to explain.

how can i execute a function once the end of an array is reached?

I have the following code...
var min_val = [{"id":"driverDOA","value":date_of_accident},etc etc...];//put validation elements in an array
for (var i=0;i<min_val.length;i++)//loop through each element if array
{
var object = min_val[i];
if(object.value == "" || object.value == null)//if element is null or empty then execute code
{
document.getElementById(object.id).parentNode.innerHTML += '<div class="prompt accident">*</div>';
document.getElementById('accident-tab').innerHTML += '<div class="prompt accident">*</div>';
return false;
}
else
{
$('.prompt accident').remove();
sendAjaxRequest();
}
}
basically,I'm validating a form by storing the elements required in an array. I then loop through the array and check for any empty values. If the user has left a value then an asterisk is shown next to that element and on the tab for that section.
Once the user has filled in all of the marked form elements then the code removes the asterisks and send an Ajax request.
However at the moment once an empty element has been found it displays the asterisk for that and stops.
What i need is for it to loop through the entire array each time and display all asterisks. I have a feeling that this will be remarkably simple but have been unable to find anything or figure it out.
Any help would be appreciated
var hasError=false;
for (var i=0;i<min_val.length;i++)//loop through each element if array
{
var object = min_val[i];
if(object.value == "" || object.value == null)//if element is null or empty then execute code
{
document.getElementById(object.id).parentNode.innerHTML += '<div class="prompt accident">*</div>';
document.getElementById('accident-tab').innerHTML += '<div class="prompt accident">*</div>';
hasError= true;
//return false; // remove this...
} else $('.prompt accident').remove();
}
if(!hasError) {
sendAjaxRequest();
}
Here
Change return false to noerror=false, add var noerror=true to before the loop and end the function with return noerror
Like this
var noerror=false, min_val = [{"id":"driverDOA","value":date_of_accident},etc etc...];//put validation elements in an array
$('.prompt accident').remove(); // reset
for (var i=0;i<min_val.length;i++) { //loop through each element if array
var object = min_val[i];
if(object.value == "" || object.value == null) { //if element is null or empty then execute code
document.getElementById(object.id).parentNode.innerHTML += '<div class="prompt accident">*</div>';
document.getElementById('accident-tab').innerHTML += '<div class="prompt accident">*</div>';
noerror=false;
}
}
if (noerror) {
sendAjaxRequest();
}
return noerror;
}
Don't return false. Just continue.
Edit: A better solution would be:
var min_val = [{"id":"driverDOA","value":date_of_accident},etc etc...];//put validation elements in an array
var valid = true; // I MADE A CHANGE HERE
for (var i=0;i<min_val.length;i++)//loop through each element if array
{
var object = min_val[i];
if(object.value == "" || object.value == null)//if element is null or empty then execute code
{
document.getElementById(object.id).parentNode.innerHTML += '<div class="prompt accident">*</div>';
document.getElementById('accident-tab').innerHTML += '<div class="prompt accident">*</div>';
valid = false; // AND HERE
}
else
{
$('.prompt accident').remove();
sendAjaxRequest();
}
}
return valid; // AND HERE

Implementing a javascript function to search in a div, getting textrange for the search

How do I get the textrange to do a search for a div (or a form)? Are there scripts already available, or jquery functions that search the text of a div?
I append a form to a div with this code:
$('#'+card_id).append('<form id="frm_search" name="frm_search" class="editableToolbar frm_search_links"> <input type="text" placeholder="Type a string..." name="linkcard_search_string" class="txt_form"> </form>');
I'd like to have a search function that will only look for a string in that div. I specify the text range like this.
txt = window.document.body.getelementbyid(card_id).createTextRange();
The search function is one that I found on the net and that I am trying to update to search the div instead of the entire page. There will be several divs on the page and I want the search to be specific to each. I call that function from search_links(card_id);.
function search_links (card_id, form) {
var search_str = document.frm_search.linkcard_search_string.value;
/* alert('search_links '+search_str); */
return search_linkcard(search_str, card_id);
}
var IE4 = (document.all);
var n = 0;
function search_linkcard(str, card_id) {
alert (card_id + ' ' + str);
var txt, i, found;
if (str == "")
return false;
// Find next occurance of the given string on the page, wrap around to the
// start of the page if necessary.
if (IE4) {
txt = window.document.body.getelementbyid(card_id).createTextRange();
// Find the nth match from the top of the page.
for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) {
txt.moveStart("character", 1);
txt.moveEnd("textedit");
}
// If found, mark it and scroll it into view.
if (found) {
txt.moveStart("character", -1);
txt.findText(str);
txt.select();
txt.scrollIntoView();
n++;
}
// Otherwise, start over at the top of the page and find first match.
else {
if (n > 0) {
n = 0;
search_linkcard(str, card_id);
}
// Not found anywhere, give message.
else
alert("Not found.");
}
}
return false;
}
My specific questions are those at the beginning of the question: How do I specify a text range for the div? Is the syntax I have right? Are there scripts that already do what I want, i.e. search the contents of a specific div?
Did the search with :contains. Did not do one match at a time. Highlighted all matches.
// Open search
function open_search(card_id) {
$('#'+card_id).append('<form id="frm_search" name="frm_search" class="editableToolbar frm_search_links"> <input type="text" placeholder="Type a string..." name="linkcard_search_string" class="txt_form" onclick="clear_search(\''+card_id+'\', this.form);"> </form>');
var frm_elements = frm_search_link.elements;
for(i=0; i<frm_elements.length; i++) {
field_type = frm_elements[i].type.toLowerCase();
switch (field_type)
{
case "text":
frm_elements[i].value = "";
break;
default:
break;
}
}
}
// Close search
function close_search(card_id, form) {
$('form.frm_search_links', $('#'+card_id)).remove();
var card_select = '#'+card_id;
$('.link',$(card_select)).removeClass('search_results');
}
// Search links
function search_links (card_id, form) {
var search_str = document.frm_search.linkcard_search_string.value;
var search_select = '.link:contains('+search_str+')';
var card_select = '#'+card_id;
var result = $(search_select,$(card_select)).addClass('search_results');
if (result.length == 0 || result.length == null) document.frm_search.linkcard_search_string.value = 'Not found.';
}
// Clear search
function clear_search (card_id, form) {
document.frm_search.linkcard_search_string.value = '';
var card_select = '#'+card_id;
$('.link',$(card_select)).removeClass('search_results');
}

Categories