Reset the html element using jquery - javascript

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

Related

Assigning .on() - keyup to dynamically created elements

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.

Delete current parent node in recursion

I created multiple divs which class="extra". Then I add delete buttons to each div in order to remove each div respectively. So my code is:
var exr = document.getElementsByClassName("extra");
for(var i = 0 ;i<exr.length;i++){
var delbt = document.createElement("button");
delbt.className="floatbutton_3 font_b"
delbt.innerHTML="delete";
exr[i].appendChild(delbt);
delbt.onclick= function(i){ return function(){ exr[i].parentNode.removeChild(exr[i]) } }(i);
}
The problem is, the button can't removethe button it should remove. It seems that after last delete, the index is changed. How to avoid this from happening?
Thanks!
Use this within the onclick function to reference the button that was clicked — so by replacing excr[i] with this.parentNode, your code should execute as intended.
Do this...
var exr = document.getElementsByClassName("extra");
for(var i = 0 ;i<inserter.length;i++){
var delbt = document.createElement("button");
delbt.className="floatbutton_3 font_b"
delbt.innerHTML="delete";
exr[i].appendChild(delbt);
delbt.index = i;
delbt.onclick= function(i){ var me = this; return function(){ exr[me.index].parentNode.removeChild(exr[i]) } }(i);
}
Since getElementsByClassName() returns a live set, you could make a shallow copy first:
var exr = [].slice.call(document.getElementsByClassName("extra"), 0);
You could use currentTarget on the click event.
This will only remove the parent div of the button clicked.
var exr = document.getElementsByClassName("extra");
for(var i = 0 ;i<exr.length;i++){
var delbt = document.createElement("button");
delbt.className="floatbutton_3 font_b"
delbt.innerHTML="delete";
exr[i].appendChild(delbt);
delbt.onclick= function( event ){
event.currentTarget.parentElement.remove();
}
}
The code looks like it should work, but only as long as you don't add or remove elements. And that's what you are doing.
There is a simpler and more reliable solution: You can use this inside the event handler to refer to the current element.
delbt.onclick = function() {
var div = this.parentNode; // you want to remove the div, not the button
div.parentNode.removeChild(div);
};
I recommend to read the excellent articles about event handling on quirksmode.org, especially about traditional event handling (since that's what you are using).
getElementsByClassName() returns an HTMLCollection. This is a live list that changes when the underlying structure changes. So even if you don't activly delete the elements from the list, they still will be removed from it automatically when you remove the corresponding HTML Element.
By passing i to the anonymous function, you kind of fixed the index. So whenever you click on the third delete button it will try to delete the third element in the list. But if you have already deleted the first and the second element, the list will be modified too. So your third button will be represented by the first item in your list but it will try to find the third one.
To avoid this problem you can pass the complete element to the anonymous function and not just the index:
for(var i = 0 ;i<exr.length;i++){
var delbt = document.createElement("button");
delbt.className="floatbutton_3 font_b"
delbt.innerHTML="delete";
exr[i].appendChild(delbt);
delbt.onclick = function(el){ return function(){ el.parentNode.removeChild(el) } }(exr[i]);
}
I'll add a jQuery solution:
$('.extra').append(function() {
return $('<button />', {'class':'floatbutton_3 font_b', html:'delete'});
});
$('.floatbutton_3').on('click', function() {
$(this).closest('div').remove();
});
FIDDLE

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.

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.

Detect clicks of images inside iframe

I cant figure out why this isn't working. It's probably something simple. The iframe is from the same domain as parent page.
I know I can use jQuery, but I want to learn to do it in pure JavaScript.
My code so far:
document.getElementById('my_iframe').onload = function() {
document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img').onclick = function() {
alert("image in iframe was clicked");
}
}
Forget the frame business for a second, and look at this code:
document.getElementsByTagName('img').onclick = function() {
Will that ever work? No. You are getting an object (a NodeList, to be precise) containing all the img elements in the document. You are adding an onclick property to that object. Not to the elements themselves: to an object that points to them. The function will never be fired because it is never applied to any elements.
You should do exactly the same as you normally would: loop though all the images you've found and apply the function to them individually.
var onclickFn = function() {
alert("image in iframe was clicked");
},
images = document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = onclickFn;
}
document.getElementsByTagName is returning a collection of images. You can't just set a click handler on the entire collection. You need to loop through them one at a time.
var allimgs = document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img');
for (var i = 0; i < allimgs.length; i++) {
allimgs[i].onclick = function() {
alert("image in iframe was clicked");
};
}

Categories