Multiple Counting Buttons JS - javascript

I'm trying to create something a page that creates post so every time someone clicks a button it creates a text with another button to like. I want each separate like button to be incremented upon clicking but it doesn't work. Either only one count is updated or none. I'm using HTML5 and CSS with javascript.
$(function(){
$('.input_button').on('click', function(){
text = $('.input_text').val();
var btn = document.createElement("BUTTON");
var t = document.createTextNode("Like");
btn.appendChild(t);
document.body.appendChild(btn);
var clicks = 0;
btn.onlick = function() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
if (text != undefined) {
post = '<div class="post test--post">' + '<img src="photo.JPG" width="20" height="25" alt=""/>' + '<p><span>jaleelg: </span></p>' + text +
'<p>Clicks: <a id="clicks">0</a></p>' + "<br>" + Date() + " " + '</div>';
new_post = $('.post_feed').append($(post))
new_post = $('.post_feed').append($(btn))
}
});
});

There were a bunch of things wrong with the code, but I fixed them: https://jsfiddle.net/yak613/opoy49ox/
$(function(){
$('.input_button').on('click', function(){
text = $('.input_text').val();
var btn = $("<button></button>");
btn.text(text);
$("body").append(btn);
btn.after("<span class='clicks'></span>")
var clicks = 0;
btn.click(function() {
clicks++;
$(this).next(".clicks").html(clicks);
});
if (text != undefined) {
post = '<div class="post test--post">' + '<img src="photo.JPG" width="20" height="25" alt=""/>' + '<p><span>jaleelg: </span></p>' + text +
'<p>Clicks: <a id="clicks">0</a></p>' + "<br>" + Date() + " " + '</div>';
new_post = $('.post_feed').append($(post))
new_post = $('.post_feed').append($(btn))
}
});
});

this is how to make a button:
**function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks
<body>
<button type="button" onClick="onClick()">Click Me!</button>
<p>clicks: $<a id="clicks">0</a></p>
</body>**

Related

onclick not working for two or more links for same function in javascript

I have displayed records from MySQL database. After displaying records added javascript onclick function. It works only for the first record and not works for other records.
In the above image, I clicked the first link which works fine. But if I click second click nothing happens.
<script>
function Confirm(title, msg, $true, $false, $link) {
/*change*/
var $content =
"<div class='dialog-ovelay'>" +
"<div class='dialog'><header>" +
" <h3> " +
title +
" </h3> " +
"<i class='fa fa-close'></i>" +
"</header>" +
"<div class='dialog-msg'>" +
" <p> " +
msg +
" </p> " +
"</div>" +
"<footer>" +
"<div class='controls' style='text-align:right'>" +
" <button class='button button-danger doAction'>" +
$true +
"</button> " +
" <button class='button button-default cancelAction'>" +
$false +
"</button> " +
"</div>" +
"</footer>" +
"</div>" +
"</div>";
$("body").prepend($content);
$(".doAction").click(function() {
$(this)
.parents(".dialog-ovelay")
.fadeOut(500, function() {
var subtotal = document.getElementById("subtotal").innerHTML;
var price = "<?php echo $price ;?>";
var subtotal = +subtotal + +price;
var totalitems = document.getElementById("totalitems").innerHTML;
var totalitems = +totalitems + +1;
document.getElementById("totalitems").innerHTML = totalitems;
document.getElementById("subtotal").innerHTML = subtotal.toFixed(2);
var total = +subtotal + +8 + +4;
document.getElementById("total").innerHTML = total.toFixed(2);
$(this).remove();
});
});
$(".cancelAction, .fa-close").click(function() {
$(this)
.parents(".dialog-ovelay")
.fadeOut(500, function() {
$(this).remove();
});
});
}
$("#linkdup").click(function() {
Confirm(
"Are you sure you want to Duplicate Frame",
"One more frame will be added to Cart",
"Yes",
"No"
); /*change*/
});
</script>
You are working with IDs here. An ID is unique, if you query it, you will get one result (the first).
Example:
// This selects one
const result = document.getElementById('myId').innerHTML;
console.log(result);
// This selects all
const elements = document.querySelectorAll('[id=myId]');
elements.forEach(function(element) {
console.log(element.innerHTML);
// add click event to element here
});
<div id="myId">Test 1</div>
<div id="myId">Test 2</div>
Use classes for this. Using an ID multiple times is invalid, even though you can make it work as shown in example.

How to add next previous buttons to popup?

I need to load XML data to next and previous buttons on the popup box. When button click, my code is fail to load the XML data. How can I implement the code.
Here is the script
function xmlParser(xml){
xml = $(xml).children();
$(xml).children().each(function () {
let tag = $(this).prop("tagName");
let image = '<img style="background-image:url(' + $(this).find("image").text() + ')"' + '" />';
let image2 = '<div><img src="' + $(this).find("image").text() + '" width="100%" alt="' + '" />' + '</div>';
let head = '<div>' + $(this).find("head").text() + '</div>';
let html = `<div class="col-sm-4 random" id="random">
<a href="#${tag}" id="openModalBtn">
<div>${image}</div>
<h5>${head}</h5>
</a>
</div>`;
let popup = `<div id="${tag}" class="overlay">
<div class="popup">
‹
›
<h6>${head}</h6>
<a class="close" href="#">×</a>
<div>${image2}</div>
</div>
</div>`;
$("#xmldata").append(html);
$("#popup").append(popup);
});
}
Plunker
Firstly div id is being duplicated if you use directly tag name. So use index in for loop and do some simple calculation to get prev & next items, something like:
$(xml).children().each(function (idx) {
let tag = $(this).prop("tagName");
let nextIdx = idx + 1;
let prevIdx = idx - 1;
//to make cyclic rotation
nextIdx = nextIdx == total ? 0 : nextIdx;
prevIdx = prevIdx == -1 ? (total -1) : prevIdx;
//..........check plunker code
http://next.plnkr.co/edit/Sj188FthvFu6H5uv?open=lib%2Fscript.js

select element with class and id with jquery

I'm trying to select two different elements with class and id, the first works but the second doesn't (it works without the id), I can't figure out why.
help me, please.
code:
$(document).ready(function() {
var num = 0;
$("#add").click(function() {
$("main").append("<div class=\"card\" style=\"width: 20rem;\">\
<div class=\"card-block\">\
<h4 class=\"card-title\" id=\"" + num.toString() + "\"></h4>\
<p class=\"card-text\" id=\"" + num.toString() + "\"></p>\
</div>\
</div>");
var title = $("#noteTitle").val();
var body = $("#noteBody").val();
var photo = $("#notePhoto").val();
if (photo) {
$(".card").prepend("<img class=\"card-img-top\" src=" + photo + " alt=\"Card Image\">");
}
$(".card-title#"+ num.toString()).html(title);
$(".card-text#"+ num.toString()).html(body); //<-- here is where I get the problem
num ++;
});
})
Here you go with the solution . https://jsfiddle.net/0knefedh/
$(document).ready(function() {
var num = 0;
$("#add").click(function() {
$("body").append("<div class=\"card\" style=\"width: 20rem;\">\
<div class=\"card-block\">\
<h4 class=\"card-title\" id=\"title" + num.toString() + "\"></h4>\
<p class=\"card-text\" id=\"text" + num.toString() + "\"></p>\
</div>\
</div>");
var title = "dasdasd";
var body = "asdasdas";
var photo = $("#notePhoto").val();
if (photo) {
$(".card").prepend("<img class=\"card-img-top\" src=" + photo + " alt=\"Card Image\">");
}
$(".card-title#title"+ num.toString()).html(title);
console.log(num);
$(".card-text#text"+ num.toString()).html(body); //<-- here is where I get the problem
num ++;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" id="add" value="Add" >Add</button>
Problem is with ID that you are generating for .card-title and .card-body. Both are having same ID, where as ID should be unique.
So, it work for the first time then it didn't.

Setting text input as a variable in Javascript

I'm trying to use my text input as a string variable and use that variable as a part of a URL to pull up JSON data but I can't seem to get it to work properly.
I don't know if I'm setting the variables incorrectly but any help would be appreciated. Thank you!
$(document).ready(function() {
var p = document.querySelector('p');
var input = document.getElementById('search').value;
$("#go").click(function() {
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
} else {
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + input + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
} else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
At the time you assign the variable value, it is empty because it is run when the site is loaded and there is probably no text in the search box yet. You want the content at the time #go is clicked, so just assign it inside the click event handler:
$(document).ready(function() {
var p = document.querySelector('p');
// the text field value is empty at this point
$("#go").click(function() {
// this is run when user clicks #go
var input = document.getElementById('search').value;
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
}
else {
// encode user input
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + encodeURIComponent(input) + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
}
else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
Additionally, you should always encode user input if you include it in a URI. Otherwise you'll experience unexpected behaviour when using any non alphanumerical character (including whitespace) in the search box. For a more detailed explanation of how and why, see the documentation.

JQuery help, How to Hide all button in JQuery

I'm trying to make a request/reply section in my project.
I want to achieve these functionality in that code (that I'm not able to implement; so guys please help me out):
1> When user click on reply button; other reply area(text-area +button) should be hide (means at a time only one reply area should be visible to the user).
2> when user click on reply button text-area will focus and page will slide down (suppose user reply 10 comment focus will automatically set to the 10 number text area and page will slide down to that position accordingly).
Here is my so far code guys:
//method call on the click of reply link.
function linkReply_Clicked(issueId) {
Id = issueId;
textId = "text_" + issueId + count;
btnReply = "btnReply_" + issueId + count;
btnCancel = "btnCancel_" + issueId + count;
var textareasArray = document.getElementsByTagName("textarea");
var btnArray = document.getElementsByTagName("input");
for (i = 0; i < textareasArray.length; i++) {
textareasArray[i].style.display = "none";
btnArray[i].style.display = "none";
}
var str = "<table cellpadding='3' cellspacing='0' width='58%'>";
str += "<tr><td valign='top' align='left'>";
str += "<textarea id=" + textId + " rows='5' cols='60'></textarea>";
str += "</td></tr>";
str += "<tr><td valign='top' align='right'>";
str += "<input id=" + btnReply + " type='button' onclick='btnReply_Clicked(Id ,textId)' value='Reply' /> ";
str += "<input id=" + btnCancel + " type='button' onclick='btnCancel_Clicked(Id ,textId)' value='Cancel' /> ";
str += "</td></tr>";
str += "</table>";
document.getElementById("divOuter_" + issueId).innerHTML = str;
$("#" + textId + "").focus();
}
// submit user reply and try to hide that reply area.
function btnReply_Clicked(issueId, textID) {
var comment = document.getElementById(textID).value;
if (comment != '') {
$.getJSON("/Issue/SaveComment", { IssueId: issueId, Comment: comment }, null);
$("#text_" + issueId + count).hide();
$("#btnReply_" + issueId + count).hide();
$("#btnCancel_" + issueId + count).hide();
document.getElementById(textID).value = '';
count = count + 1;
}
}
// cancel user reply and try to hide that reply area.
function btnCancel_Clicked(issueId, textId) {
$("#text_" + issueId + count).hide();
$("#btnReply_" + issueId + count).hide();
$("#btnCancel_" + issueId + count).hide();
document.getElementById(textId).value = '';
count = count + 1;
}
I changed a bit of this because you can do it much easier since you're already using jQuery :)
Go here for the demo version
You can replace all of your posted code with this:
function linkReply_Clicked(issueId) {
$(".replyTable").hide();
var tbl = $("<table class='replyTable' cellpadding='3' cellspacing='0' width='58%'></table>");
tbl.append("<tr><td valign='top' align='left'><textarea rows='5' cols='60'></textarea></td></tr>");
tbl.append("<tr><td valign='top' align='right'><input type='button' class='reply' value='Reply' /> <input type='button' class='cancel' value='Cancel' /> </td></tr>");
tbl.find(".reply").click(function() {
var comment = $(this).closest("table").find("textarea").val();
if (comment != '') {
$.getJSON("/Issue/SaveComment", { IssueId: issueId, Comment: comment }, null);
$(this).closest("div").empty();
}
}).siblings(".cancel").click(function() {
$(this).closest("div").empty();
});
var div = $("#divOuter_" + issueId).empty().append(tbl);
$('html, body').animate({ scrollTop: $(div).offset().top }, 500,
function() { div.find("textarea").focus(); });
}
This does the following things differently with the slide effect & the hiding and scrolling from the question:
Click handlers for reply/cancel buttons are now in-line, no need for extra functions
The inputs no longer have IDs you need to track, it just finds them relatively
Table has a class replyTable so it all old ones can be hidden quickly
Inputs have classes to find them easier (to bind the click handlers)
No more count, no need :)
Animates the body, does a quick scroll effect to the location and focuses the text area
Removes old tables to cleanup

Categories