use variable part of ID with js - javascript

I have a list of 8 divs: #video1, #video2, ... with each the same javascript actions to run when clicked, but with other id's (for #video1: show #image1, #preview1, ...).
Instead of writing 8 times the same code but with other id's, can I do this more efficient? Is it possible to take the sixth caracter (the number) from each #videoX as a variable when clicked, and use
this in the code?

Inside your event handler, you can extract the number, e.g. with a regular expression [MDN]:
var id = element.id.match(/\d+$/)[0];
and then use it to create the IDs of the other elements:
var image_id = "image" + id,
preview_id = "preview" + id;
Another option would be to assign data- attributes to the elements and use them to store the numerical part of the ID.

Use a class name instead. This way it's independent of the IDs completely.
<div class="videoClick" id="...">...</div>
JS:
$('.videoClick').click(function() {
...
})

yes you can:
$("div[id*='video']").click(function() {
var numid = $(this).attr("id").replace("video", "");
alert(numid);
//...use your numid value
});
Check attribute contains selector.

Try this
var ids = [#video1, #video2, #video3, #video4, #video5, #video6, #video7, #video8];
$(ids.join(",")).click(function(){
var imageId = this.id.replace("video", "image");
var previewId = this.id.replace("video", "preview");
$("#"+imageId).show();
$("#"+previewId).show();
});

Related

Get the tagName element inside class

I want to get the element of a inside class and change it.
My HTML is:
<div class="alignleft">
« Older Entries
</div>
I want to change Older Entries to Previous.
My JavaScript code is:
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
oldentries.ainside.innerHTML = "Previous";
but that gives me undefined.
Once you use Document.querySelector() to get the elements with class '.alignleft' you can also do oldentries.querySelector('a'); to get the 'a' element within oldentries and then change the element.innerHTML:
var oldentries = document.querySelector('.alignleft'),
ainside = oldentries.querySelector('a');
ainside.innerHTML = 'Previous';
<div class="alignleft">
« Older Entries
</div>
You need to update the textContent property of the <a> element.
Working Example:
var linkElement = document.querySelector('.alignleft a');
linkElement.textContent = 'Previous';
<div class="alignleft">
<a>Older Entries</a>
</div>
You can look for your element using a signle call to querySelector by using a more precise selector : Directly use .alignLeft a instead of doing it twice.
This code works :
var entries = document.querySelector('.alignLeft a');
entries.innerHTML = "Previous"
Your code would render out to something like
document.querySelector('.alignleft').document.getElementsByTagName('a').innerHTML = "Previous";
Also, getElementsByTagName('a') would render an Array not an object which you can apply .innerHTML to.
var ainside = document.querySelector('.alignlef a'); // Select first occurance of a inside the first occurance of .alignleft in the document
ainside.innerHTML = "Previous";
document.getElementsByTagName returns a HTML Collection. So you need to iterate over it (in your case it would be the first entry).
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
for(i=0;i<ainside.length;i++) {
ainside[i].innerHTML = "Previous";
}

Get only word part of an id/name

I have a div element with lots of descendent's elements, all with ids in the form "word1", for a simple example: id="moviment1" or id="type1".
I need to get only the written part of these ids (moviment or type), in order to concatenate their names with a increment of 1 (id="moviment2" or id="type2").
$clone.find('*').each(function() {
var id = $(this).prop('id');
var num = parseInt( $(this).prop("id").match(/\d+/g), 10 ) +1;
$(this).prop('id', id+num);
});
The way it is, I always get ids like id="moviment12". I already tried:
var id = $(this).prop('id').replace(/\d+/g, '');
or
var id = $(this).prop('id').match(/\w+/);
But I always get errors like "cannot read property 'replace'/'match' of undefined". So, what am I doing wrong? Any other ideas? Thank you very much!
Ideally you should use a template. Traversing and modifying parsed elements makes your code slow and hard to maintain.
If you want to increment the number part of the IDs by 1 you can use the replace method callback function:
$clone.find('[id]').prop('id', function(_, id) {
// Assuming `id` is `test_25_segment`
return id.replace(/(\d+)/, function(num) {
// |
// --- is 25
return +num + 1;
// |
// --- parses the matching string into integer
});
});
Here is a demo using the above snippet.
Easiest way, you could just add those values as data-attr:
<div id="type1" data-id="1" data-text="type"></div>
So you can easily get them separated just using .data('id') and .data('text').
You may select the elements by this way:
var all = [].filter.call(document.querySelectorAll('[id*=type]'), function(el) {
return (/\btype\d+\b/).test(el.id);
});
and then you can change the ids using methods like replace()
Try this...
var onlyAlphabets = id.split(/(\d)/)[0];

jQuery selecting attribute value of multiple elements with name attribute

I have a form that has multiple input, select, textarea elements. With jQuery, How can I get the name attribute values of each element? I have tried the following but its not working:
var names = $('[name]');
names.each(function(){
console.log(names.attr('name'));
})
You need to use this within the each() to refer to the element within the current iteration. Your current code is attempting to get the name of a set of elements which is logically incorrect. Try this:
var names = $('[name]');
names.each(function(){
console.log($(this).attr('name'));
})
You are still using names within your each function. Try this:
var names = $('[name]');
names.each(function(index, name){
console.log($(name).attr('name'));
})
This should loop around all the required elements and output the name and value to the console.
$('input,select,textarea').each(function() {
var thisname = $(this).attr('name');
var thisval = $(this).val();
console.log('name = ' + thisname);
console.log('value = ' + thisval);
});
You can try this way too.
var $name = $("[name]");
$name.get().map(function(elem,index){
console.log($(elem).attr("name"));
});
Add a class to all the elements you wish to get the names of.
Then you get all the elements from that class and iterate them to get their names.
formElements = $('.form-element');
for(key in formElements) {
name = formElements[key].attr('name');
// do what you wish with the element's name
}
P.S. You may need to wrap formElements[key] in $(), have not tested it.
// Selects elements that have the 'name' attribute, with any value.
var htmlElements = $("[name]");
$.each(htmlElements, function(index, htmlElement){
// this function is called for each html element wich has attribute 'name'
var $element = $(htmlElement);
// Get name attribute for input, select, textarea only
if ($element.is("input") ||
$element.is("select") ||
$element.is("textarea")) {
console.log($element.attr("name"));
}
});
Give your input ID then call attr() method
$("#id").attr("name");

Renaming formelements in a particular range with jquery

I've multiple autogenerated forms on a page. They are named in a particular manner like:
form-0-weight, form-1-weight, form-2-weight etc.
<ul>
<li>
<input id="id_form-0-weight" type="text" name="form-0-weight">
<a class="deleteIngredient" href="">x</a>
</li>
<li>
....more forms
</li>
</ul>
The user can add and delete forms. If a form get's deleted, the remaining ones should be renamed to stay in order. e.g. "form-1-weight" gets deleted >> "form-2-weight" will be renamed to "form-1-weight".
The total number of forms is stored in a hidden field named TOTAL_FORMS.
I'm trying to achieve this with a simple for loop.
The problem is that all the forms after the deleted one get the same name.
e.g. If I delete form-2-weight, all the following forms get the name form-2-weight instead of 2, 3, 4 etc.
$(".deleteIngredient").click(function(e){
e.preventDefault();
var delete = $(this).closest('li');
name = delete.children('input').attr("name");
count = name.replace(prefix,'');
count = name.replace("-weight",'');
var formCount = parseInt($("#TOTAL_FORMS").val())-1;
delete.remove();
for (var i = parseInt(count); i<=formCount; i++){
var newName = "form-"+i+"-weight";
$("#id_form-"+(i+1)+"-weight").attr("name",newName);
}
});
I suppose it has something to do with how I select the elements inside the loop because when I use just the variable "i" instead of "newName" it works as expected.
The problem is you're not initializing i properly.
This happens because "count" doesn't contain a string that can be parsed into an integer under the conditions of parseInt, I suggest you look here:
w3Schools/parseInt
Note: If the first character cannot be converted to a number, parseInt() returns NaN.
When you assign a string to "count" you're actually inserting the string "form-i" into the variable.
What you should do is this:
count = name.replace(prefix,'');
count = count.replace("-weight",'');
You should also rename your "delete" variable to "form" or any other descriptive name, as delete is a reserved word in javascript and also an action so it doesn't really suit as a name for an object.
Don't forget to change the id attribute of the item so it'll fit the new name.
As a note, you should probably consider following through some tutorial on Javascript or jQuery, Tuts+ learn jQuery in 30 days is one i'd recommend.
My first impulse is just to solve this a different way.
Live Demo
var $ul = $('ul');
// Add a new ingredient to the end of the list
function addIngredient() {
var $currentIngredients = $ul.children();
var n = $currentIngredients.length;
var $ingredient = $('<li>', {
html: '<input type="text" /> x'
});
$ul.append($ingredient);
renameIngredientElements();
}
// Rename all ingredients according to their order
function renameIngredientElements() {
$ul.children().each(function (i, ingredient) {
var $ingredient = $(ingredient);
var $input = $ingredient.find('input');
var name = 'form-' + i + '-weight';
$input
.attr('id', 'id_' + name)
.attr('name', name);
});
}
// Delete an ingredient
function deleteIngredient($ingredient) {
$ingredient.remove();
renameIngredientElements();
}
// Bind events
$('.add-ingredient').on('click', addIngredient);
$ul.on('click', '.delete-ingredient', function (event) {
var $ingredient = $(event.currentTarget).closest('li');
deleteIngredient($ingredient);
event.preventDefault();
});
As to why your particular code is breaking, it looks like user2421955 just beat me to it.

Jquery changing ID of cloned element children not working

I am trying to clone an element and then change the id of one of its children:
var s = $('.RunWell').clone().wrap('<div>').parent().html();
s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
but it is not working, what am I doing wrong ??
how to change the ID of a child of a cloned element ?
you don't have to go to its html..just use the cloned jquery object.
try this
var s = $('.RunWell').clone().wrap('<div>');
s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
the line
var s = $('.RunWell').clone().wrap('<div>').parent().html();
assigns variable s with a string value. But you are assuming it to be a jquery object in the next line by performing a .find on it.
It should be
var $s = $('.RunWell').clone().wrap('<div>').parent();
$s.find('#tag' + runNum).attr('id', 'tag'+ (++runNum));
//$s is used to denote it as a jquery object to provide more readability to code.

Categories

Resources