I'm trying to get the ID of a button but I can't seem to get it but rather getting the ID of the div which isn't what I want.
Here's what I'm currently doing:
HTML
<div class="container container-about container-login">
<div id="white-container" class="white-container about-text2 bottom-padding-fortypx">
<p id="availableTitle" class="text-center avail-title">Available</p>
<p id="acceptedTitle" class="text-center accept-title">Accepted</p>
<div id="availableJ" class="contractor-dash-div available-j"></div>
<div id="acceptedJ" class="contractor-dash-div accepted-j"></div>
<div class="clear"></div>
</div>
</div>
Javascript:
i++;
$('<div>', {
id: 'available' + i,
class: "avail-accept-jobs-div margin-bottom-twentypx"
}).appendTo('#availableJ');
$('#available' + i).append('<div class="delete-job initial-hidden"><p class="text-center font-weight-bold"><b>X</b></p></div>');
// Populating the available list
$('#available' + i).append('<p class="customer-name partial-name">Name: ' + partialName + '</p>');
$('#available' + i).append('<p class="customer-name full-name initial-hidden">Name: ' + name + '</p>');
$('#available' + i).append('<p>Date: ' + date + '</p>');
$('#available' + i).append('<p>Time: ' + time + '</p>');
// Get this buttons ID
var but = $('#available' + i).append('<div class="accept-job-button text-center"><p>Accept</p></div>');
but.id = keys;
// I understand this is getting the id of the div but the button is essentially a div
$("div").click(function() {
alert(this.id);
});
My question:
How am I able to get the actual ID of the button which is actually a div?
this should be the element that fired the event.
you could also respond to the button's click event, directly, instead of waiting for it to bubble up to the div.
if you want the button ID, you can add it as an attribute to the divs firing the event.
if you add matching "btnID" data attributes to the divs and their button, you can get back what you need (in the same attribute) when the user clicks on the div or its button.
BTW, is the value of keys being updated somewhere? if not, it appears you will allow "shared" ID values.
I misread the original question. If you want to select a child element it is as follows.
$("div > .accept-job-button").click(function() {
alert(this.id);
});
Related
So I have a get json function that makes items appear on my page, there is a button with json included inside of it that when is clicked I want the item to appear inside an alert (its called cart) - its going to be a simple shopping cart that is hidden on page ready/load. So when the user clicks this button parts of my json file appear inside of the alert, like a shopping cart, If there can be a total to calculate the price this would be good but is not necessary.
So this is my script to get the json and display it on my page :
$.getJSON('iproducts.json',function(products){
var output = "";
$.each(products.appleitems, function(i, product) {
output +=
"<div class=\"col-xs-12 col-sm-6 col-md-3\"><div class='panel panel-default'><div class='panel-footer'><h4 class='text-center'>"
+ products.appleitems[i].Product_id
+ "</h4></div>" + "<img src ='" + products.appleitems[i].Imgpath + "' style='width:100%;height:250px; display: block;' id='appleinfo_"
+ products.appleitems[i].Product_id +
"' /><p class='lead text-justify'>" + products.appleitems[i].Information
+ "</p><div class='panel-footer'><button class='btn btn-primary btn-block' id='btncart'>£" + products.appleitems[i].Price+"</button></div></div></div>";
});
$("#container").html(output);
});
as you will notice this is the button I am talking about:
<div class='panel-footer'><button class='btn btn-primary btn-block' id='btncart'>£" + products.appleitems[i].Price+"</button></div>
the price is displayed inside of the button.
This is a snip (one of the products, there are about 12 products in total) from my json file:
{
"appleitems":[
{
"Product_id":"Iphone5",
"Information":"Iphone 5 64GB",
"Imgpath":"image/iphone5.jpg",
"Price":"200.00"
}
]
}
This is the alert I want the name and price to display in when the button is clicked:
<div class="alert alert-warning" id="cart"></div>
Here is a bit of a clue from a previous script I worked on, when the user entered their name/ login details (from the json) and they matched their name, picture and details would appear in the welcome alert, I also had a hide button inside this alert that then hid the welcome alert and this is how I got it to work ( could be quite similar to this only .show():
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
Kind Regards
So on button click you want to update the alert div with it's price.
Here is a code block explaining things you need.
According to this html
$('.btn-block').click(function(e){
//alert($(this).attr("value")); //get value of button
$("#cart").empty(); //clear div every time on click
$("#cart").html($(this).attr("value")); //this will update div with value of button.
var product_information = $(this).closest("div").prev("p").html();//This will get you product info
});
I have added some explanation as comment.This are self explanatory.
Important
I notice you assign hardcore id in each loop in button which is not correct.You should always assign dynamic id as id cannot be same.
Ive been desperately trying to get this to work.
Iknow there are probably better ways to do this other than the way I am trying but its for an assignment and has to be done this way.
I am creating a simple shopping cart/ the cart does not have to add a total just get the items inside of the panel (if anyone knew how to add the price also that would be brilliant but not 100% necessary)
So I have displayed items of json using json and ajax, on page ready the items are on show as so (there are about 12 items):
so I have the panel hidden, when the user clicks on a button (the blue button) I want the json information and the json price to appear inside the panel.
here is a snip of one of the items from my json file (which is called result.json:
{
"appleitems":[
{
"Product_id":"Iphone5",
"Information":"Iphone 5 64GB",
"Imgpath":"image/iphone5.jpg",
"Price":"200.00"
}
]
}
This ishow my items are displayed:
$.getJSON('iproducts.json',function(products){
var output = "";
$.each(products.appleitems, function(i, product) {
output +=
"<div class=\"col-xs-12 col-sm-6 col-md-3\"><div class='panel panel-default'><div class='panel-footer'><h4 class='text-center'>"
+ products.appleitems[i].Product_id
+ "</h4></div>" + "<img src ='" + products.appleitems[i].Imgpath + "' style='width:100%;height:250px; display: block;' id='appleinfo_"
+ products.appleitems[i].Product_id + "' /><h5 class='text-center'>" + products.appleitems[i].Information
+ "</h5><div class='panel-footer'>`<button class='btn btn-primary btn-block' id='btnadd'>£" + products.appleitems[i].Price+"</button>`</div></div></div>";
});
$("#container").html(output);
});
and you will notice the button that I want clicked to display the json is btnadd:
<button class='btn btn-primary btn-block' id='btnadd'>£" + products.appleitems[i].Price+"</button>
so when the user clicks btn add I want the json "information" and "price" to display inside of the pannel cart:
<div class="panel panel-default">
<div class="panel-body" id="cart"></div>
I have started the script for this:
$(document).ready(function() {
//Hide alert when page loads
$("#cart").hide();
//get the item into the panel
$("#btnadd").click(function(event){
$.getJSON('result.json', function(add) {
...
});
});
});
First of all, You are having same Id value for all the buttons(inside the loop). Duplicate Id's are not valid. So may be you can remove that and add a css class to the button for the jQuery selection. Also i would recommend keeping the price and information in HTML5 data attributes on the button for easier read.
var output ="";
$.each(products.appleitems, function(i, product) {
output += "<div><div>"
output +="<button class='btn btn-primary btn-block addBtn' data-info='"+
product.Price +"' data-price='"+
product.Information +"'>£" + product.Price+"</button>";
output +="</div></div>";
});
And listen to the click event on this specific css class
$(function(){
$(document).on("click",".addBtn",function(e){
e.preventDefault();
var _this=$(this);
var c=_this.data("info") + " " +_this.data("price");
$("#cart").html(c);
});
});
Here is a working sample
Although the question title gives an impression that I want to ask one question, but there are two problems I have facing at the moment.
I have gone through few similar questions on how to clear the input text area on button click, but most of them are for fixed input class or id's.
Problem 1: I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
Problem 2: After entering individual values in the betslip input boxes and if I click "clear all" button. It should clear all the inputs entered earlier in the bet slip.
Here is the HTML structure
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field - This is where I am creating the input fields
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text" class="betInput"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
HTML for Apply to all and Clear all button
APPLY TO ALL <input type="text">
CLEAR ALL
JS where I need to implement those 2 functions
function applyToAllBetInput() {
$('.apply').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
}
function clearAllBetInput() {
$('.clearall').click(function() {
$('div.bet').find('input').val('');
});
}
The best thing to do is remove the inline event handlers from the links, like this...
APPLY TO ALL <input type="text">
CLEAR ALL
Then, assign the event handlers in your script...
$("a.button.apply").on("click", function(e) {
e.preventDefault();
applyToAllBetInput($(this).find("input").val());
});
$("a.button.clearall").on("click", function(e) {
e.preventDefault();
applyToAllBetInput("");
});
And this would apply the value to all inputs...
function applyToAllBetInput(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}
If you pass a parameter into applyToAllBetInput and then set the inputs with that then you only need the one function, as they both do the same thing, but with different values. Best to only have 1 bit of code if it's only doing 1 thing, then you only have to fix it once if things change in the future :)
Please replace the id's i've given with your actual button/textarea ids (give ID's to your elements).
$('#txtApplyToAll').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
$('#btnClearAll').click(function() {
$('#txtApplyToAll').prevAll().find('input[type=text].val('');
});
There are several general suggestions I'd make before even starting to write the code. First, Why are you using longhand JavaScript when you have jQuery available? For example:
inputId = divId.document.getElementById('input');
should be simply:
inputId = $(inputId).find('input');
(or something along those lines--I'm not sure what you're after with that.)
Next, you're using inline click handlers. Instead, use event listeners:
<a href="javascript: applyToAllBetInput()" ...
Should be
$('a#my-id').click(function() { ... }
Finally, you can target all your inputs for clearing with a selector like this:
$('div.bet').find('input').val('');
I have a problem getting my little script to work correctly, and was just looking for a little guidance. I'm trying to make it so that when I click on a legislator's name, it will display more information about them, underneath their name. Such as their party, and district. However, when I click on a name, all it does is post more List-items underneath the legislators names. I'm very new to programming and I'm sort of stuck on what to do here. Any suggestions? I'm using Sunlight Congress API if that helps.
Here's the HTML
<body>
<h1>Find your local legislators</h1>
<form id="get-zip">
<label for="zip">Enter your Zip code:</label>
<input id="zip" type="text">
<button type="submit">Look up</button>
</form>
<ul id="legislators"></ul>
</body>
And the JavaScript
$(function(){
$("form#get-zip").submit(function(){
var zip = $("input#zip").val();
$.get("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=PUT-YOUR-API-KEY-HERE&zip=" + zip)
.done(function(responseJSON){
responseJSON.results.forEach(function(legislator){
$("ul#legislators").append("<li>" + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")</li>");
$("ul#legislators").click(function(){
$("ul#legislators").append("<li>" + legislator.party + " " + legislator.district + "</li>").toggle();
});
});
});
return false;
});
});
I suggest that when you create the li elements in your forEach loop you add all of each legislator's details, but put the part for which you want to toggle visibility in a separate child element. So the dynamically created li elements would look something like this:
<li>
<p>Juanita Johansson (Senate)</p>
<p class='details'>JavaScript Party Canberra</p>
</li>
And then add a details class to your stylesheet to hide the secondary details by default:
.details { display : none; }
Note that then the visibility is not the only thing you can then style separately for the details - you could also put them in a smaller font or whatever.
Then you can add a delegated click handler to the ul element that toggles based on that class:
$(function(){
$("#legislators").on("click", "li", function(){
$(this).find("p.details").toggle();
});
$("#get-zip").submit(function(){
var zip = $("#zip").val();
$.get("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=PUT-YOUR-API-KEY-HERE&zip=" + zip)
.done(function(responseJSON){
responseJSON.results.forEach(function(legislator){
$("#legislators").append(
"<li><p>" + legislator.first_name + " " + legislator.last_name +
" (" + legislator.chamber +
")</p><p class='details'>" +legislator.party + " " +
legislator.district + "</p></li>"
);
});
});
return false;
});
});
A general note about the selectors you're using: if selecting by id you can just say $("#idHere"), there's no need to include the tagname first.
Not sure why I cannot get this to work. Tried a few permutations now.
I have built a JSFIDDLE here.
I cannot get this jQuery to return the inner HTML for the target element. Is it because of the number child elements in the hierarchy?
jQuery:
modalContentLeft = 'Project: ' + $('#mob-' + uuid + ' div.project-name').html();
I have also tried using .find() without success. Thanks for any help.
I found your fault:
you are closing the div tag of the id before it gets to the name.
You are closing it before the class <div class="mobile-item-row clearfix">, so the selector does not find the children ".project-name" in it,because there is none. if you remove the closing tag and close it at the end of the HTML and change the syntax of the selector a bit, it works.
Project: ' + $('#mob-'+uuid+' .project-name').html()
Here you go: https://jsfiddle.net/ucupbtsf/5/
First your post here and your jsfiddle don't reflect the same...
JsFiddle :
modalContentLeft = 'Project: ' + $('#mob-' + uuid + ' div div .project-name').html()...
Here :
modalContentLeft = 'Project: ' + $('#mob-' + uuid + ' div.project-name').html();
Then, your html is :
<div class="mobile-item-row-first first-row clearfix" id="mob-6c985947-c68a-4f5b-9ebe-0d488b696f0d">
<div class="project-client pull-left">
<i class="ion-ios-people ion-fw" data-original-title="" title=""></i> Sienna Cremin
</div>
</div>
which does not reflect your jquery selector :
$('#mob-' + uuid + ' div div .project-name').html()
Seems you closed too much div, so your .project-name div is not in the #mob-id div.
$(elem).html() will get you all the content of the div (including the <i></i> part). If you only want the text, you can go for $(elem).text().