How to save data using jQuery? - javascript

I have some dynamic data in my <div> element. Look at the sample below:
<div>345</div>
<div>3245</div>
When I click on the div element, the nested value will change.
var someVar = $(this).find(div);
someVar.empty();
someVar.append("<div>Number has changed</div>");
Sample:
<div>345</div>
<div>Number has changed</div>
And when I click again on the div, I need to return the previous value:
<div>345</div>
<div>3245</div>
Here's the question: How do I keep this value for returning the number every time I click on the div with changed text inside of it?

you need create some data attribute store the previous value.The each time click get the data from attribute and restore the current text to attr like this data-prev.No need to append .html() is enought to toggle
updated
$('div').click(function(){
var prev=$(this).html();
$(this).html($(this).data('prev'));
$(this).data('prev',prev)
console.log($(this).data('prev'))
})
.nested{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>345</div>
<div data-prev="<div class='nested'>Number has changed</div>">3245</div>

You can use jQuery 'data' method.
$( "div" ).data( "number", 1 )
Then read it with:
( $( "div" ).data( "number" ) )
Documentation:
https://api.jquery.com/data/

Related

Getting a dom element before its displayed?

I currently am trying to use a library that requires a dom element to be passed to it.
However I am dynamically creating a layout like this so the dom element doesnt exist at that time.
I wanted to know how i can pass the current dom element which will eventually be rendered ?
function addControl(domeElement)
{
jsonTree.create(data, domeElement);
}
function () {
$(container).append(
"<div class='myfancydiv'>" + addControl(this Div) + "</div>"
);
You should use appendTo so that you can easily retrieve the element after it is appended, then pass that element to your function:
let domElement = $("<div class='myfancydiv'></div>").appendTo(container)[0];
addControl(domElement);
Note: [0] is simply a way to grab the actual DOM element from the JQuery Object, instead of a reference to the JQuery Object itself.
Example:
function demo(domEle) {
$(domEle).css({color: "blue"});
}
let el = $( "<p>Test</p>" ).appendTo( ".inner" )[0];
demo(el);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>

Jquery - if element contains a class, add HTML after element

I've got a booking form.booking-wrap with 2 elements in it, div#booking and then div.quantity
<form class="booking-wrap">
<div id="booking"></div>
/* insert div#message IF div.quantity is present inside div.booking-wrap */
<div class="quantity"></div>
</form>
The div.quantity is only present dynamically for some bookings.
What I am trying to achieve is that if the div.quantity is present, then I would like to insert an additional html div#message, but this new div should appear after div#booking and before div.quantity
I am trying the following jQuery:
if($('.booking-wrap:has(div.quantity)')){
$('#booking' ) .after( '<div id="message">Message</div>');
}
But that doesn't seem to work.
I then tried this:
$('.booking-wrap:has(div.quantity)').append($('<div id="message">Message</div>'));
This works and the new div appears, however it is just next to the quantity div.
How can I get it to show after the #booking , but before .quantity?
Any selector returns an object, you should check the length property of the returned object. Like $('.booking-wrap:has(div.quantity)').length
Though, I prefer $('.booking-wrap > div.quantity').length
if($('.booking-wrap > div.quantity').length){
$('#booking').after('<div id="message">Message</div>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="booking-wrap">
<div id="booking">booking</div>
<div class="quantity">quantity</div>
</form>
Try using prepend instead of append, since the selector $('.booking-wrap:has(div.quantity) will return the (div.quantity) element.
Example:
$('.booking-wrap:has(div.quantity)').prepend($('<div id="message">Message</div>'));
You can use "hasClass()" jQuery function to check class is exist or not:
Try This
if($( ".booking-wrap" ).children('div').hasClass( "quantity" )){
jQuery('<div id="message">Message</div>').insertAfter('.booking');
}
Try This jQuery.
if($(".quantity").length ){
$('#booking' ).after( '<div id="message">Message</div>');
}
You need to put the div you are adding within a function.
if($('.booking-wrap:has(div.quantity)')){
$( "#booking" ).after(function() {
return '<div id="message">Message</div>';
});
}

jquery random element id for every loop

sorry i'm new in jquery and i need help :-(
i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)
for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:
$(document).ready(function() {
$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);
$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );
});
});
$(".anot-body") does a search of the whole document, if you want to find a particular element in another element you need to do a search from that parent element.
In your case you would do a search on the particular .parts element that is currently being iterated over in your $.each() callback
$('.parts').each(function(index,element){
var parent = $(element);
var ran=Math.floor(Math.random()* 1000000);
parent.find('.anot-head').attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
parent.find('.anot-body').attr( "id","s"+ran );
});
No need to use random.... use index of each
$('.parts').each(function(index){
var $part = $(this);
$part.find('.anot-head').attr({"data-toggle":"collapse","href":"#s"+index});
$part.find('.anot-body').attr("id","s"+ index);
});

Get HTML with current input values

I need to get the HTML of the whole page, with the current values of all inputs in their value="...".
I've tried this:
document.getElementById("htmlId").innerHTML;
and this:
$('html').html();
but the both return the HTML page but without the input values.
I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.
An input has a value attribute that determines the initial value of the input. It also has a value property that holds the current value of the input.
It appears that you want to export the HTML markup of the page, where the value attributes of all inputs are set to the value of the value property.
You can do so as follows:
// first, set `value` attribute to value of property for all inputs
$('input').attr('value', function() {
return $(this).val();
});
// export HTML with correct `value` attributes
$('html').html();
And here is a little demo of that in action.
$('#export').on('click', () => {
$('input').attr('value', function() {
return $(this).val();
});
console.log($('html').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Some paragraph.</p>
<input type="text" value="initial value" />
<h1>Header</h1>
<p>Another paragraph</p>
<button id="export">Export page</button>
for input value inside html use this code may got some help
$("#html input[type=text]").each(function(index,value) {
val = $("#"+value.id).val();
alert(val)
});
Assuming "html" itself is an id of an element, you can try cloneNode.
var clonedElem = document.getElementById("html").cloneNode(true);
This clonedElem is a DOM object which contains both html as well as values ( and all other attributes). You can now use this DOM for all your purposes.
For Eg. If you wish to insert it into another element, you can do like
document.getElementById('newElement').appendChild(clonedElem)
This will put the entire node with its values
As commented before,
.html() or innerHTML will return the markup. value is a property associated with input elements. Yes you have a tag, but eventually you end you initiating this property. So when you change value dynamically, it updates property and not attribute
You will have to loop over all the inputs and set value attribute.
function updateAttribute() {
var parent = document.querySelector(".content");
var inputs = parent.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("value", inputs[i].value);
}
}
Working Demo
If you want to get input values I will do with .attr to change dynamically element value !
$("ButtonToCatchInputValue").click(function(){
$("input").each(function(){
$(this).attr("value",this.value);
});
console.log($("html").html());
});
Use document.cloneNode to clone the whole document with retaining the state of the html.
cloneNode has a boolean parameter that denotes the following
true - Clone the node, its attributes, and its descendants
false - Default. Clone only the node and its attributes
For more details check this document
function cloneMe() {
var newelement = document.cloneNode(true);
console.log(newelement.getElementsByTagName("input")[0].value)
}
<input type="text" value="Change My Value" style="width:100%" />
<input type="submit" onclick="cloneMe()" value="Clone Now" />

Appened is not working with calling id which is unique

This my code when click the button i want to display button dynamic id to the specific place by calling that id:
this is my code:
<span id="2" class="view-details">View Details</span>
$( ".view-details" ).on( "click", function() {
var group = field.attr("id");
console.log(group); //Ex: value is coming as "2"
$("#groupID").append( group );
My HTML
<span id="groupID"></span> //i want to display the value "2" here
In your code field variable is not defined instead of that use this to refer the clicked element and get id property. Althogh for updating the content use html() or text() method since append() method just insert the new content at end(existing content would be there).
$(".view-details").on("click", function() {
// get id property
var group = this.id;
// update the html contecnt of span element
// or use `text()` method
$("#groupID").html(group);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="2" class="view-details">View Details 1</span><br>
<span id="3" class="view-details">View Details 2</span><br>
<span id="groupID"></span>
If we look only the snippet you provided, the issue is that you are not defining the field variable. However it will keep appending the 2 in your span as many times as you click if that is not desired , the other answer is already taking care of that.
$( ".view-details" ).on( "click", function() {
field = $(this);
var group = field.attr("id");
console.log(group); //Ex: value is coming as "2"
$("#groupID").append( group );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="2" class="view-details">View Details</span>
<span id="groupID"></span>

Categories