In js library use where .bind("focus.mask") and .bind("blur.mask") function which do blur and focus.
js library:
(function(a){var b=(a.browser.msie?"paste":"input")+".mask",c=window.orientation!=undefined;a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn"},a.fn.extend({caret:function(a,b){if(this.length!=0){if(typeof a=="number"){b=typeof b=="number"?b:a;return this.each(function(){if(this.setSelectionRange)this.setSelectionRange(a,b);else if(this.createTextRange){var c=this.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select()}})}if(this[0].setSelectionRange)a=this[0].selectionStart,b=this[0].selectionEnd;else if(document.selection&&document.selection.createRange){var c=document.selection.createRange();a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length}return{begin:a,end:b}}},unmask:function(){return this.trigger("unmask")},mask:function(d,e){if(!d&&this.length>0){var f=a(this[0]);return f.data(a.mask.dataName)()}e=a.extend({placeholder:"_",completed:null},e);var g=a.mask.definitions,h=[],i=d.length,j=null,k=d.length;a.each(d.split(""),function(a,b){b=="?"?(k--,i=a):g[b]?(h.push(new RegExp(g[b])),j==null&&(j=h.length-1)):h.push(null)});return this.trigger("unmask").each(function(){function v(a){var b=f.val(),c=-1;for(var d=0,g=0;d<k;d++)if(h[d]){l[d]=e.placeholder;while(g++<b.length){var m=b.charAt(g-1);if(h[d].test(m)){l[d]=m,c=d;break}}if(g>b.length)break}else l[d]==b.charAt(g)&&d!=i&&(g++,c=d);if(!a&&c+1<i)f.val(""),t(0,k);else if(a||c+1>=i)u(),a||f.val(f.val().substring(0,c+1));return i?d:j}function u(){return f.val(l.join("")).val()}function t(a,b){for(var c=a;c<b&&c<k;c++)h[c]&&(l[c]=e.placeholder)}function s(a){var b=a.which,c=f.caret();if(a.ctrlKey||a.altKey||a.metaKey||b<32)return!0;if(b){c.end-c.begin!=0&&(t(c.begin,c.end),p(c.begin,c.end-1));var d=n(c.begin-1);if(d<k){var g=String.fromCharCode(b);if(h[d].test(g)){q(d),l[d]=g,u();var i=n(d);f.caret(i),e.completed&&i>=k&&e.completed.call(f)}}return!1}}function r(a){var b=a.which;if(b==8||b==46||c&&b==127){var d=f.caret(),e=d.begin,g=d.end;g-e==0&&(e=b!=46?o(e):g=n(e-1),g=b==46?n(g):g),t(e,g),p(e,g-1);return!1}if(b==27){f.val(m),f.caret(0,v());return!1}}function q(a){for(var b=a,c=e.placeholder;b<k;b++)if(h[b]){var d=n(b),f=l[b];l[b]=c;if(d<k&&h[d].test(f))c=f;else break}}function p(a,b){if(!(a<0)){for(var c=a,d=n(b);c<k;c++)if(h[c]){if(d<k&&h[c].test(l[d]))l[c]=l[d],l[d]=e.placeholder;else break;d=n(d)}u(),f.caret(Math.max(j,a))}}function o(a){while(--a>=0&&!h[a]);return a}function n(a){while(++a<=k&&!h[a]);return a}var f=a(this),l=a.map(d.split(""),function(a,b){if(a!="?")return g[a]?e.placeholder:a}),m=f.val();f.data(a.mask.dataName,function(){return a.map(l,function(a,b){return h[b]&&a!=e.placeholder?a:null}).join("")}),f.attr("readonly")||f.one("unmask",function(){f.unbind(".mask").removeData(a.mask.dataName)}).bind("focus.mask",function(){m=f.val();var b=v();u();var c=function(){b==d.length?f.caret(0,b):f.caret(b)};(a.browser.msie?c:function(){setTimeout(c,0)})()}).bind("blur.mask",function(){v(),f.val()!=m&&f.change()}).bind("keydown.mask",r).bind("keypress.mask",s).bind(b,function(){setTimeout(function(){f.caret(v(!0))},0)}),v()})}})})(jQuery);
In my js file I want to unbind this .bind(focus.mask) and .bind(blur.mask) function ?
My Js:
function applyInputMasks() {
var $form.bind("blur.mask",function(){v(),f.val()!=m&&f.change()}) = $('form');
if ($form.size()) {
// added try catch so that if input field not found then it wont give an error
try{
//$form.find('input:not([skip-masks])[name*=cpf]').mask("999.999.999-99");
//$form.find('input:not([skip-masks])[name*=document]').mask("999.999.999-99");
$form.find('input:not([skip-masks])[name*=date]').mask("99/99/9999");
$form.find('input:not([skip-masks])[name*=postalCode]').mask("999999");
//$form.find('input:not([skip-masks])[name*=phone]').mask("999999999999");
// Postal code
var $postalCode = $form.find('input:not([skip-masks])[name*=postalCode]');
if ($postalCode.attr('skip-resolve-postalcode')) {
$postalCode.mask("999999");
} else {
$postalCode.mask("999999");
$postalCode.mask("999999", {completed: resolvePostalCode});
}
// override the value AFTER applying the mask
var valueToOverride = $postalCode.attr('override-value');
if (valueToOverride) {
$postalCode.val(valueToOverride);
}
} catch (e) {}
}
BRAPRINT.util.log('Masks applied!');
}
In my form where i use this mask function when I enter 6 digit postal code in box in submit form then city is automatically update If i providing incomplete pin code and clicking outside Postal Box in form data is cleared because in library use .bind("focus.mask") and .bind("blur.mask").
I read this tutorial:
http://view.jqueryui.com/mask/tests/visual/mask/mask.html
where say if .bind() convert to .unbind() then incomplete enter postal code in form not cleared after clicking out of the postal code input box.
after read this functionality I was try this in my js file where postal code :
$form.find('input:not([skip-masks])[name*=postalCode]').unbind("focus.mask");
$form.find('input:not([skip-masks])[name*=postalCode]').unbind("blur.mask");
and after this I was clearing all cache but this is not working.
I want data not cleared if i enter incomplete postal code. it is possible ?
I don't want to change in mask library file because this is not a right way.
Rather than unbind you could try e.preventDefault or return false as used in this article on CSS tricks which stops event propagation and bubbling.
http://css-tricks.com/return-false-and-prevent-default/
Related
So, i want to come out with the Javascript which forced user to input / select anything before going to next step, (like forced user to press button, input their name, etc). I am working on Django Framework with mix together with Javascript and HTML together.
Ignore the first part as I am trying to assign each function to the button so the button can do different tasks individually. But it wont work in the intro.js script.
Code snipper are below:
<script>
/*
var btn1=document.getElementById("button1");
var btn2=document.getElementById("button2");
var div=document.getElementById("InputName");
btn1.onclick=function(){
if (div.style.display !=="none") {
div.style.display="none";
} else {
div.style.display="block";
}
};
// this is the crucial part
btn2.onclick=function(){
var steps=[
{element:"#button1",intro:"A button", position:"right"},
{element:"#button2",intro:"This goes away sometimes"}
];
if (div.style.display==="none") {
steps.splice(1,1);
}
introJs().setOptions({
steps:steps
}).start();
} */
var steps=[
{element:"#InputName",intro:"Please fill your name", position:"right"},
{element:"#InputUsername",intro:"Please fill your username"},
{element:"#button1",intro:"Succesfully Filled, press register."}
];
introJs().setOptions({
steps:steps
}).start();
I have an input field that either allows negative and positive numbers, or only positive numbers based on a value of a select.
When changing the value of the select option, I'm trying to modify the rule of the input field like this:
const id = '#myId';
$(id).attr("data-val-range-min", -10000);
removeRules(id);
addRules(id);
$(id).change(); // trying to trigger the validation of the rule
The removeRules is a function:
let removeRules = function removeRules(field) {
$(field).rules('remove');
}
And so is the addRules:
let addRules = function addRules(field) {
let $field = $(field);
if ($field.attr("data-val-required")) {
$field.rules("add", {
required: true,
messages: {
required: $field.attr("data-val-required")
}
});
}
if ($field.attr("data-val-number")) {
$field.rules("add", {
number: true,
messages: {
number: $field.attr("data-val-number")
}
});
}
if ($field.attr("data-val-range")) {
$field.rules("add", {
range: [$field.attr("data-val-range-min"), $field.attr("data-val-range-max")],
messages: {
range: $field.attr("data-val-range")
}
});
}
}
When I change the select in the UI, the data-val-range-min attribute is set correctly, but the rule is not reapplied.
Only when I manually click into the input-field and deselect it again, the rule is applied...
What am I doing wrong here?
Thanks in advance
Only when I manually click into the input-field and deselect it again, the rule is applied...
There's a validation trigger you expect that isn't part of the plugin.
By default, this plugin triggers validation on:
onfocusout - when you leave an element
onkeyup - when you're typing inside a text box
onclick - interactions with radio, checkbox, and select
Adding and removing the rules though is not enough... you'll also need to force a validation test after adding or removing the rule.
Simply call the .valid() method on the element or form when you want to programmatically force validation. Since your OP contains zero HTML markup or working demo, I cannot be more specific with a solution.
I've been using this Background colors on Luhn Algorithm - JavaScript to help build a similar webpage. However unlike the original poster I would like the code not to submit if there is any invalid inputs across any of the fields. I would still like the input fields to change colour (either green for valid or red for invalid).
I believe that I can fix both the name and email using a mixture of pattern (for the name - "[A-Za-z!#$%&'*+-/=?^_`{|}~]+") and using the input type of email for the email section. This is in addition to using 'required' for all the input fields. However it is with the card section that I am having the most trouble with. At the moment, I cannot figure out a way to not allow the form to submit if the card field is red. For example using the code in the original post, I can input '1', the input field will turn red, but I can still submit the form. I am assuming it is something to do with the section below but I am not sure what to change/add:
cardNumberInput.addEventListener("keyup", e => {
const isCardValid = valid_credit_card(e.target.value);
if (isCardValid) {
cardNumberInput.style.backgroundColor = "green";
} else {
cardNumberInput.style.backgroundColor = "red";
}
})
Any help would be greatly appreciated and I apologise for any missing details that you may need, it is my first question here.
Make isCardValid global and add a submit event listener on your form like this
let isCardValid = false
const cardNumberInput = document.getElementById('your-input')
const cardForm = document.getElementById('your-form')
cardNumberInput.addEventListener("keyup", e => {
isCardValid = valid_credit_card(e.target.value);
if (isCardValid) {
cardNumberInput.style.backgroundColor = "green";
} else {
cardNumberInput.style.backgroundColor = "red";
}
})
cardForm.addEventListener('submit', e => {
if(!isCardValid)
e.preventDefault()
})
And the form won't be submitted until the isCardValid is true, if you want to submit the form manually instead of the default HTML submit behaviour, do this
yourForm.addEventListener(e => {
// To prevent default submission always.
e.preventDefault()
if(!isCardValid) return
// Do anything here...
})
So the problem I'm getting is probably something so, so simple (probably), but it's infuriating my as to why it won't work.
What I'd like to do is click on an Edit button on a website, change a value, and Save it.
However, there are over 120 of these changes to be made, and thus over 120 edit clicks, etc.
Hence why I thought I'd use a Data Table.
And here is my subsequent test code;
const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
const globals = require('../../config/globals.js')
var emailEntry = (`input[name='administrator[email]']`)
var passwordEntry = (`input[name='administrator[password]']`)
var existingGtmKey = ("GTM-123456")
var newGtmKey = ("GTM-654321")
var gtmKey = (`//div/input[#value='${existingGtmKey}']`)
var saveButton = (`input[type=submit][value='Save']`)
defineSupportCode(({ Given, Then, When }) => {
Given(/^I've logged into Winit cms$/, () => {
return client
.url('http://winit-stage.bauerpublishing.com/admin/sign_in')
.waitForElementVisible('body', 5000)
// Enter winit email address
.moveToElement(`form#new_administrator ${emailEntry}`, 1,1)
.click(`form#new_administrator ${emailEntry}`)
.setValue(`${emailEntry}`, "*****.*****#*****.co.uk")
// Enter winit password
.moveToElement(`form#new_administrator ${passwordEntry}`, 1,1)
.click(`form#new_administrator ${passwordEntry}`)
.setValue(`${passwordEntry}`, "******")
// Click on the 'Sign in' button
.click("form#new_administrator input[type=submit][value='Sign in']")
})
Then (/^I'm able to change the gtm tag for that site (.*?)$/,
(siteedit) => {
return client
// Click on the 'sites' link
.useXpath()
.click("//a[normalize-space(text())='Sites']")
// Click on Edit button
.click(siteedit)
.click(`${gtmKey}`)
.clearValue(`${gtmKey}`)
// Set new gtm key value
.setValue(`${gtmKey}`, `${newGtmKey}`)
// Click save
.useCss()
.click(`${saveButton}`)
})
})
I thought (wrongly!) this would be pretty straightforward, the script would log into my account, click the edit button, enter new value, press the save key, then do the same for the next website edit button.
It works for the first edit button in the Data table, but then the test fails, giving the following error;
So it looks as though it's running the whole script, and not just the Then part of the script.
But I don't understand why??
Any help would be greatly appreciated.
Many thanks.
I'm having some problems to apply a background-color in the textarea of a ckeditor instance.
When the user clicks on submit without adding any text, it's shown a message telling him to fill all the required fields, and these required fields areas all with the text-fields set with background-color: #CFC183;.
As the ckeditor is created with javascript code, I was using it to try to check if there's any text entered in the text area. if there's no character, I apply the changes.
When I apply in the console this code:
CKEDITOR.instances.body.document.getBody().setStyle('background-color', '#CFC183');
It applies the background exactly like I want to.
So, I added this javascript code in my javascript file to try to manage it, but doesn't seems to be working. Here's my code:
var editorInstance = CKEDITOR.replace('body', { toolbar : 'Full' });
editorInstance.on("instanceReady", function (ev) {
var editorCKE = CKEDITOR.instances.body; readyMap[editorCKE] = true;
editorCKE.setReadOnly(true);
});
var hasText = CKEDITOR.instances.body.document.getBody().getChild(0).getText();
if (!hasText) {
CKEDITOR.on('instanceCreated', function(e) {
e.editor.document.getBody().setStyle('background-color', '#CFC183');
});
}
Firebug shows this error message:
TypeError: CKEDITOR.instances.body.document is undefined
I'm not that good at Javascript, so is there anything wrong with my code?
I already checked this question here, so I believe there's something wrong with my javascript code and I want your help, please.
I guess that you've got an error in this line:
var hasText = CKEDITOR.instances.body.document.getBody().getChild(0).getText();
This is because you're trying to get document element before it's ready (before instanceReady event).
The same error will be thrown here:
if (!hasText) {
CKEDITOR.on('instanceCreated', function(e) {
e.editor.document.getBody().setStyle('background-color', '#CFC183');
});
}
Again - instanceCreated is still too early. You have to move all that code to instanceReady listener. You'll have something like (I'm not sure if I understand what you're trying to achieve):
var editor = CKEDITOR.replace( 'body', { toolbar: 'Full' } );
editor.on( 'instanceReady', function( evt ) {
readyMap[ editor.name ] = true;
editor.setReadOnly( true );
var hasText = editor.document.getBody().getFirst().getText();
if ( !hasText ) {
editor.document.getBody().setStyle( 'background-color', '#CFC183' );
}
} );
As you can see, there is one more issue in your code:
readyMap[editorCKE] = true;
In JS there are no weak maps (yet, but they will be introduced soon). Only strings can be used as a keys of an object. In your case toString() method will be called on editorCKE, which returns [object Object]. That's why I added name property there.