Assigning .on() - keyup to dynamically created elements - javascript

The idea of this script is to allow dynamically created elements to respond to a keyup function that changes the inner html (or jQuery text()) based on what is inside of a text form.
Each dynamically created element has it's own text form and title. So whatever you type in that given element's text form should become the title for that element which is wrapped in tags.
I've tried a few ways but I just cant get it to work. What is the best way to go about this?
Here's my latest attempt - http://jsfiddle.net/gnkxxgjz/1/
$('body').on('keyup', '.qForms', function() {
var nameOfLoan = [];
var loanOfName = function(t) {
if ($(this).hasClass('.loanNameV'+t)) {
$('body').on('keyup', '.qForms', function() {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
else {
return false;
}
};
for (var t=1; t < z; t++) {
nameOfLoan[t] = loanOfName(t);
}
for (var j=1; j < z; j++) {
nameOfLoan[j]();
}
});

Take a look at this Fiddle
<button onclick="crea()">create</button>
<div id="d1">
</div>
function crea(){
$('#d1').append( $("<h2></h2><input>").on('keyup',function(){
$(this).prev().html( $(this).val() );
}) )
}

Something along these lines:
$(document).on("keypress", $("input"), function(e){
console.log($(e.target).attr("id"))
});
This will print to the console the id attribute of any input field you type into. Please provide how the input and text elements are related and I might be able to link them in this code piece.

Related

Reset the html element using jquery

I am having a div with lot of elements inside the div. For some scenario i want to reset the value for the div's element to the initial status.
Is there any way to do this??
if($(window).width()<=960){
$('#desktopCart').html(/i want to reset this element/);
}
if($(window).width()>960){
$('#mobileCart').html("/i want to reset this element/");
}
try:
$( document ).ready(function() {
var initialValue =$('#mobileCart').html();
});
if($(window).width()<=960){
$('#desktopCart').html(initialValue);
}
if($(window).width()>960){
$('#mobileCart').html(initialValue);
}
use .empty() of jquery
$("#divId").empty();
It will remove all the child elements and text in that particular element.
If you want to restore the initial state of the div, you should save the initial innerHtml to a variable a document.ready().
Like,
var desktopCart;
var mobileCart;
$(document).ready(function(){
desktopCart=$('#desktopCart').html();
mobileCart=$('#mobileCart').html();
});
Then restore the html whenever you want,
if($(window).width()<=960){
$('#desktopCart').html(desktopCart);
}
if($(window).width()>960){
$('#mobileCart').html(mobileCart);
}
First clone the element instead of saving the content. Then use replaceWith to restore it.
$(document).ready(function() {
var divClone = $("#mobileCart").clone();
if($(window).width()<=960){
$('#desktopCart').html(/i want to reset this element/);
}
if($(window).width()>960){
$("#mobileCart").replaceWith(divClone);
}
});
For further reference, please see the below link.
How can I "reset" <div> to its original state after it has been modified by JavaScript?
What if I have multiple elements ? And want to save the elements' state at regular intervals ? And regularly reset them ? There might not be just one of them .... maybe I will have a and p and div and too many of them. But I want to reduce typing ? What do I do ?
I am glad you asked.
// Write Once: Use Anywhere functions
$.fn.reset = function () {
var list = $(this); // list of elements
for(var i = 0, len = list.length; i < len; i++){
list.eq(i).text(list.eq(i).data("initValue"));
}
};
$.fn.saveState = function () {
var list = $(this); // list of elements
for(var i = 0, len = list.length; i < len; i++){
list.eq(i).data("initValue", list.eq(i).text());
}
}
$("div").saveState(); // simple call to save state instantly !
// value change!
$("div:nth-child(2)").text("99999");
$(window).resize(function () {
if ($(window).width() <= 960) {
$("div").reset(); // simple call to reset state instantly !
}
});
DEMO Resize window

html dom editing/adding attributes/functions

I have got something like this in html
<div class="change"><div>
<div class="change"><div>
<div class="change"><div>
<div class="change"><div>
Now here we go for the java script
var base = document.getElementsByClassName("change");
base[0].setAttribute();
console.log(base[0]);
From the console I can see that I"m getting an object but I can't edit it this way, is there any other possibility to edit/add attributes( i need to add a onclick function to like 100 elements).
It's pretty difficult to get the higer object by document.getElementById,
so... anyone got a solution for this?^^
You can add attributes like this
var element = document.getElementByClassName('change')[0];
element.setAttribute(attributeName,attributeValue);
Just use jQuery. Then it's just a matter of doing something like the following:
$(document).ready(function () {
$('.change').click(function () {
$(this).attr('class', 'new-value');
});
});
JSFiddle demo here.
You can accomplish this using the code below:
var nodes = document.querySelectorAll('.change'),
length = nodes.length,
counter = 0;
for (; counter < length; counter += 1) {
// set an attribute.
nodes[counter].setAttribute('data-test', 'test' + counter);
// add a click event.
nodes[counter].addEventListener('click', function () {
alert('Yep, you clicked me');
}, false);
}
Demo here
Using jQuery:
$('.change').on('click', function() {
// Action
});
Syntax of setAttributte:
Object.setAttributte(attribute, value);

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

JavaScript: get custom button's text value

I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))

Remove onclick event from img tag

Heres my code:
<div id="cmdt_1_1d" class="dt_state1" onclick="sel_test(this.id)">
<img id="cmdt_1_1i" onclick="dropit('cmdt_1_1');" src="/site/hitechpackaging/images/items/bags_menu.jpg ">
<span class="dt_link">
BAGS
</span>
</div>
Unfortunately I cannot modify this file, is there a way using javascript to disable the onclick from the img tag only.
I was using this script but it disable the onclick event from all images. But i want only from this component
var anchorElements = document.getElementsByTagName('img');
// for (var i in anchorElements)
// anchorElements[i].onclick = function() {
// alert(this.id);
// return false;
// }
Any ideas will be appreciated.
Edited:
Is there a way to stop the function dropit from executing, is it possible using javascript. On page load, etc.
another option is can i rename the img file using javascript??
document.getElementById('cmdt_1_1i').removeAttribute("onclick");
var eles = document.getElementById('cmdt_1_1d').getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
eles[i].onclick = function() {
return false;
}
Lots of answers, but the simplest is:
document.getElementById('cmdt_1_1i').onclick = '';
try something like this:
var badImage = document.getElementById("cmdt_1_1i");
badImage.onclick = null;
badImage.addEventlistener("click",function(e){
e.preventDefault();
e.stopPropagation();
return null;
},true);
If you later need to restore the onclick property, you can save it in a field before overwriting it:
document.getElementById(id).saved=document.getElementById(id).onclick;
document.getElementById(id).onclick = '';
so that later you can restore it:
document.getElementById(id).onclick=document.getElementById(id).saved;
This can be useful especially in the case, in which the original onclick property contained some dynamically computed value.
You can programmatically reassign event listeners. So in this case, it might look something like:
const images = document.querySelectorAll('#cmdt_1_1d img')
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() => {}
}
...where the query above returns all of the img tags that are descendants of the element with ID cmdt_1_1d, and reassigns each of their onclick listeners to an empty function. Therefore no actions will take place when those images are clicked.

Categories