select element with class and id with jquery - javascript

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.

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.

Cannot read property : style of Null

I am working on a Trello Board using Vanilla Javascript and I am receiving an error on making my Cards . I have used Local and Session Storage to store the cards and lists respectively but I can't figure out why this error persists after I click on the Add Card Board Button
function newTask(x){
card_index= parseInt(localStorage.getItem("card_indices")) ;
//card_index = parseInt(sessionStorage.getItem("card_indices"));
list_index = parseInt(sessionStorage.getItem("index"));
document.getElementById('myTasks').innerHTML +=
'<div id = "list_' + list_index + ' " class="list-item animated zoomIn" > <h2 id = "title_' + list_index +'" onClick = "modifyObj.titleEdit('+ list_index +')" class="list-item__h2">'+x+'</h2><span id = "span_del_' + list_index + '" class ="btn title-delete" onClick ="modifyObj.titleDelete(' + list_index + ')">\u00D7</span><hr>'+
'<input id = "card_del_' + card_index + '" type="text" class="myInput" placeholder="Title...">' +
'<div class="btn add-items " id = "div_add_list_" onClick = "myCard.titleForm(' + list_index + ',' + card_index + ')" >Add List Item</div>'
'</div>'
sessionStorage.setItem("index", parseInt(sessionStorage.getItem("index"))+1);
}
var myCard = {
card:function(index, card_index){
var enteredElement = document.getElementById('card_del_' + card_index).value;
var textNode = document.getElementsByClassName('text_' + card_index);
textNode.innerText = enteredElement;
if (enteredElement === ""){
alert("You must write something ");
}
else{
document.getElementById("text_").style.display = "block";
}
},
titleForm: function(index,card_index){
element = document.getElementById('card_del_' + card_index);
text = '<li style="display:none" class="text_'+ card_index +'"> <span class = "btn items" onClick = "myCard.cardClose()">u00D7</span></li>'
element.insertAdjacentHTML('beforeend', text);
myCard.card(index,card_index);
localStorage.setItem("card_indices", parseInt(localStorage.getItem("card_indices"))+1);
// card_index+=1;
}};

Multiple Counting Buttons JS

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>**

HTML - JavaScript - Adding and Deleting/Hiding Elements

In my website the user is going to select an image, that image will then be inserted into a div tag. I need it so when the user clicks the image that was inserted into the div then it will be removed (deleted or hidden) from the div. I've tried:
document.getElementById("elementId").style.display = "none";
and other similar things. I really just cant get this to work please help!
HTML + JavaScript code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
var addCard = function(cardName)
{
if("undefined" != document.getElementById("card" + cardNumber).value)
{
if(deck.indexOf(cardName) > -1)
{
}
else
{
if(deck.length != 1)
{
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if(deck.length >= 1)
{
cardNumber = 1;
}
}
}
}
</script>
</head>
<body>
<div id = "card1" class = "cards"></div>
<div id = "1">
<img class = "cardSize" onclick = "addCard('Archer')" src = "Images/Cards/Archer.png">
</div>
</body>
CSS Code:
.cards
{
height:150px;
width:125px;
float:left;
margin-left:6.2%;
margin-bottom:30px;
border:5px solid #ff6666;
background-color:#ff6666;
}
.cardSize
{
height:150px;
width:125px;
float:left;
margin-left:7%;
margin-top:30px;
}
You can delete the img by id.
Also fix the issue with the updateCards function:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = "updateCards(\'' + cardName + '\')" src = "' + cardName + '.png">';
For example,
<div id="card1" class="cards">
<img id="Archer" class="deckCardSize" onclick="updateCards('Archer')" src="Archer.png">
</div>
Then just remove the div with id="Archer":
document.getElementById("Archer").remove();
FYI, I added a simple updateCards function that just hides the img instead of removing it entirely :
var updateCards = function(cardName) {
document.getElementById(cardName).style.display = 'none';
}
You need to attach a click event listener to a class that is applied to all inserted images. the function that the listener fires would then apply css.style.display = "none" to this
First, remove all spaces between attributes and its values (I mean everywhere in your code), that is:
<div id="card1" class="cards"></div><!-- correct -->
<div id = "card1" class = "cards"></div><!-- incorrect -->
Second, you have an error in your code here:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
You have missed double quotes around onclick's value. Replace it with this:
document.getElementById("card" + cardNumber).innerHTML = '<img id="' + cardName + '" class="deckCardSize" onclick="updateCards(' + cardName + ')" src="Images/Cards/' + cardName + '.png">';
Also, you have to define function updateCards(name), it maybe empty, but it must exists. If it doesn't exists, than any javascript code will stops running after you clicked on that image.
Third, <div id = "1"> has an error too. id attribute must starts from a letter.
here is working code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
function addCard(cardName) {
if ("undefined" != document.getElementById("card" + cardNumber).value) {
if (deck.indexOf(cardName) > -1) {
} else {
if (deck.length != 1) {
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id="img' + cardName + '" class="deckCardSize" onclick="updateCards(\'' + cardName + '\')" src="Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if (deck.length >= 1) {
cardNumber = 1;
}
}
}
}
function updateCards(cardName) {
//some work
document.getElementById("img" + cardName).remove();
}
</script>
</head>
<body>
<div id="card1" class="cards"></div>
<div id="main1">
<img class="cardSize" onclick="addCard('Archer')" src="Images/Cards/Archer.png">
</div>
</body>
Tested and worked!

How to move up/down div on one place use onclick in jquery

This is my first post so I asked for help and possible comments.
I would like to do change div (which is added by using the tool: AddR) by one position up and down when I click "onclick" with jQuery function.
I wrote something like that but it did not work ..
Could someone help me what should I improve?
Thanks for your help
<script>
function AddR(k) {
Radio_L = Radio_L + 1;
Radio_N = "Radio" + Radio_L;
$("#" + k.id + "").append("<div id='"+Radio_N+"'>" + Radio_N + "<br /><br />" +
"<button type='submit' class='button' style='float: left;' onclick='AddR(" + Radio_N + ");' >Add</button>" +
"<button type='submit' class='button' style='float: left;' onclick='UpR(" + Radio_N + ");' >Up</button>" +
"<button type='submit' class='button' style='float: left;' onclick='DownR(" + Radio_N + ");' >Down</button><br />" +
"<br />" + "<input type='text'>" + "<br /><br />" + '</div>'
);
}
function UpR(k) {
var pos = (this).index();
var parent = $("#" + k.id + "");
parent.insertAfter(pos.next());
}
function DownR(k) {
var pos = (this).index();
var parent = $("#" + k.id + "");
parent.insertBefore((pos.next());
}
</script>
I would offer a solution which simplifies the HTML, does not put in hard coded HTML in the code and uses classes rather than a lot of code embedded in the markup.
With this markup to start:
<div id='Radio_N0' class='container'><span class='containerName'>Radio_N 0</span>
<br/>
<button type='submit' class='button add'>Add</button>
<button type='submit' class='button up'>Up</button>
<button type='submit' class='button down'>Down</button>
<br/>
<input type='text' />
<br />
</div>
You could use this code to create more of these and move them around:
function AddR(k) {
Radio_L = $('.container').length;
var Radio_N = "Radio_N" + Radio_L;
var newDiv = k.parents('.container').clone();
newDiv.attr('id', Radio_N).find('.containerName').text(Radio_N);
newDiv.insertAfter(k.parents('.container'));
}
function UpR(k) {
var parent = k.parents('.container');
var pos = parent.prev();
parent.insertBefore(pos);
}
function DownR(k) {
var parent = k.parents('.container');
var pos = parent.next();
parent.insertAfter(pos);
}
$(document).on('click', '.add', function () {
AddR($(this));
});
$(document).on('click', '.up', function () {
UpR($(this));
});
$(document).on('click', '.down', function () {
DownR($(this));
});
See it in action here: http://jsfiddle.net/uka2C/
var pos = (this).index();
^---- Missing $ sign
supposed to be
var pos = $(this).index();
Also
pos with give you an number and they do not have the next method. Only jQuery objects do
Try this
function UpR(k) {
var $elem = $(this).next();
var parent = $("#" + k.id + "");
parent.insertAfter($elem);
}
Try this code (also here: http://cdpn.io/AjHyE), i've found some syntax errors:
<script>
var Kon_L = 0;
function Kon() {
Kon_L = Kon_L+ 1;
var Kon_R_N = "Kon" + Kon_L;
$("<div id='" + Kon_R_N + "' class='ka' > " + "Kon " + Kon_L +
"<button type='submit' class='button' style='float: left;' onclick='UpR(\"" + Kon_R_N + "\");' >UpDIV</button>" +
"<button type='submit' class='button' style='float: left;' onclick='DownR(\"" + Kon_R_N + "\");' >DownDIV</button>" +
"<br />Tekst<br />" +
"</div>").appendTo(".Place");
}
function UpR(k) {
var self = $("#"+k);
var prev = self.prev();
self.insertBefore(prev);
}
function DownR(k) {
var self = $("#"+k);
var next = self.next();
self.insertAfter(next);
}
</script>
Also check your browser console to see if it's working.
Anyway, since you are asking for comments i'd recommend something to you:
remove the HTML from your JS code. You could reference the buttons with some jQuery selector and move them around
remove the inline style from HTML, you can easily move the float property inside the button class
decouple the JS from the HTML even more, don't use the onclick in the HTML but use the jQuery click() function with the selectors
If you try these modifications i think that you could get more feedback from the Stack Overflow community.

Categories