Removing <p> element with jQuery - javascript

This is a jQuery function that determines the class of an image within a table and acts accordingly. If the image parent doesn't have the class selected, it gives it that class and then adds the td id to a div (order). If it does have the class selected, it should remove the class, which it does, and then remove the p element containing the td id.
$(document).ready(function () {
$('td img').click(function () {
if ($(this).parent().hasClass('x')) {
alert("Seat " + ($(this).parent().attr("id")) + " is taken");
} else if ($(this).parent().hasClass('selected')) {
$(this).attr('src', 'images/a.gif');
$(this).parent().removeClass('selected');
var z = $(this).parent().attr('id');
$(z).remove();
return false;
} else {
$(this).attr('src', 'images/c.gif');
$(this).parent().addClass('selected');
alert($(this).parent().attr("class"));
var z = $(this).parent().attr('id');
$('<p>').attr('id', z).text(z).appendTo('#order');
return false;
};
});
});
It works up until removing the p element, where it just doesn't. The p id is dynamically set and is the same as the td id, hence the use of a variable to choose the id.

Ok, so it was a combination of answers on here.
Firstly, the ids weren't unique, so I added a suffix to them:
var z = $(this).parent().attr('id');
$('<p>').attr('id', z+'1' ).text(z).appendTo('#order');'
Then used the suggestion of $('#' + z).remove(); but changed it for my new suffix, so it now shows this $('#' + z+'1').remove();
All seems to be working now, thanks for your help.

Related

Change div id attribute on click

I have two divs. When I click on a button it moves to another div
Here is it looks like
I realize it like this
var counter = 0;
$('.click2').on('click', function () {
counter++;
if (counter > 10) {
return false;
}
else {
var elem = $(this).closest('.title');
$('.title2').append($(elem).html()).show();
}
});
But I have one problem I need to change Id of elements when it moves
I know that is realizing like this
$(this).attr('id', '.title_left');
But I can have 1-10 divs in left column and need to name it .title_left1. Next will be title_left2 and ++
How I can code it?
You can just append counter to the id attribute:
$(this).attr('id', '.title_left' + counter);

Javascript - Pull attribute into array/delete items based on attribute

I want to pull into an array the classes of all of the <img> in a particular <div> and then use those classes to delete the first <img> that shares that class in a different <div>.
So far, I have this that calls the original array:
var class = $('.frame div img').each(function() {
return $(this).class;
}).get();
class.forEach(function(entry) {
console.log(entry);
});
The log outputs a list of the <img></img> lines.
After that, I get stuck.
//Iterate through array and delete first <img> in #grid that has the same class, limit one per iteration.
// var img_class = $.each(class, function(key, value) {
// console.log(value);
// return $(this).attr('class');
// });
$('#grid img').each(function(){
if($(this).attr('class') == img_class){
$(this).remove();
}
});
The goals are:
Getting an array of classes into the img_class variable
Delete only the first <img> as it iterates through each class in the array
Thanks!
I am not sure if I understood it right but would something like this be of any help?
var firstIDs = "";
$('.frame div img').each(function() {
firstIDs += $(this).attr('id') + ",";
});
var SplitIDs = firstIDs.split(",");
$('#grid img').each(function(){
for(var i = 0; i < SplitIDs.length; i++) {
if($(this).attr('id') == SplitIDs[i]){
$("#grid img #"+$(this).attr('id')+":first").remove();
}
}
});
I would suggest to use some other attribute than class, eg. 'data-type'.
With the collected attribute values (e.g. 'types' array) do:
var $grid = $('#grid');
// iterate over collected types
types.forEach(function(type)) {
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
}
You could also do all in one rush:
// iterate over source <img> set
$('.frame div img').each(function() {
// get current images type-attrib
var type = $(this).attr('data-type');
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
});
Try
$(function() {
var classes = $.map($(".frame div img"), function(v, k) {
return [$(v).attr("class")];
});
var d = [];
console.log($("#grid img").length);
$.each($("#grid img"), function(k, v) {
if ( classes.hasOwnProperty($(v).attr("class")) ) {
d.push(v); $("body").find($(d.slice(0, 1))).remove();
};
});
console.log($("#grid img").length);
});
jsfiddle http://jsfiddle.net/guest271314/yv95C/

Clone jquery mobile input field with data-clear-btn="true"

Using jquery and jquery mobile I try to make a dynamic form. Input fields are created or removed so that always one empty input field is left.
This is my jquery code to achieve this (try it here:
http://jsfiddle.net/SR864/17/):
$(document).ready(function() {
var total = 1;
// add new field
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
});
$("#bar").on("input", ".input", function() {
// remove empty field
if ($(this).val() == "") {
$(this).closest("p").remove();
}
});
});
I also would like to have "delete-buttons" inside of the input fields to remove the text from the input fields. jquery mobile provides data-clear-btn="true" for that. However, somehow the behavior of data-clear-btn="true" only works for the first input field - the new (cloned) ones don't get the clear button.
Question
How can I have the clear-buttons for the cloned input fields?
Bonus question
What is necessary to have input fields deleted when they are empty after the clear button is pressed?
jQM wraps input fields in a div ui-input-text. You need to clone input itself - not the wrapping div - change its' id, name, val()...etc. Then add it to form and enhance it using .textinput() function.
Moreover, you should wrap code in pagecreate event.
$(document).on("pagecreate", function () {
var counter = 0;
$("#bar").on("input", function (e) {
if ($(e.target).val().length === 1) { /* after 2 characters add a new input */
counter++;
var id = "input-" + counter;
var input = $(e.target).clone().prop({
id: id,
name: id
}).val("");
$(e.target).closest(".ui-input-text").after(input);
$("#" + id).textinput();
}
});
});
Demo
I had a check at the problem. By default the cross button (which is an tag) has a class 'ui-input-clear-hidden' which keeps it hidden till you type. Though you are cloning the element after you start typing, the duplicate element also has this class which keeps it hidden (may be cloning is done before the class 'ui-input-clear-hidden' is removed). So I suggest removing the class 'ui-input-clear-hidden' from your cloned object explicitely as shown below.
$("#bar").on("input", ".input", function() {
// add new field
if ($(".input").last().val() != "") {
var newFields = $(this).closest("p").clone();
newFields.find(":input").each(function() {
var name = $(this).attr('name').replace('-' + (total - 1), '-' + total);
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('');
total++;
});
$(this).closest("p").after(newFields);
}
/* New line Added for Fix*/
newFields.find('a').removeClass('ui-input-clear-hidden');
});

Get unique selector jQuery

I need to be able to get an unqiue selector for each element on a page.
For example, when I click on an element I want to do something like this:
$(document).click(function(){
var sel = getUniqueSel(this);
});
So, after storing the sel value in a DB I can get that value and simply access the element by
var el = $(sel);
I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.
Another approach might be to wander up the dom tree and create a path to the element, which you can save and use it later as a selector again, although that might not be bulletproof, but maybe its a point where you can start off.
Edit: Updated the Answer with your suggestion in the comment, now it returns the id if available
Just visit the example on JSBin And click the document twice.
but notice what gets highlighted..
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
if (node[0].id) return "#" + node[0].id;
while (node.length) {
var realNode = node[0],
name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
var sel;
$(document)
.click(function (e, a) {
if (!sel) {
sel = $("#comment-21702402")
.getPath();
alert("Path is: " + sel + ", hiding the Element -> Click again to highlight");
} else {
$(sel)
.css("background-color", "yellow");
}
});
One way to do this is to get all the information you can get on the element that was clicked.
So when you save it to the database you can save it as a text for example:
If the element you clicked on is: <div> I'm a div </div>
$(document).click(function(){
var tagName = $(this).prev().prop('tagName');
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( index, attr ) {
attributes[ attr.name ] = attr.value;
} );
}
var elText=$(this).html();
saveToDB(tagName,attributes,elText);
});
You can later find the element using the attributes you have or simply use
$(tagName+'['+attribute+'="'+value+'"]:contains("'+elText+'")')
I think this should help

Increase element ID by one after every click?

I am trying to clone multiple divs on my page by using the jQuery .clone() method. The problem is, as soon as a div is cloned, it needs to have a unique ID. The cloned ID has to be there too. I was thinking I could keep the old ID and then just add a number on, increasing as more div's are on the page.
Example: base ID = one, so div one would be id, then div two would be id-2, then div three would be id-3, etc.
Is this possible? My attempt at this is below:
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
$(target).clone().attr("id",id + $(id).size()).attr("class","drag").appendTo("body");
});
Each a tag looks like this:
One
Two
Then the cloned element looks like this:
<div class="drag base" style="background-color:blue" id="one"></div>
<div class="drag base" style="background-color:green" id="two"></div>
See this: http://jsfiddle.net/3tu7V/1/
$(function(){
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
var click = $(target).data("clicked") || 0;
$(target).data("clicked", ++click);
$(target).clone().attr("id",id + click).attr("class","drag").appendTo("body");
});
});
​
I think this does what you want according to your comment:
"Ah, is there any way for the element ID to be reset when the base ID is unique? Ex.) "If you clone div "one", it will produce "one-1", then "one-2", but if you then clone div "two", it will produce "two-3", not "two-1""
i think in ur case $(id).size() will always be = 2. (only the last one and its clone will have the same id)
why don't you use a global variable var clickNumber that you increment each time.
your code will be
var clickNumber = 0;
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
clickNumber ++;
$(target).clone().attr("id","id-" + clickNumber).attr("class","drag").appendTo("body");
});
See this live example
var increment = 2;
$('a').live('click', function() {
$(this).clone().attr('id','id-' + (increment++)).appendTo('body');
});​
Result:
Revised answer:
You can use the jQuery attribute starts with selector to keep a track of the clones, and their counts:
$("a").click(function() {
var targetId = $(this).attr("href").substring(1); // "one", "two"
var count = $("div[id^=" + targetId + "]").length; // initial value will be 1
$("#" + targetId).clone().attr("id", targetId + '-' + count).attr("class", "drag").appendTo("body");
});
Demo
You could do something like this:
$('a').addClass('link');
$('body').on('click', 'a', function() {
$(this).clone(true).attr('id', 'id-' + $('.link').length).appendTo('body');
});​
Demo: http://jsfiddle.net/Em8PE/1/

Categories