placeholder javascript fallback for textarea not working - javascript

The below is the html code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Please help me point out the mistake. placeholder fallback functionality is not working.I have been debugging it from long time.
Below is the link for fiddle:
check the functionality in ie9 and below as they doesn't support placeholder attribute:
http://jsfiddle.net/DxcYW/
Thanks

Here it is in pure JavaScript:
(function (D, undefined) {
'use strict';
var i, length, placeholder, textareas;
function hidePlaceHolder (placeholder) {
return function (e) {
var target;
target = e.target || e.srcElement;
if (target.value === placeholder) {
target.value = '';
}
};
}
function showPlaceHolder (placeholder) {
return function (e) {
var target;
target = e.currentTarget || e.srcElement;
if (target.value === '') {
target.value = placeholder;
}
};
}
if (! ('placeholder' in D.createElement('textarea'))) {
textareas = D.getElementsByTagName('textarea');
length = textareas.length;
for (i = 0; i < length; i += 1) {
placeholder = textareas[i].getAttribute('placeholder');
textareas[i].value = placeholder;
if (textareas[i].addEventListener) {
textareas[i].addEventListener('focus', hidePlaceHolder(placeholder));
textareas[i].addEventListener('blur', showPlaceHolder(placeholder));
} else {
textareas[i].attachEvent('onfocus', hidePlaceHolder(placeholder));
textareas[i].attachEvent('onblur', showPlaceHolder(placeholder));
}
}
}
}(document));

try putting your JS in
<script> ... </script>
tags. :)

My findings and solution:
Input fields have value attribute but TEXTAREA doesn't have it.
So when we use inputObj.defaultValue="sometext" for input tag it sets the default value as well as current value to sometext, if we dont define the attribute value="something" in the input tag.This works fine from ie9 and above. For below versions if we don't define value="sometext" inputObj.defaultValue="sometext" won't set current value as the default value by itself. For this we can do two things:
we have to manually give value="something which is equal to placeholder text"
we can get the value of placeholder through javascript and set the value from there.
This is not the case with textarea. Textarea doesn't have a attribute value. So when we use textareaObj.defaultValue="sometextarea text" then the default value is set to the given text but not the value itself as we don't have value attribute.value in textarea is nothing but the content between the textarea tags.
Difference between defaultvalue and value:
default value remains the same once it is set.
value is the current value which is being modified by javascript or ourself my typing into the textfield.
For my above issue I found a workaround just by adding one more line to my code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].value = fields[i].getAttribute('placeholder');//setting the value
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Thank you guys for your quick replies and I pity the guy who voted down the question. I feel it is a good question. isn't it ?

Related

How to Prevent/disable copy and paste in Tinymce

I am setting up the tinymce on my system, and want to disable the copy and paste for the user in the tinymce editor, but no where I find the solution. How can I disable the copy paste in tinymce
I have implemented the
Disable pasting text into HTML form
But it is working only in simple text area but not in tinymce textarea
<script>
// Register onpaste on inputs and textareas in browsers that don't
// natively support it.
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
</script>
</head>
<body>
<!-- Not Working here-->
<textarea class="tinymce" onpaste="return false;"></textarea>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="plugin/tinymce/init-tinymce.js"></script>
<!-- Working here-->
<textarea onpaste="return false;"></textarea>
</body>
I expect that, it should work in the textarea of tinymce,
Thank you in advance, I will be very gratefull
have you tried to prevent the default
document.addEventListener('paste', function(e){
e.preventDefault();
});
I also read that you can intercept paste in the tinymce.init
paste_preprocess: function(plugin, args) {
console.log(args.content);
args.content = '';
}
Hope that one of those methods works out for you

Kendo Validator always says multi-select is invalid

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");

Copy to Clipboard function for multiple buttons how to switch from id to class identifier

I need some help please i have a nice copy to clipboard function which works well for ids and only one button on website.
But I need it to be done for multiple buttons and multiple values with class identifier i think but i really got no idea how to switch/change it from id identifier to class identifier and make it work for multiple buttons and inputs on one page.
Could you please help me?
This is my HTML button with ID identifier which i need for class to make it work for multiple buttons:
<button type="submit" id="bbcopyButton" class="btn btn-md btn-primary-filled btn-form-submit">BB Code copy</button>
This is the Input to copy from also by ID but i need to make it work with Class in order to copy more values from different input types:
<input type="text" class="form-control" id="bbcopyTarget" value="valueno.1" name="name" readonly="readonly" onclick="focus();select();">
I hope you understand what i want
Here is finally the Javascript Code which should be switched into class identifier in order to copy several/multiple values on one page:
document.getElementById("bbcopyButton").addEventListener("click", function() {
copyToClipboardMsg(document.getElementById("bbcopyTarget"), "bbcopyButton");
});
function copyToClipboardMsg(elem, msgElem) {
var succeed = copyToClipboard(elem);
var msg;
if (!succeed) {
msg = "Press Ctrl+c to copy"
} else {
msg = "BB Code copied <i class='lnr lnr-thumbs-up'></i>"
}
if (typeof msgElem === "string") {
msgElem = document.getElementById(msgElem);
}
msgElem.innerHTML = msg;
msgElem.style.background = "green";
msgElem.style.border = "2px solid green";
setTimeout(function() {
msgElem.innerHTML = "BB Code copy";
msgElem.style.background = "";
msgElem.style.border = "";
}, 2000);
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
Some help would be great.
Thanks.
I will make it a little bit clearer when i have a second button with same ID the Javascript/JQuery Code does nothing and cant point to second input value
This would be the second Button:
<button type="submit" id="bbcopyButton" class="btn btn-md btn-primary-filled btn-form-submit">BB Code copy</button>
And the second input where i want to copy from:
<input type="text" class="form-control" id="bbcopyTarget" value="valueno.2" name="name" readonly="readonly" onclick="focus();select();">
Hope this helps to understand better
Put this code:
var but = document.getElementsByClassName('btn btn-md btn-primary-filled btn-form-submit');
var txt = document.getElementsByClassName('form-control');
for (let x=0; x < but.length; x++){
but[x].addEventListener("click", function() {
copyToClipboardMsg(txt[x], but[x]);
}, false);
}
Instead of:
document.getElementById("bbcopyButton").addEventListener("click", function() {
copyToClipboardMsg(document.getElementById("bbcopyTarget"), "bbcopyButton");
});
This will only work if number of buttons = number of txt fields. If you want to avoid using let then you need to change it like this:
var but = document.getElementsByClassName('btn btn-md btn-primary-filled btn-form-submit');
var txt = document.getElementsByClassName('form-control');
for (var x = 0; x < but.length; x++) {
(function(x) {
but[x].addEventListener("click", function() {
copyToClipboardMsg(txt[x], but[x]);
}, false);
})(x);
}

Input to make "Enter" forbidden

I have a HTML input in my site and i want to make "ENTER" forbidden in this box.
I mean user should not be able to enter into the box and if the user pasted some text, the enters gets converted to "space character" auto.
you can put this in the onchange of the text input/textarea
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '');|
put this inside your header script tags and you should be good.
<script type="text/javascript" language="javascript">
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA')
for(var i = 0, l = txts.length; i < l; i++) {
var func = function() {
var text = this.value;
text = text.replace(/\r?\n/g, '');
this.value = text;
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
}
</script>
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Uses setTimeout and clearTimeout
<input type='text' id='text'>
var timer = null;
$('#text').keydown(function(){
clearTimeout(timer);
timer = setTimeout(doStuff, 1000)
});
function doStuff() {
alert('do stuff');
}
use the doStuff() function to execute code 1 second after user stops typing

Jquery form get default values

If I have code like this:
<form id="test_form">
<input type="text" value="Original value" />
</form>
Then using jQuery I run this code:
$('#test_form input').val('New value');
So input have new value, but I wanna get the old one, so I do:
$('#test_form')[0].reset();
now $('#test_form input').val() == 'Original value';
But reset method reset all form inputs and restore there default values, so how can I restore default value just in definite input?
on jQuery 1.6+
$('#test_form input').prop('defaultValue');
on older versions use .attr() instead of .prop()
You can use the defaultValue property:
this.value = this.defaultValue;
For example, the following code would reset the field to its default value when the blur event is fired:
$("#someInput").blur(function() {
this.value = this.defaultValue;
});
And here's a working example.
You could very easily build a plugin to do this, using the defaultValue property, which corresponds to the original state of the element.
$.fn.reset = function() {
this.each(function() {
this.value = this.defaultValue;
});
};
You can then call this plugin like this:
$('someSelector').reset();
Try whatever the jQuery equivalent to JavaScript's .getAttribute('value') is - the attribute does not change even if the value itself does.
I would suggest using placeholder attribute for inputs and textareas.
// Sample Usage
// $(document).ready(function(){ $.snapshot("#myForm"); }); Take shapshot
// event, function(){ $.reset("#myForm"); } Rest Form On Some Event
(function($) {
$.fn.getAttributes = function() {
var attributes = {};
if(!this.length)
return this;
$.each(this[0].attributes, function(index, attr) {
attributes[attr.name] = attr.value;
});
return attributes;
}
})(jQuery);
(function($)
{
jQuery.snapshot = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
if(elements && elements.length)
{
elements.each(function(){
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
var safe_attributes = {};
for(i in attributes)
{
var jq_attr = $(this).attr(i);
if(jq_attr != "undefined")
{
safe_attributes[i] = jq_attr;
}
}
if(tagName == "select")
{
var option = $(this).find("option:selected");
if(option && option.length)
{
var init_selected = option.attr("value");
safe_attributes['init_selected'] = init_selected;
}
}
if(tagName == "textarea")
{
var init_value = $(this).val();
safe_attributes['init_value'] = init_value;
}
$.data( $(this).get(0), "init_attr", safe_attributes );
});
}
}
jQuery.reset = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
var reset_btn = $('<input type="reset" name="reset" />');
form.append(reset_btn);
reset_btn.trigger("click");
reset_btn.remove();
if(elements && elements.length)
{
elements.each(function(){
var init_attributes = $(this).data("init_attr");
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
for(i in attributes)
{
if(i.toLowerCase() == "value" || i.toLowerCase() == "checked" || i.toLowerCase() == "selected")//if(i.toLowerCase() != "type")
{
var attr_found = false;
for(a in init_attributes)
{
if(i == a)
{
$(this).attr(a, init_attributes[a]);
attr_found = true;
}
}
if(!attr_found)
{
$(this).removeAttr(i);
}
}
}
if(tagName == "select" && 'init_selected' in init_attributes)
{
$(this).find("option:selected").removeAttr("selected");
var option = $(this).find("option[value="+init_attributes['init_selected']+"]");
if(option && option.length)
{
option.attr("selected", "selected");
}
}
if(tagName == "textarea")
{
if('init_value' in init_attributes)
{
$(this).val(init_attributes['init_value']);
}
}
$(this).trigger("change");
});
}
}
})(jQuery);

Categories