how to search appended html in jquery? - javascript

I want create somthing like wordpress comment reply form. in WP when you click on reply button a from apear under the reply button.
I do appending form after clicking reply button, but my problem is if i click again another form append to container.
for handeling this I want search container before append form, if form exist it sholudn't append another one but it seems search wouldn't work for appended html.
what's your suggestion for this problem?
$(document).on('click','.reply-btn',function(){
...
var form="<div class='col-xs-12' >"+
"<form role='form' method='post'>"+
....
"</form>"+
"</div>";
var container=$(this).closest('div');
if(container.html().search(form)<0){
container.append(form)
}else{
alert('it'e also appended')
}
})// .reply-btn

Your html string and the html returned by the dom structure may not be the same, what you should do is to check whether container has a form like
$(document).on('click', '.reply-btn', function () {
var container = $(this).closest('div');
if (container.find('form').length == 0) {
var form = "<div class='col-xs-12' >" +
"<form role='form' method='post'>" + ....
"</form>" +
"</div>";
container.append(form)
} else {
alert('it\' e also appended ')
}
})

use find and length to check the element present or not
if(container.find("form").length){
// already there
}

$(document).on('click','.reply-btn',function(){
var form="<div class='col-xs-12' >"+
"<form role='form' method='post'>"+
....
"</form>"+
"</div>";
var container=$(this).closest('div');
if(container.find('form').length <1)
container.append(form)
}else{
alert('it is also appended')
}
});

Related

Javascript: onclick for dynamically created button

I dynamically create a button in the way I found in the Internet:
...
outPut +=
"<div class=\"col-lg-4 col-md-6 mb-4\">" +
"<div class=\"card h-100\">"+
"<img class=\"card-img-top\" src=\"http://placehold.it/700x400\" style=\"height: 50%; width:50% \" alt=\"\">"+
"<div class=\"card-body\">"+
"<h4 class=\"card-title\">"+
""+ nome +""+
"</h4>"+
"<h5>"+ preco +"</h5>"+
"<p class=\"card-text\">"+ descricao +"</p>"+
"</div>"+
"<div class=\"card-footer\" >"+
"<button type=\"button\" class=\"btn btn-success-cart\" data-id=\"" + id + "\" data-nome=\"" + nome + "\" data-descricao=\"" + descricao + "\" data-preco=\"" + preco + "\">+ Carrinho</button>"+
"</div>"+
"</div>"+
"</div>";
...
$("#divCards").html(outPut);
And Imply the method of click on each one in this way:
$(".btn-success-cart").click(function(event){
event.preventDefault();
var _id = Number( $(this).attr("data-id") );
var _nome = $(this).attr("data-nome");
var _descricao = $(this).attr("data-descricao");
var _preco = Number( $(this).attr("data-preco") );
console.log("Item add");
addItem(_id, _nome, _descricao, _preco, 1);
updateCart();
});
But nothing happens when I click the generated buttons.
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
You need to bind on a static element that exists when the code .on() is executing. Use event delegation:
$('#divCards').on('click', '.btn-success-cart', function(event){
event.preventDefault();
var _id = Number( $(this).attr("data-id") );
var _nome = $(this).attr("data-nome");
var _descricao = $(this).attr("data-descricao");
var _preco = Number( $(this).attr("data-preco") );
console.log("Item add");
addItem(_id, _nome, _descricao, _preco, 1);
updateCart();
});
I know it's a bit late to answer here but similar situation happened to me and above accepted answer worked sort of. But it fires the event multiple times because my script included to call that function which creates click event several times for different occasions. So each call would create the click event repeatedly. Then when a user click the button, the function will be called multiple times. Therefore I had to off click then on click. Just adding this answer so that anyone else has same issue with me may get help.
('#divCards').off('click', '.btn-success-cart').on('click', '.btn-success-cart', (event) => {
......
}
});

Apply a javaScript function to 1 div when there are more divs with the same class

I'm trying to make a simple timeline that informs users. When they click on a date, there should be some sort of "accordion" system that drops down and give more information. When they click on it again, the "accordion" closes again.
I've included some pictures to make it somewhat more clear:
And:
The first image shows what the user is seeing when he gets onto the page, the second picture shows what he sees when he clicks on 1 of the elements.
The problem ive at the moment is when he clicks on 1 day, all the information is shown. I dont know how i can get some sort of index so only that particular day shows its hidden information.
At the moment I've the following code:
JavaScript
$counter=1;
$(document).ready(function(){
$(".tijdlineElement").click(function(){
$(".tijdlineElementHidden").slideToggle("slow");
if($counter == 1){
getElementsByClassName("tijdlineElementHidden").style.display = "block";
$counter = 2
}
else{
getElementByClass("tijdlineElementHidden").style.display = "none";
$counter =1
}
});
});
and the PHP to make 1 Day:
echo "<div class='tijdlineElement'>";
echo "<div class='tijdlineP2Element' >" . $topic['Uur']."<br /><br />" . $topic['Beschrijving'] . "</div>";
echo "<div class='tijdlinePElement'>". $newDate . '<br />'. $newDate1 . ' '. $newDate1a . '<br />' . $newDate2 ."</div>";
echo "<img src='images/meerFase1.png'/>";
echo "</div>";
echo "<div class='tijdlineElementHidden' style='display:none;'>";
echo "<div class='tijdlineP2Element'>" . $topic['LangeBeschrijving'] . "</div>";
echo "<div class='tijdlinePElement'></div>";
echo "</div><br />";
The issue is, when a user clicks on 1 date, all the information from the other days get revealed aswell.
So my question is: How can i get access to that particular div, so only the information from the selected(the div that was clicked on) div is shown?
With your current code by using $(".tijdlineElement").click(function(){ } You are triggering the click event on all elements with that class. What you could do is use something like .each() and $(this) to scope it to your currently clicked element.
$(".tijdlineElement").each(function(){
$(this).on({
click:function()
{
$(this).slideToggle("slow");
// other click function stuff
}
});
});
Quick Demo:
http://jsfiddle.net/9v2D5/
Updated Demo:
http://jsfiddle.net/9v2D5/25/
Loop through all elements that share the same class name, then addEventListener or attachEvent if IE8. (Native JS solution)
var elements = document.querySelectorAll(".tijdlineElement");
var i = 0, length = elements.length;
for (i; i < length; i++) {
if (document.addEventListener) {
elements[i].addEventListener("click", function() {
var element = this;
});
} else { // IE8 support
elements[i].attachEvent("onclick", function() {
var element = elements[i];
});
};
};
Instead of referencing the class, use $(this) to reference it:
$(".tijdlineElement").click(function(){
$(this).find(".tijdlineElementHidden").slideToggle("slow");
.....the rest of the code...
}
Try this:
var parent = $( this );
$( ".tijdlineElementHidden", parent ).slideToggle("slow");
It should toggle only the "tijdlineElementHidden" divs that are children to the clicked element.

how to create button dynamically and add the onclick event for html page

i have created one button in my javascript code, after clicking on this button it should go to the product.html
var outputb2 = "<p align=right>"+ "<input type=button value=productandservices onClick=window.location=product.html>" + "</input>" +"</p>";
$('#product').append(outputb2);
where product is the div id in the product.html.but when i click on this button product and services..its not going to this product.html.how can i do..?
I don't know why you are using javascript for this, unless you are sending some data with the click event. there is a simple html code to do what you want.
product and services
If you must use java-script try this
onclick="javascript:location.href='product.html#product'"
Check this out
<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices >" + "</input>" +"</p>";//added id
$('#product').append(outputb2);
$(document).ready(function()
{
$(document).on("click","#productandservices",function()
{
alert('clcik');
window.location='product.html';
});
});
</script>
or
Enclose filename in quotes '
<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices onClick=window.location='product.html' >" + "</input>" +"</p>";
$('#product').append(outputb2);
</script>
Probably you need some escape characters in your code, it will work
var outputb2 = "<p 'align=right'>"+ "<input type='button' value='productandservices' onClick='window.location=\"product.html?someParam=hi\"'>" + "</input>" +"</p>";
$('#product').append(outputb2);
var outputb2 = "<p align=right>";
outputb2 += "<input type='button' value='productandservices' onClick='window.location=product.html'>"
outputb2 += "</p>";
$('#product').append(outputb2);
var outputb2 = "<p align='right'><input type='button' value='productandservices' onClick='window.location=product.html'></input></p>";
$('#product').append(outputb2);
right syntax to use:
<input TYPE="button" value=productandservices onclick="window.location.href='http://www.wherever.com'">
Another option is to create a link in the button:
<button type="button">Link link</button>
Then use CSS to style the link and button, so that the link takes up the entire space within the button (so there's no miss-clicking by the user):
button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}
but the point of a link is to go to another page. So trying to make a button act like a link is the wrong solution. My suggestion is that you should use a link and style it to look like a button.
<a href="/page2>Continue</a>
Try this :
var outputb2 = "<p align='right'>"+
"<input type='button' value='productandservices 'onClick='window.location=\"product.html\"' />" +
"</p>";
$('#product').append(outputb2);
Add ' like this : onClick='window.location=\"product.html\"'
Live demo

javascript : built an html form from json, but can't update the form

I have a javascript code that takes objects from json.
from this, i built an html string:
var htmlstr = "<table border=0>";
for (var i=0;i<jsonData.people.length;i++) {
htmlstr=htmlstr+"<tr><td>" + jsonData.people[i].name + "</td>";
htmlstr=htmlstr+"<td>"+ jsonData.people[i].cash + "</td>";
htmlstr=htmlstr+"<td><button onclick='changeCash(i)'>Update</button></td></tr>";
}
htmlstr=htmlstr+"</table>";
layer.addFeatures(features);
layer.events.on({ "featureselected": function(e) { updateMak('mak', htmlstr) } });
function changeCash(k) {
jsonData.people[k].cash=jsonData.people[k].cash+100;
}
The HTML page is as follows:
<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
alert("Mobile device detected."); }
function updateMak(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
} </script>
<div id="mak"> List of People </div>
Lets say this displays 10 people with their money.
If I click on one of their Update buttons, I think the json data is updated as intended. But I don't know how to verify it. The values in the form doesn't update the new value from the changeCash function.
How do I update the htmlstr and also update what's already displayed on screen?
Please advise.
When you generate htmlstr for the people cash
htmlstr=htmlstr+"<td>"+ jsonData.people[i].cash + "</td>";
You should also generate id for this td so that you can update the content from the function changeCash(k).
Something like
htmlstr=htmlstr+"<td id='peoplecash"+i+"'>" + jsonData.people[i].cash + "</td>";
And then in your changeCash function
function changeCash(k) {
jsonData.people[k].cash=jsonData.people[k].cash+100;
var peoplecash= document.getElementById("peoplecash"+k);
peoplecash.innerHTML = jsonData.people[k].cash;}

Copy div to a popup

How can I copy an entire div to a popup window?
What I`m trying to do:
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript' />\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
text += $("#divDadosBasicos").html($(querySelector).html());
text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n/body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
I dont know if this is the better way to do it. If you think/know a easier way to do it, please share
Thanks in advance!
Fix some of these errors and it will work fine
Script tag is not closed properly
body tag not closed properly
querySelector is not defined. (I am commenting that portion)
function ImprimirTela() {
var text = "<html>\n<head>\n<title>Impressão Guia</title>\n";
text += "<script src='~/js/jquery-1.4.2.js' type='text/javascript' language='javascript'></script>\n";
text += "</head>\n<body>\n";
text += "<input type='button' value='Imprimir esta página' onclick='window.print();' style='float: right' />\n";
text += "<div id='conteudo'>\n";
//define querySelector
//text += $("#divDadosBasicos").html($(querySelector).html());
//text += $("#divHipotesesDiagnosticas").html($(querySelector).html());
text += "</div>\n</body>\n</html>";
var newWindow = window.open('', 'Impressao', 'width=900,height=700');
newWindow.document.write(text);
}
You could use a Jquery Modal Popup
http://jqueryui.com/demos/dialog/
Check it out, it has the functionality that you need.
It has several events you can tweak to modify the data.
Just tested this, and the code seems to be working just fine as long as querySelector is defined, and it's in a document.ready function and you are testing this on an actual webserver (like WAMP/LAMP etc.). It will not work in places like jsFiddle etc.

Categories