dynamically find jquery element if exists - javascript

i have a function, where if called, will update another object if it exists. thing is, when the page is created the id is not known.
so, for example, heres my code:
$('.slides').on("slidestop", function() {
$this = $(this);
$.ajax({
url: "action.php?event=ITEM "+$this.attr("data-itemID") + " " + this.value+"&itemID="+$this.attr("data-itemID"),
type:'POST',
success: function(result){
//update brightness slider if it exists
$("#sl" + $this.attr('data-itemID')).val(15);
$("#sl" + $this.attr('data-itemID')).slider("refresh");
},
});
});
html:
<input class='dimmerSlider' type='range' id='3' value='4' min='0' max='15' step='1' data-highlight='true' data-itemID='3'/>
error:
Uncaught TypeError: $(...).slider is not a function

$("#$this.attr('data-itemID')").val(15);
I am guessing you wanted to build a string using the attibute
$("#" + $this.attr('data-itemID')).val(15);
or use data instead of attr
$("#" + $this.data('itemID')).val(15);
To answer your second question if the element can not be found.
If you select an element with jQuery and it does not exist, it will be ignored when you run methods against it. If you need to know it does not exist than you can check the length
var x = $(".mySelector");
if (!x.length) { //aka x.length===0
console.log("not found");
}

also, the element is not guaranteed to exist, how do i check for that
as well?
Try using Attribute Equals Selector [name="value"] , .is()
var elem = $("[id=" + $this.attr("data-itemID") + "]");
if (elem.is("*")) {
// do stuff
elem.val(15)
.slider("refresh");
}

Related

How to use checkbox for DOM display toggle (with objects)

I'm writing in jquery/javascript and I'm stumped. I have an input form that creates objects in an empty array, each object is a band, containing the band name and some other info.
Once these objects are made, they're displayed on the site as a list like an address book, creating a master list. Each display of the band object has a serialized checkbox, with their id's being set to 0, 1, 2, and so forth as they get created with each form submit. You can submit one band at a time, and it will add them to the array in the order you create them.
First I have an empty array to hold all the bands:
var bands = []; // This is the overall list of bands that have been entered.
Then I use this following function to add to the DOM, listing the bands out with a serialized checkbox for the users to check.
var showBands = function() { // this function will add the bands to the DOM
$("#all-bands").empty();
var totalNumberOfBandsInAddressBook = 0;
bands.forEach(function(band) {
totalNumberOfBandsInAddressBook++;
$("#all-bands").append(
'<div class="band-list">' + "<div class='row'>" + "<div class='col.md-2'>"
+ "<input type='checkbox' class='BandContactCheckbox' id='" +
(totalNumberOfBandsInAddressBook-1) + "'></input></div>" +
'<div class="col-md-10"><b>' + band.BandName + '</b><br>' +
band.BandMainContactFirstName + ' ' +
band.BandMainContactLastName + ', ' +
band.BandEmail + ', ' +
band.BandPhone +
'</div>' + '</div>' + '</div>'
);
});
}
And finally I'm stuck here, trying to get get this thing to find each checked box, no matter the order, and list the bands upon check or uncheck on the website:
$('form#all-bands-form').click(function(event) { // this function will display the bands in the "Bands to Add" section dynamically with the checkboxes turned on or off
$("input:checkbox[class=BandContactCheckbox]:checked").each(function(band) {
var bandID = $("input:checkbox[class=BandContactCheckbox]:checked").getAttribute('id').val();
debugger;
$('span#bandListForShow').text('<li>' + bands[bandID].bandName + ' test1' + '</li>')
});
});
I'm pretty new to a lot of this, so full explanations are most helpful. Basically my intention with this last function here is to have a click event listener on the checkboxes which would toggle the display on or off depending on whether the box is checked. With the checkbox ID being serialized, I was hoping to use that ID number to sort through the array locations per checkbox ID, but I can't figure out how to get this 'each' method to grab the attribute value.
Inside the .each() loop, you should use the band variable (or this) to refer to the current element of the loop. If you use the selector again, you're referring to all the checked boxes.
You shouldn't use .val() after calling getAttribute(). getAttribute() returns the attribute's value already. Also, getAttribute() is a DOM method, not a jQuery method (the analogous jQuery method is .attr()). But you don't need any method, just band.id will get the ID.
To get all the bands that were checked you should be using .append() rather than .text(). .text() replaces the text of the element rather than appending to it; also, it doesn't parse HTML, it will show the <li> literally.
Before the loop that appends, you need to empty the element; otherwise you'll add to whatever was shown on the previous click.
$('form#all-bands-form').click(function(event) { // this function will display the bands in the "Bands to Add" section dynamically with the checkboxes turned on or off
$('span#bandListForShow').empty();
$(".BandContactCheckbox:checked").each(function(band) {
var bandID = band.id;
$('span#bandListForShow').append('<li>' + bands[bandID].bandName + ' test1' + '</li>')
});
});

How to bind image to the div tag multiple time

I want to bind my image to the div tag.it bind only to the first object and not
all.
I stored images in azure blob storage.
type: "Get",
url: "/contollerName/methodname",
success: function (result) {
data = JSON.parse(result);
alert("Pic " + data.ContentType +" "+data.Content);
$('#MyProfile').attr('src', "data:" + data.ContentType + ";base64," + data.Content);
this methods gives me image.and the same id i.e MyProfile I am using for div tag
You are referencing the divs by ID. In valid HTML you must only use a ID once per page. Change it to class and reference it in jquery. Although a div has no src attribute, but you want to reference an image:
<div class="profilePic"><img src="value.png"/></div>
The jquery part:
$('.profilePic img').attr('src', "data:" + data.ContentType + ";base64," + data.Content);
First of all, use a class instead of ID like $('.bindImage').attr(...).
Second one, you get multiple elements back, so you need to go through them:
var elements = $('.bindImage');
elements.forEach(element, index) {
element.attr('src', "data:" + data.ContentType + ";base64," + data.Content);
}
Do not use ID selector for multiple element!
var $profiles = $('.MyProfile');
$profile.forEach(element, index) {
element.attr('src', "data:" + data.ContentType + ";base64," + data.Content);
}
css id selector (#MyProfile) only returns the first element it finds on the page since ID selector should be unique on the page. It seems like you actually want to use class selector (.cssClassHere)

variable in onclick function of dynamically created button

Hy,
Basically, I have a number of dynamically generated list items with a button in them. When I prepend the list item to the ul list, I have access to a variable that I want to pass when I click the button in the list items. But when I add the variable in the line of code shown below, it gives me a Uncaught ReferenceError: challenger is not defined error. How can I pass these variable along?
JAVASCRIPT:
window.GLOBAL_socket.on('challenged', function(data) {
console.log("You have been challenged by the player " + data.challenger);
var challenged = getUrlVars()['user'];
var challenger = data.challenger;
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>" + data.challenger +
"</p><input type='button' value='ACCEPT' id='challenge_accept' onclick='acceptChallenge(challenger)'></input><input type='button' value='DECLINE' " +
"id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
});
The onclick method is found on line 6.
Thanks for your responses,
Zeno
The reason why challenger is not defined is because it's a local variable and is not accessible globally when you actually trigger the function with a click.
So instead of using the variable, just place it's actual value in the onclick.
Change your code to:
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>" + data.challenger +
"</p><input type='button' value='ACCEPT' id='challenge_accept' onclick='acceptChallenge(\""+challenger+"\")'></input><input type='button' value='DECLINE' " +
"id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
Change your code as I mentioned in comments.
var challenged = [];
var challenger = [];
var counter = 0;
window.GLOBAL_socket.on('challenged', function(data) {
console.log("You have been challenged by the player " + data.challenger);
counter++;
challenged[counter] = getUrlVars()['user'];
challenger[counter] = data.challenger;
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>"
+ data.challenger
+ "</p><input type='button' value='ACCEPT' id='challenge_accept'"
// change of code --> passing value directly into the function
+ " onclick='acceptChallenge(challenger["+counter+"]
+")'></input><input type='button' value='DECLINE' "
+ "id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
});
I just modified code, hope it works for you. Let me know

JQuery how to id of the button that called the function

I have a button <button onclick="takedown()"> that when it is clicked JQuery will create a new button with the id of the text in a input and button, when that button is clicked it will call a function deltebutton() which should delete the button, but I need for JQuery to get the id of the button which called the function and set it to a String called id.
I tryed $(event.target).attr('id'); and $(this).attr('id'); but both of them did not work
I goggled it but could not find anything.
This is the functions
function takedown(){
note = document.getElementById("noteinput").value;
idh1 = note + "h1";
idbutton = note + "button";
idcenter = note + "center";
$('<center id="' +idcenter + '"> <h1 idh1="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
and
function deletenote(){
String id = $(event.target).attr('id');
$(id).remove();
}
If anybody knows how to do this, it will be very helpful.
Dont use String in JS and jQuery. And your selector is wrong.
function deletenote(){
var id = event.target.id;
$('#'+id).remove();
}
Also I think you can just call remove without getting the ID.
function deletenote(){
$(this).remove();
}
A simpler solution building on the previous answer and comments would be:
function deletenote(){
$(event.target).remove();
}

Removing rows that do not contain search-term with jQuery

I'm using the following JQuery to filter rows on a datatable, which works fine...
yuiDtFilter = function(tableDivId, filter) {
//custom jQuery function defines case-insensitive fn:Contains, use default fn:contains for case-sensitive search
jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
$("#" + tableDivId + " .yui-dt-data").find('tr').hide();
$("#" + tableDivId + " .yui-dt-data").find('td:Contains("' + filter + '")').parents('tr').show();
}
However I have a need for the filter work in the opposite way. I need it to remove rows that don't match the search terms.
I've found out that I need to use 'not()', but I've spent most of the day in vain trying to get it to work (using every example I can find).
I've tried many variations of -
$("#" + tableDivId + " .yui-dt-data")
.find(:not(('td:Contains("' + filter + '")'))
.parents('tr').remove();
Could anyone give me a hand using my code as a starting point?
Try
$("#" + tableDivId + " .yui-dt-data").find('td').not(':contains("' + filter + '")').parents('tr').remove();
or
$("#" + tableDivId + " .yui-dt-data").find( 'td:not(:contains("' + filter + '"))' ).parents('tr').remove()
Remove row from HTML table that doesn't contains specific text or string using jquery.
Note: If there are only two column in HTML table, we can use "last-child" attribute to find.
*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:last-child");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.
Passing column index with "nth-child(column index)"
$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:nth-child(2)");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: "DrivePilot" is nothing but text or string

Categories