I have several elements that were dynamically added to my web page and now I'm trying to append them to textarea, but I keep getting only the last element to show up.
I figured I need to use val() instead of append(), but with val() I only get last option that was stated.
Can someone help me out? I'm trying to include all rows in the textarea.
I've recreated my problem in a snippet bellow.
function getDetails() {
// Clear content
$("#save-content").val('');
// First headline
$("#save-content").val("First group: \n");
// Content from first group
$(".first-item .row").each(function(){
var firstGroupName = $(this).find(".name").text();
var firstGroupSurname = $(this).find(".surname").text();
$("#save-content").val(firstGroupName + " " + firstGroupSurname + "\n");
});
// Second headline
$("#save-content").val("Second group: \n");
// Content from second group
$(".second-item .row").each(function(){
var secondGroupName = $(this).find(".name").text();
var secondGroupSurname = $(this).find(".surname").text();
$("#save-content").val(secondGroupName + " " + secondGroupSurname + "\n");
});
// Third headline
$("#save-content").val("Third group: \n");
// Content from third group
$(".third-item .row").each(function(){
var thirdGroupName = $(this).find(".name").text();
var thirdGroupSurname = $(this).find(".surname").text();
$("#save-content").val(thirdGroupName + " " + thirdGroupSurname + "\n");
});
}
$('button').on('click', function() {
getDetails();
});
.row>div {
display: inline-block;
}
button {
display: block;
margin: 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="imported-content">
<div class="first-item">
<div class="row">
<div class="name">Penelope</div>
<div class="surname">Smith</div>
</div>
<div class="row">
<div class="name">Jane</div>
<div class="surname">Dalton</div>
</div>
</div>
<div class="second-item">
<div class="row">
<div class="name">Kate</div>
<div class="surname">Davidson</div>
</div>
</div>
<div class="third-item">
<div class="row">
<div class="name">David</div>
<div class="surname">Peters</div>
</div>
<div class="row">
<div class="name">Brad</div>
<div class="surname">Lucas</div>
</div>
</div>
</div>
<button>Import</button>
<textarea id="save-content" rows="5"></textarea>
You can add the val when settings the val when you want to append.
For example:
$('#save-content').val($('#save-content').val() + yourContentHere);
Related
I want to calculate numbers in some DIV boxes and append the total in another DIV.
How can I make this work on-click of the box class as another function adds the values to the box dynamically?
I have tried various messy ways like wrapping the whole code in window.onclick.
https://jsfiddle.net/esw6dbLn/1/
var total =0;
$('.box > .box_content > .box_price').each(function(){
total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total : "+total+"</div>");
console.log(total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<div class="container">
<div class="box">
<div class="box_content">
<div class="box_price">100</div>
</div>
</div>
<div class="box">
<div class="box_content">
<div class="box_price">200</div>
</div>
</div>
</div>
You can use click event on box_price div then get value of div which is been clicked and also the sum div value add them and display them inside your sum div.
Demo Code :
var total = 0;
$('.box > .box_content > .box_price').each(function() {
total += parseInt($(this).text());
});
$('.container').append("<div class='sum'>Total :<span> " + total + "</span></div>");
console.log(total);
$(".box_price").click(function() {
//get price which is clicked then add with sum
var price = parseInt($(this).text()) + parseInt($(".sum span").text().trim())
$(".sum span").text(price) //display in span
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box">
<div class="box_content">
<div class="box_price">100</div>
</div>
</div>
<div class="box">
<div class="box_content">
<div class="box_price">200</div>
</div>
</div>
</div>
You can put an empty div in your HTML and update it via an event listener that is added to each .box element, like:
// Finds all the boxes and calls `sumBoxes` whenever one is clicked
const boxes = document.getElementsByClassName("box");
for (let box of boxes){ box.addEventListener("click", sumBoxes); }
// Defines listener
function sumBoxes(event) {
var total = 0;
$('.box > .box_content > .box_price').each(function() {
total += parseInt($(this).text());
});
$('.sum').html("Total : " + total); // Replaces contents of `.sum`
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<div class="container">
<div class="box">
<div class="box_content">
<div class="box_price">100</div>
</div>
</div>
<div class="box">
<div class="box_content">
<div class="box_price">200</div>
</div>
</div>
<!-- Empty div to recieve sums -->
<div class="sum"></div>
</div>
You can listen for the .container click so anything inside the container will trigger the event and then do the calculation.
DEMO: https://jsbin.com/bokoman/edit?html,js,console,output
// Get the container
const container = document.querySelector('.container');
// Create an empty <span> and added to the end of the container
const totalEl = document.createElement('span');
container.appendChild(totalEl);
// listen for all the click but only do somethig if one of it childs was clicked
container.addEventListener('click', function(e) {
if (!e.target.classList.contains('container')) {
const prices = document.querySelectorAll('.box_price');
let total = 0;
prices.forEach(item => {
total += parseInt(item.innerText, 10)
})
// Add the total to the total element we created
totalEl.innerHTML = total
}
})
var total =0;
calculateResult = () =>{
total = 0;
$('.box > .box_content > .box_price').each(function(){
console.log()
total += parseInt($(this).text());
});
$('#sum').html("total:" + total);
}
$( "#target" ).click(function() {
$('.container').append("<div class='box'><div class='box_content'><div class='box_price'>100</div></div></div>");
calculateResult();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
</div>
<div id="result">
<div class='sum' id="sum">0</div>
</div>
<div id="target">
Add
</div>
var r1=Math.floor(Math.random()*255)
var g1=Math.floor(Math.random()*255)
var b1=Math.floor(Math.random()*255)
$(".color1").click(function (){
$(this).css("background", "rgb(" + r1 + "," + g1 + "," + b1 + ")")
})
$(document).ready(function () {
$(document).on('click', function (event) {
$target = $(event.target);
$target.addClass('clicked');
});
})
var numItems
var getfirstclass
var getsecondclass
$('div').click(function saveclassnames(){
var getfirstclass=$(this).attr('class')
console.log(getfirstclass)
var getsecondclass=$(this).attr('class')
console.log(getsecondclass)
getfirstclass===null
getsecondclass===null
})
$('div').click(function remove(){
var numItems = $('.clicked').length
if(numItems===2 && getfirstclass === getsecondclass){
$('.clicked').css('opacity', '0')
}
else{
$('.clicked').css('background', 'black')
}
})
<body>
<div class="container">
<div class="row">
<div class="color1"></div>
<div class="color2"></div>
<div class="color3"></div>
<div class="color4"></div>
</div>
<div class="row">
<div class="color5"></div>
<div class="color3"></div>
<div class="color1"></div>
<div class="color6"></div>
</div>
<div class="row">
<div class="color7"></div>
<div class="color6"></div>
<div class="color8"></div>
<div class="color5"></div>
</div>
<div class="row">
<div class="color7"></div>
<div class="color8"></div>
<div class="color4"></div>
<div class="color2"></div>
</div>
</div>
</body>
I am trying to make a game called "Memory" (if 2 flipped cards are same, the cards will disappear, but if the cards are not the same, they will flip back). But there is a difference between the original one). I am using random colors instead of card pictures, but I cannot make <div> elements with the same background-color disappear, or flip back if they are not the same. Can someone explain to me why this code does not work?
Thanks.
opacity: 0; hiding generates a lot of space although the element is not visible.
background: black; – the element needs to blend in with the background, otherwise it will not work (technically it won't work)
You can either do this:
$('yourItem').css({
display: 'none'
});
Or, the "simplest way to hide an element":
$('yourItem').hide();
For more information see https://api.jquery.com/hide/
You could use
display: none
If that messes with other stuff, use
visiblity: hidden;
Confused why this happened,
when I am in second page (ex: product_detail.html?id=1), then I want to click the same page but different id (ex :product_detail.html?id=5) it is not working, nothing displayed.
Here is my index.html
<script type="text/javascript" src="cordova.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.mobile.min.js"></script>
<div class="item">
<img src="http://web/banner2.jpg">
</div>
<div class="item">
<img src="http://web/banner3.jpg">
</div>
<script>
$( document ).on( "pageinit", "#detailsPage", function( event ) {
var parameters = $(this).data("url").split("?")[1];
parameter = parameters.replace("id=","");
var devid=localStorage.getItem("macid");
$.getJSON('http://url_web_services/related_product.php?id='+parameter, product_detail);
});
function product_detail(data) {
var employee = data.item;
var urls="";
urls="http://url_web_services/"+employee.product_image;
var myid3="";
myid3 = localStorage.getItem("macid");
$('#product_detail').append('<a href="product_detail.html?id='+employee.product_id+'"><div class="item">');
$('#product_detail').append('<div class="xxw"><img src="http://webservice' + employee.promo_image +'"></div>');
$('#product_detail').append('<div style="background-color:#2E64FE;margin-top:15px;"><font color="#FFFFFF" face="arial" size="3">' + employee.product_name + '</font></div><br>');
$('#product_detail').append('</div></a>');
//SIMILAR PRODUCT
var idp=employee.promo_id;
$.getJSON('http://webservice/product_related.php?id='+idp, function(data) {
employees2 = data.items;
$.each(employees2, function(index, employee2) {
$('#product_similar').append('<a href="product_detail.html?id='+employee2.product_id+'"><div class="some">'+
'<div><img src="http://webservice/' + employee2.product_image +'" class="bgr"></div>'+
'<div class="four"><p style="margin-left:5px;margin-top:2px;"><font face="arial" size="2" color="black"><b>'+employee2.product_name+' ....</b></font></p></div>'+
'</div></a>');
});
});
}
</script>
here is my second page product_detail.html
<div data-role="page" id="detailsPage">
<div data-role="header" data-tap-toggle="false" data-theme='b'>
<h1 class="header-title">Detail</h1>
</div>
<div data-role="content" id="product_detail">
</div>
<br>
<div style="background-color:#3104B4;margin-top:5px;"><font color="#FFFFFF" face="arial" size="3"><center>PRODUCT SIMILAR</center></font></div>
<div id="product_similar" style="background-color:#E6E6E6;margin-top:2px;">
</div>
<div data-role="footer" data-theme="none" data-inner="true" data-border="false">
</div>
</div>
when I click one of item in product_similiar (it means reload the same page, but different ID, it displays nothing)
You can try dynamically creating page with the new values, here is an example:
<img src="http://web/banner2.jpg">
<script>
function create_page(page_id) {
var jsonUrl = 'http://url_web_services/related_product.php?id=' + page_id
var content = $('#detailsPage').html();
var newPage = '<div data-role="page" id="product_detail_id=' + page_id + '">' + content + '</div>'
$('body').append(newPage);
//initialize the new page
$.mobile.initializePage();
//navigate to the new page
$.mobile.changePage("#product_detail_id=" + page_id, "pop", false, true);
//now you can get #product_detail
$.getJSON(jsonUrl , product_detail);
}
</script>
With some adjustments it should work
In my webpage, I have an input method and a button which opens a popup with smiles. When a user taps a smile once, the input value is changed to 'current value' + ':smile1:', for example. However, I have about 28 smile icons and this way to send emojis is a little bit difficult. How can I make this process easier? Because after this, I'll need to parse all 28 smiles and check if the input value equals one of them.
My popup:
<div class="smile-popuptext" id="smPopup">
<div class="smile1"></div>
<div class="smile2"></div>
<div class="smile3"></div>
//.....and other 25 divs
</div>
My function that sends the smile:
$('.smile1').on('click', function () {
var message = $('#message').val() + ' :smile1:';
$('#message').val(message);
});
I'd recommend giving all the buttons a single class and giving them unique id's.
So something like this:
<div class="smile-popuptext" id="smPopup">
<div class="smile" id="smile1"></div>
<div class="smile" id="smile2"></div>
<div class="smile" id="smile3"></div>
//.....and other 25 divs
</div>
Then:
$('.smile').on('click', function () {
var message = $('#message').val() + ' :' + this.id + ':';
$('#message').val(message);
});
JSFiddle
You could bind an EventListener on the container and defining the value as a data attribute:
var container = document.querySelector('.smile-popuptext');
container.addEventListener('click', function(event) {
var target = event.target;
var emoji = target.getAttribute('data-emoji');
if(emoji) {
console.log('clicked', [':', emoji, ':'].join(''));
}
});
<div class="smile-popuptext" id="smPopup">
<div class="sm1" data-emoji="smile1">1</div>
<div class="sm2" data-emoji="smile2">2</div>
<div class="sm3" data-emoji="smile3">3</div>
</div>
With no changes in your markup:
$('#smPopup div[class^="smile"]').on('click', function () {
var message = $('#message').val() + ' :' + this.className + ':';
$('#message').val(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="smile-popuptext" id="smPopup">
<div class="smile1">smile 1</div>
<div class="smile2">smile 2</div>
<div class="smile3">smile 3</div>
</div>
<textarea id="message"></textarea>
thanks in advance.
The question is:
I have 2 buttons that shows the content of the div when the user click on it.
The content of the div are in a function that shows the content when the users click on the button (onclick).
But when the page loads just appear the two buttons without any content, is there any way to 'put' one of these buttons as active by default?
I tried with this:
Html:
<div class="diferencias col-md-12 col-lg-12">
<div class="diferencias col-md-6 col-lg-6"><input type="button" value="Web" onClick="fashioncatweb();">
</div>
<div class="diferencias col-md-6 col-lg-6"> <input type="button" value="Logo" onClick="fashioncatlogo();">
</div>
</div>
<div class="row">
<div id="container">
<div id="content"></div>
</div>
</div>
JS:
function fashioncatweb()
{
var text = "<p>text";
var img = "images/.....";
var content = "<div class=\"col-md-7\"><div class=img><img class=img-responsive src=\"" + img + "\" alt=\"\" /></div></div>"
+ "<div class=\"col-md-5\"><div class=pre-scrollable id=\"fashion\">" + text + "</div></div>";
appendToContainer(content);
}
function fashioncatlogo()
{
var text = "<p>text";
var img = "images/....png";
var content = "<div class=\"col-md-7\"><div class=img><img class=img-responsive src=\"" + img + "\" alt=\"logo\" /></div></div>"
+ "<div class=\"col-md-5\"><div class=pre-scrollable id=\"logo\">" + text + "</div></div>";
appendToContainer(content);
}
$(document).ready(function () {
piramidalweb();
});
But it just works for one section and I have like 15 different sections.
Thanks again!!
You should have a function that is called on the click of the buttons:
Using pure Javascript:
<input type="button" value="Button1" id="btn1" onclick="showContent(this.id)" />
function showContent(id) {
if(id === "btn1") {
// show the content
}
}
Then call immediately at the base of the page within script tags:
showContent("btn1");
That will load the content immediately.
To improve this you would execute this function onload, or in a ready function within jQuery, but hopefully you'll be able to take it from there.