Move array of DOM elements to placeholders in page - javascript

I have a design received on my page with a set of placeholders such as:
<span id="ApplicationDate_" class="removeMe"></span>
Plus other many elements as well inside that html. These spans should be replaced by real inputs coming from another area on the page, such inputs look like:
<input type="text" id="ApplicationDate_48596977"/>
So basically what I need to do, is to get all input elements in an array, and then for each element, get its ID up to "_", and search for the span that equals that value, and replace it with this element, then remove all spans with class=removeMe, but I can't achieve it in code, below is what I have reached:
$(document).ready(function () {
var coll = $("input");
coll.each(function () {
var id = this.id; //getting the id here
var substringId = id.substring(0, id.indexOf('_') + 1); //getting the span id
this.appendTo("#" + substringId); //having problems here..
});
$(".removeMe").each(function () {
this.remove();
});
});
it tells me this.appendTo is not a function, any help or hint is much appreciated.

TL;DR - Just use:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});
Here's why:
this is a DOM element, but .appendTo() is a jQuery method. You probably just need to wrap this in a call to jQuery:
$(this).appendTo("#" + substringId);
That would place the <input> element inside the <span> like this:
<span id="ApplicationDate_" class="removeMe">
<input type="text" id="ApplicationDate_48596977"/>
</span>
But, then you call:
$(".removeMe").each(function () {
this.remove();
});
First, you would have the same problem as above - this is a DOM element, but .remove() is a jQuery method. Second, it would be better to just call $(".removeMe").remove() - wrapping it in a .each() is redundant. Third, that would remove the span, and the input along with it. That's not what you are trying to do is it?
If you want to replace the span with the input, use .replaceWith():
var coll = $("input");
coll.each(function () {
var substringId = this.id.substring(0, id.indexOf('_') + 1);
$("#" + substringId).replaceWith(this);
});
It seems like the whole thing could be rewritten, taking advantage of the attribute starts with selector, as:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});

Related

jquery - get the id of the closest element?

This is my code which is used to edit an input when clicked on it and then save in the db.
$(document).ready(function() {
$('.editable').on('click', function() {
var that = $(this);
if (that.find('input').length > 0) {
return;
}
var currentText = that.text();
var $input = $('<input>').val(currentText);
$(this).append($input);
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if ($input.val()) {
that.text($input.val());
var div_id = $(this).closest('#commentbox').attr('id');
div_id = div_id.replace('comment-', '');
alert(div_id);
$.post( "updateComment.php", {id: div_id,message: $input.val()})
}
that.find('input').remove();
}
});
});
});
Var div_id is not retrieving it at all.
And I want to retrieve only the number from the id from this however it does not work. I've been trying several solutions and this last one isn't working either
<div id="comments">
<div class="commentbox" id="comment-90">...</div>
<div class="commentbox" id="comment-91">...</div>
</div>
This part of code is basically a problem:
var div_id = $(this).closest('#commentbox').attr('id');
Firstly, you are trying to get closest element from document as this points to document in that part of your code (you meant probably event.target instead).
Secondly, you are trying to find the closest element with id == 'commentbox', as this is what #<selector> means. You should use some other attribute for that purpose - probably best would be some class selector and then use the .attr('id') on it.

For Loop to Programmatically hide elements

I am currently trying to programmatically hide div elements on a page using an Array and loop in jQuery, but it doesn't seem to work.
I have done alerts and console.log to confirm the array is firing and the loop is working through the items, but it's the .hide() method that seems to be giving issue. Any help would be appreciated.
Thanks
$(document).ready(function(){
var divsToHide = ["fin_0", "fin_1", "fin_2", "fin_3", "fin_4", "fin_5",
"fin_6", "fin_7", "fin_8", "fin_9", "fin_10", "fin_10-1", "fin_10-2", "fin_10-3",
"fin_10-4", "fin_10-5", "fin_10-6", "fin_10-7", "fin_10-8", "fin_10-9", "fin_20",
"fin_21", "fin_22", "fin_23"];
$.each(divsToHide, function(index, value)
{
var currentDiv = "div#" + value;
var stringCurrent = currentDiv.toString();
var currentHide = $(' stringCurrent ');
console.log(currentDiv);
currentHide.hide();
});
});
You should probably use:
var currentHide = $(stringCurrent);
Your code
var currentHide = $(' stringCurrent ');
has no reference to stringCurrent variable, it just try to find <stringCurrent> element.
Even better, you should use
$.each(divsToHide, function(index, value)
{
$("#" + value).hide()
});
since an element id should be unique to the document
You need to remove the ' around stringCurrent. Otherwise your string is not interpreted but jquery searches for ' stringCurrent '

jQuery id does not yield text representation

I’d like to add a button to certain text fields to allow for additional input methods. Since the button should be able to reference the text field it belongs to, I'm adding a parameter to the function call within the button’s onClick() handler, containing the ID of the text field.
At least, this is my plan. When I obtain the ID of the text field, and display it in an alert, it displays nicely. However, when I use the result of $(this).attr('id') as a function parameter, I'd expect a string to be given to the function (the id of the element). Instead some weird object is given.
How do I convert that object to a string? Or is there a conceptual flaw?
<form>
<input class="joeDateTime" type="text" name="n1" id="n1" value="2014-09-01 17:30:00">
</form>
<script>
function handleJoeDateTime(e)
{
alert('Edit '+e); // shows 'Edit [object HTMLInputElement]'
}
$(document).ready(function() {
$('.joeDateTime').each(function(){
var i = $(this).attr('id');
alert(i); // shows 'n1'
$('<button onclick="handleJoeDateTime(' + i + ');return false;">πŸ“…</button>').insertAfter($(this));
});
});
</script>
You are not passing i as a string value, you are passing it as an variable. In modern browsers the element's id are copied to properties of the window object(so you can access then as global variables).
So you need to enclose them using quotes to pass i as a string value
$('<button onclick="handleJoeDateTime(\'' + i + '\');return false;">πŸ“…</button>').insertAfter($(this));
Demo: Fiddle
Also Instead of using inlined event handlers, I would recommend using jQuery event handlres
$('.joeDateTime').each(function () {
var i = $(this).attr('id');
console.log(i); // shows 'n1'
$('<button />', {
text: 'πŸ“…',
click: function () {
handleJoeDateTime(i);
return false;
}
}).insertAfter(this);
});
Demo: Fiddle
Your problem lies here:
$('<button onclick="handleJoeDateTime(' + i + ');return false;">πŸ“…</button>')
where this should be
$('<button onclick=\"handleJoeDateTime(\"' + i + '\");return false;\">πŸ“…</button>')
When you're passing an element to jQuery ( $ ), it becomes a jquery object.
It had been made to handle id, class, elements, not html chunks.
What you want is inserting a piece of concatenated elements as an html node.
so first concatenate your elements then append it with the jQuery's after() method.
(or create/append it with vanilia js var btn = document.createElement("BUTTON");)
var Button = '<button class=\"AltBut\" id=\"' + i + '\">πŸ“…</button>';
$(this).after(Button);
or ( for compacity )
$(this).after('<button class=\"AltBut\" id=\"' + i + '\">πŸ“…</button>');
In this exemple, I'm adding an id to each enabled buttons where I store your variable i
Then add a click listener to those buttons, avoid inline js at all price, for maintainability's sacke.
$('.AltBut').on('click',function(){
var i = $(this).attr("id");
alert("i= "+i);
return false;
})
The whole demo is here: http://jsfiddle.net/x6x4v90y/1/

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

Renumbering numerically ordered div ID's when adding one in the middle with Javascript

I'm developing an application with javascript. What I need is to have divs with id's (1,2,3...) and be able to insert a div between, for example, 2 and 3, with jquery, and then have that be the new three, and three becomes four, four becomes five, etc. I've got the div insertion working, I just need to know how to reorder the divs. Any ideas?
After you inserted the new div, you can do this:
var i = 1;
$('div').each(function() {
$(this).attr('id', i++);
});
Replace $('div') by your own selector.
Remember also that, depending on which version of HTML you use, id's can't start with a number.
You can't start IDs with a numeric value, but regardless of that you'd do something like
// set a data value in the div you have just inserted into the dom and set a variable theID to the current ID you have just inserted.
$(this).data('inserted', true);
var theID = $(this).attr('id'); // this will be 3.
// now to update the other divs.
$('div').each(function() {
if($(this).attr('id') >= theID && !$(this).data('inserted')){
$(this).attr('id', $(this).attr('id') + 1);
}
});
// now set the data inserted to false for future updates
$('div#3').data('inserted', false);
$(function() {
reorder();
$('#click').click(function() {
$('<h2>hello world blah!</h2>').insertAfter('.content h2:eq(1)');
reorder();
});
});
function reorder() {
$('.content h2').each(function(i) {
$(this).attr('id', 'order_'+(i+1));
// alert( parseInt(this.id.split('_')[1]) ); // this is the id #
});
};
I'm pretty sure that you get things back in DOM order from jQuery selectors, so couldn't you just find the parent element, select the child <div> elements, and then .each() through the list?

Categories

Resources