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

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

Related

Function not running after submitting name into prompt

entering correct student name associated with image within prompt but it is not running the "checkAnswer" function
this is the function
function checkAnswer() {
if (document.getElementById('response').value == personArray[currentId].firstname) {
//NOTE TO STUDENT: apply the class to reduce the opacity of the image,
//takeout the mouse events because they shouldn't be there anymore
document.getElementById(currentId).className = "opClass";
document.getElementById(currentId).removeAttribute("onclick");
document.getElementById(currentId).removeAttribute("onmouseover");
//superimpose name on image
var divVar = document.createElement('div');
divVar.setAttribute('id', currentId + 'name');
document.getElementById('pic-grid').appendChild(divVar);
var textNode = document.createTextNode(personArray[currentId].firstname);
divVar.appendChild(textNode);
document.getElementById(currentId + 'name').style.position = "absolute";
document.getElementById(currentId + 'name').style.top = y;
document.getElementById(currentId + 'name').style.left = x;
//clean up loose ends: hide the prompt, turn the frame white so it doesn't change to aqua on the rollover, erase the response and message
document.getElementById('prompt').style.display = 'none';
document.getElementById(currentId).parentNode.style.backgroundColor = 'white';
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
} else {
if (document.getElementById('message').innerHTML == "Wrong!") {
document.getElementById('message').innerHTML = "Incorrect answer!"
} else {
document.getElementById('message').innerHTML = "Wrong!"
}
}
return false;
}
Basically if the user enters the correct name in the prompt that is associated with the image they selected, the image should fade (opacity) and display the name of the student in the image (style position, top, & left) or if they enter the wrong name they are told within the prompt that they are wrong or incorrect.
As soon as I enter the correct student name, the prompt disappears and nothing happens or if I do the wrong name, it disappears as well.
here is the populateImages function that i forgot to place in here, sorry.
function populateImages() {
for (var i = 0; i < personArray.length; i++) {
var imageContainer = document.createElement("div");
var image = document.createElement("img");
imageContainer.classList.add('frame');
image.src = personArray[i].url;
image.setAttribute('onclick','promptForName(this)');
image.setAttribute('onmouseover','styleIt(this)');
image.setAttribute('onmouseout','unStyleIt(this)');
imageContainer.appendChild(image);
document.getElementById('pic-grid').appendChild(imageContainer);
}
}
Here's my HTML:
<body onload="populateImages()">
<header>
<h2>Class Flashcards</h2>
<h3>Click on a student to guess their name</h3>
<h4>Concepts: Rollovers, Opacity, Showing and Hiding Elements, Arrays of Objects, Adding and Removing Elements/Attributes Dynamically to the DOM,
Accessing Elements using parentnode</h4>
</header>
<div id="pic-grid">
</div>
<div id="prompt">
What is this student's name?<br>
<form onsubmit="return checkAnswer()">
<input type="text" id="response" name="quizInput">
</form>
<div id="message"></div>
</div>
</body>
the form is being submitted through this function and shows up when image is selected:
function promptForName(element) {
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
document.getElementById('prompt').style.display = 'block';
currentId = element.id;
x = element.offsetLeft;
y = element.offsetTop;
x = x + 20;
y = y + 20;
document.getElementById('prompt').style.position = "absolute";
document.getElementById('prompt').style.top = y;
document.getElementById('prompt').style.left = x;
document.getElementById('response').focus();
}
return false cancels submit action. you must insert a return true if everything is ok
try this function
function checkAnswer() {
if (document.getElementById('response').value == personArray[currentId].firstname) {
//NOTE TO STUDENT: apply the class to reduce the opacity of the image,
//takeout the mouse events because they shouldn't be there anymore
document.getElementById(currentId).className = "opClass";
document.getElementById(currentId).removeAttribute("onclick");
document.getElementById(currentId).removeAttribute("onmouseover");
//superimpose name on image
var divVar = document.createElement('div');
divVar.setAttribute('id', currentId + 'name');
document.getElementById('pic-grid').appendChild(divVar);
var textNode = document.createTextNode(personArray[currentId].firstname);
divVar.appendChild(textNode);
document.getElementById(currentId + 'name').style.position = "absolute";
document.getElementById(currentId + 'name').style.top = y;
document.getElementById(currentId + 'name').style.left = x;
//clean up loose ends: hide the prompt, turn the frame white so it doesn't change to aqua on the rollover, erase the response and message
document.getElementById('prompt').style.display = 'none';
document.getElementById(currentId).parentNode.style.backgroundColor = 'white';
document.getElementById('response').value = "";
document.getElementById('message').innerHTML = "";
return true; // return true if everything is ok
} else {
if (document.getElementById('message').innerHTML == "Wrong!") {
document.getElementById('message').innerHTML = "Incorrect answer!"
} else {
document.getElementById('message').innerHTML = "Wrong!"
}
return false; // return false if error
}
}

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

Add different event listener to a set of elements in a loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
Hello people of the internet,
I have a set of buttons and if a button is clicked it's content should be appended to a text field's content.
Lets say I have three buttons: [first] [second] [third]
My addEventListener-implementation results in "third" appended to the in text field's content, regardless which button I press. I don't know hot to fix this.
function setupListeners() {
var targetInputField = d.querySelector("#expression");
var t = d.querySelectorAll(".expression-button").length;
for (var i = 1; i <= t; i++) {
var btnElem = d.querySelector("#expression-button-"+i);
btnElem.addEventListener('click', function() {
if (targetInputField.value == "") {
targetInputField.value = btnElemLocal.innerText;
}
else {
targetInputField.value += ";"+btnElemLocal.innerText;
}
});
}
}
What I want:
If I click all of the three buttons in a row, the text field's content should be :
"first;second;third"
And not :
"third;third;third"
Put the click event code inside another function (btnClick in my example) and just call it when you attach the event in .addEventListener() inside the loop, then use this to refer to the current clicked element :
function btnClick() {
var targetInputField = d.querySelector("#expression");
if (targetInputField.value == "") {
targetInputField.value = this.innerText;
}
else {
targetInputField.value += ";"+this.innerText;
}
}
Hope this helps.
var d = document;
function setupListeners() {
var t = d.querySelectorAll(".expression-button").length;
for (var i = 1; i <= t; i++) {
var btnElem = d.querySelector("#expression-button-"+i);
btnElem.addEventListener('click', btnClick);
}
}
function btnClick() {
var targetInputField = d.querySelector("#expression");
if (targetInputField.value == "") {
targetInputField.value = this.innerText;
}
else {
targetInputField.value += ";"+this.innerText;
}
}
setupListeners();
<button class='expression-button' id='expression-button-1'>First</button>
<button class='expression-button' id='expression-button-2'>Second</button>
<button class='expression-button' id='expression-button-3'>Third</button>
<input id='expression' />

placeholder javascript fallback for textarea not working

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 ?

Multiple javascript live updating input fields

I would like to have more than one input which can output what the user has put inside the input box on one page and for it to update live. I can currently only get one input to work live.
HTML Code
<input type=text></input><!-- inputs live text -->
<p id="headingone"></p><!-- outputs live text -->
Javascript Code
function reverse(s) {
return s.split('').reverse().join('')
}
function set(el, text) {
while (el.firstChild) el.removeChild(el.firstChild);
el.appendChild(document.createTextNode(text))
}
function setupUpdater() {
var input = document.getElementsByTagName('input')[0]
, orig = document.getElementById('headingone')
, oldText = input.value
, timeout = null;
function handleChange() {
var newText = input.value;
if (newText == oldText) return;
else oldText = newText;
set(orig, newText);
}
function eventHandler() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(handleChange, 50);
}
input.onkeydown = input.onkeyup = input.onclick = eventHandler;
}
setupUpdater();
document.getElementsByTagName('input')[0].focus();

Categories