getting value from nearest of clicked button - javascript

i am trying to do a profile management function in that i want to add type of users that is students to other type of user's is teacher's database for that i am using i using jquery and ajax but i am facing a problem to accomplish that which is each student have a add button who are listed in in html page (this is listing done using php for selecting from data base) when i press add button of each student i get undefined in alert box
part of html is
<li class="studdet">
<div class="row">
<div class="col-md-6" id="studname">
<div class="col-md-3" id ="all">
<label>Name Of Student:</label>
<p id="nameOfStud" >name of student fetched from database</p>
</div>
<div class ="col-md-3">
<label></label>
</br></br>
<button class="btn-u" id="addStudents">Add</button>
</div>
</div>
</div>
</li>
<li class="studdet">
<div class="row">
<div class="col-md-6" id="studname">
<div class="col-md-3">
<label>Name Of Student:</label>
<p id="nameOfStud" >Name of student fetched from data base</p>
</div>
<div class ="col-md-3">
<label></label>
</br></br>
<button class="btn-u" id="addStudents">Add</button>
</div>
</div>
</div>
</li>
jquery for gettting value of student name is
$(document).on('click', '#all #addStudents', function() {
var option = $(this).closest("id","nameOfStud").html();
alert(option);
// $.ajax({url: "http://localhost/ededge/Add_students/add_to_group",data: {studentname : option},type:"POST", success: function(result){
// $('#studdet').attr('class','label label-light');
// alert(result);
// }});
});
but what i am getting is undefined in alert box
help me to find my error like before

$(document).on('click', '#addStudents', function() {
var option = $(this).closest('div#studname').find('p#nameOfStud').text();
alert(option);
});
closest('div#studname') searches for parent div in DOM heirachy with id studname
find('p#nameOfStud') searches for p tag descendants in DOM tree of earlier searched div.
.text() fetches text inside paragraph tag

You cannot have multiple ids in jQuery. ID is unique.
Try the following:
Change your <p> element as follows:
<p class="nameOfStud" >Name of student fetched from data base</p>
Change your 'button' as follows:
<button class="btn-u addStudents">Add</button>
Then try the following code:
$(function(){
$('.addStudents').click(function(){
var option = $(this).closest('.nameOfStud').html();
alert(option);
});
});

Related

How to execute a javascript function for every element in a list with Freemarker in Kotlin Ktor?

I'm calling an api with Kotlin and Ktor to get a book in return as json response. From this response I want to load the book cover in my frontend Freimarker .ftl file. I'm doing this call in javascript and write it to html.
When I'm calling the function like in my code shown, only the first element in the list get the book cover. The rest is empty.
The javascript is executed as inline code in html. I was excepting this function will be called for every new item in the list.
So what can I do to load the image for every element in my list?
index.ftl:
<#-- #ftlvariable name="books" type="kotlin.collections.List<com.nw.models.Book>" -->
<#import "_layout.ftl" as layout />
<#layout.header>
<#list books?reverse as book>
<div class="container-fluid">
<hr>
<div class="row justify-content-center">
<div class="card" style="width: 18rem;">
<img id="img-book" class="card-img-top" src="https://via.placeholder.com/128x209.png">
<div class="card-body">
<h5 class="card-title">${book.title}</h5>
<p class="card-text">${book.author}</p>
<input type="hidden" id="img-url" name="imageUrl" placeholder="${book.imageUrl}">
<script type="text/javascript">
(function() {
let a1 = document.getElementById("img-url").getAttribute("placeholder");
const image = document.getElementById("img-book");
image.src = a1;
})();
</script>
Go to Book
</div>
</div>
</div>
</div>
</#list>
<hr>
<p>
Create book
</p>
</#layout.header>
With the current DOM scripting approach the OP has to assure that the html render process actually creates a unique id value for each book item, thus img-url is not a valid id value for each book item. The same btw applies to each image element's img-book id value. And the placeholder attribute is not to be abused as data storage; the correct way is the usage of a custom data-* attribute.
One very easily could even implement an approach which is entirely free of id attributes and hidden input fields by just using both data related features the custom data-* attribute and the element's related dataset property.
<#-- #ftlvariable name="books" type="kotlin.collections.List<com.nw.models.Book>" -->
<#import "_layout.ftl" as layout />
<#layout.header>
<#list books?reverse as book>
<div class="container-fluid">
<hr>
<div class="row justify-content-center">
<div class="card" style="width: 18rem;">
<img data-book-cover-src="${book.imageUrl}" class="card-img-top" src="https://via.placeholder.com/128x209.png">
<div class="card-body">
<h5 class="card-title">${book.title}</h5>
<p class="card-text">${book.author}</p>
Go to Book
</div>
</div>
</div>
</div>
</#list>
<script type="text/javascript">
document
.querySelectorAll('img[data-book-cover-src]')
.forEach(elmNode =>
elmNode.src = elmNode.dataset.bookCoverSrc
);
</script>
<hr>
<p>
Create book
</p>
</#layout.header>

How to use divs as radio button and save data from inside the selected div to valiables using javascrip?

I have multiple divs in my HTML with sample class name and I want these divs to behave like a radio button, that is when a div is clicked / selected, I want to achieve following.
1: Change the selected div background color
2: Get values from different elements those are inside the selected div and save the values in variables.
I am able to change the color but I am not able to get the unique values from inside the selected div.
Here is the HTML
<div class="col-lg-4 text-center">
<div class="package">
<input type="hidden" class="packageId" value="5" />
<p class="small">Deep</p>
<h4 class="packageTitle">Deep Cleaning</h4>
<p>All-inclusive cleaning service</p>
<p class="small">Price Per Cleaner</p>
<p class="price packagePrice">41.90 <span class="small">/h</span></p>
</div>
</div>
<div class="col-lg-4 text-center">
<div class="package">
<input type="hidden" class="packageId" value="4" />
<p class="small">Last Minute</p>
<h4 class="packageTitle">Last-Minute Cleaning</h4>
<p>Last minute & after party cleaning</p>
<p class="small">Price Per Cleaner</p>
<p class="price packagePrice">43.90 <span class="small">/h</span></p>
</div>
</div>
<div class="col-lg-4 text-center">
<div class="package">
<input type="hidden" class="packageId" value="3" />
<p class="small">Moving</p>
<h4 class="packageTitle">Move-In-Out Cleaning</h4>
<p>For move-ins, and move-outs</p>
<p class="small">Price Per Cleaner</p>
<p class="price packagePrice">41.90 <span class="small">/h</span></p>
</div>
</div>
And here the the Script
var packageId = "";
var packageTitle = "";
var packagePrice = "";
var packages = document.getElementsByClassName('package');
Array.prototype.forEach.call(packages, function (element) {
element.addEventListener('click', function () {
$('.package').css("background-color", "#FFFFFF");
$(this).css("background-color", "#FCF6CC");
packageId = $('.packageId').attr('value');
packageTitle = $('.packageTitle').text();
packagePrice = $('packagePrice').text();
console.log(packageId);
console.log(packageTitle);
console.log(packagePrice);
});
});
The reason that youre not getiing the unique value is because you are using get element by class ,
ie packagePrice = $('.packagePrice').text();
and there are 3 elements with same class name , to fix this issue
const elem = $(this);
packagePrice = elem.find('.packagePrice').text();

Find document element by class name closest to the button that is being clicked

I have a little mini html game that uses Backbone.
The main page has multiple <div> tags with the class name of "monsterName".
There is a button near it, that, when clicked, I want to get the text that is inside the "monsterName" <div>
I am trying to use the closest() method from the WebAPI to find the closest <div> to the clicked button that has a class name of "monsterName".
Here this will help you see my HTML page generated by the view and template:
<div id="root">
<div id="title">Monster Hunting 101</div>
<div class="monsterArea">
<div class="monsterName">Orc</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
<div class="monsterArea">
<div class="monsterName">Dragon</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
<div class="monsterArea">
<div class="monsterName">Giant</div>
<div class="controls">
<button class="findMonster">Monster Hunting</button>
</div>
</div>
The view has code that fires when the button ".findMonster" is clicked:
events: {
"click .findMonster": "startHunt"
},
When that button is clicked, it fires this function:
startHunt: function (e) {
const $closestMonster = e.closest('.monsterName');
console.log($closestMonster.innerHTML);
...do some stuff with the text in the monsterName...
}
So the view is working and the button works, and it fires off the startHunt event.
But it always gives me this error:
Uncaught TypeError: e.closest is not a function
A combination of closest() and find() worked for this problem:
const $closestMonster = e.closest('.monsterArea').find('.monsterName');

Add a Like + Sort Function to existing dynamic funcion

I wrote a function that dynamically creates a webpage for me based on a json database.
Now I want to add 2 functions:
If you click the like img (its got the id button) the like counter should increase on the webpage by 1. Pretty easy just a on(click) with jQuery variable++ and then .text(variable)
A sort function - based on the likes one item received, you should be able to sort it (most liked div first, 2nd, 3rd....
I can write it for each individually with individual variables when I give all the like buttons and outputs a separate id but I wanted to make it dynamic so if you add new data to json file it dynamically works with the like and sort function.
The likes are not saved anywhere for now.
Since sitting on it for 3h and google so much and so much stackoverflow I think I overloaded my brain with different stuff and now nothing seems to work ^^
function filmInsert(insert) {
$.each(film, function(i, data) { //.each statt loop
let box =
`<div class="boxwrapper">
<div class="imgbox">
<img src="${data.img}" alt="${data.titel}">
</div>
<div class="textbox">
<h3>${data.titel}</h3>
<p>${data.beschreibung}</p>
<p> <a id="button${data.id}">
<img src="img/budspencer_official.png"> Like
</a>
<span class="output${data.id}">${data.likes}</span>
</p>
</div>
</div>`;
insert.append(box);
});
}
I've added a container element for the boxwrapper items as I assume you have one and as it's better to have one instead of just adding the sorted items to the body of the HTML document.
$(document).on("click", ".textbox a", function() {
let likes = parseInt($(this).closest(".textbox").find("span").text());
$(this).closest(".textbox").find("span").text(likes + 1);
});
$("#sort").on("click", function() {
let divs = $(".boxwrapper")
let sorted = divs.sort(function(a, b) {
return $(a).find("span").text() < $(b).find("span").text() ? 1 : -1;
});
$(".container").html(sorted);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel</h3>
<p>Description</p>
<p> <a id="button1">
<img src="https://dummyimage.com/40x40/000/fff&text=1"> Like
</a>
<span class="output1">0</span>
</p>
</div>
</div>
<div class="boxwrapper">
<div class="imgbox">
<img src="example.gif" alt="Title">
</div>
<div class="textbox">
<h3>Titel 2</h3>
<p>Description 2</p>
<p> <a id="button2">
<img src="https://dummyimage.com/40x40/000/fff&text=2"> Like
</a>
<span class="output2">0</span>
</p>
</div>
</div>
</div>
<button id="sort">
Sort
</button>

Get the id of a parent tag with a specific class from a form

I want to get the id of <a> tag, with a specific class, which is a parent (somewhere above in the DOM tree) of a form when I submit the form
<div class="article">
<div class="titre">Mon premier article de blog</div>
<div class="resume" style="display: none; ">Ceci est le premier article de blog <a id="1" href="#">link</a></div>
<div class="content">Ceci est effectivement mon premier article de blog
<div class="nb_com">2 commentaires</div>
<div class="form">
<form method="post" action="">
<div class="form_text">
<textarea name="com" id="com" rows="4" cols="122">... </textarea>
</div>
pseudo : <input type="text" name="pseudo" id="pseudo">
mail : <input type="text" name="mail" id="mail">
<input type="button" value="Commenter" onclick="enregistre_com(this.form.com.value,this.form.pseudo.value,this.form.mail.value,this.parentNode.innerHTML">
</form>
</div>
</div>
<div class="comment">
</div>
</div>
When I click on the button, I want to retrieve the value of the id of <a> tag which is in the <div class="resume"> tag. The javascript or jquery expression will take place instead of this.parentNode.innerHTML (it was just test purpose)
Use .closest() to go up to the first shared container (.article) and then use .find() to find the <a> inside the .resume element..
$(this).closest('.article').find('.resume a')[0].id;
$('.form :button').click(function(){
var id = $('.resume a').attr('id'); //
// the variable id contains the content of the id attribute
});
You may want to change the selectors according to your other markup.
I'm not sure which element you're looking for specifically in your example, but you should look into using jQuery's .parents([selector]) method (see API page here)
$('form input[type=button]').click(function(){
var id = $(this).closest('.className').attr('id');
});
this will be the id your tag when the input button is clicked, even with multiple "resume" classes:
id = $(this).closest('.article').find('a').attr('id');
here is a working example:
http://jsfiddle.net/JMEPj/2/
Finally, it look like
<input type='button' value='Commenter' onClick='enregistre_com(this.form.com.value,this.form.pseudo.value,this.form.mail.value,$(this).closest(\".article\").find(\".resume a\").attr(\"id\"))' />
I was in trouble with the " and the ' because all this js form is encapsulated in php source

Categories

Resources