jQuery selecting attribute value of multiple elements with name attribute - javascript

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");

Related

Get innerHTML of class elements

I am using the function getElementsByClassName to get an array of elements and then use .innerHTML but it returns me the following text:
HTML
<input class="form-control input-block" value="Algorithms to live by" type="text">
JAVASCRIPT
function save_book(event){
var id = event.target.id;
var book = document.getElementsByClassName(id);
console.log(book[0].innerHTML)
}
and I only want the value. When I display the array of elements I find the .innerHTML returns the value but I get this.
Thanks!
With the given function, you need to grab the captured elements child element (the input), not its innerHTML, and with that you then get is value using e.g. book[0].firstChild.value
function save_book(event){
var id = event.target.id;
var book = document.getElementsByClassName(id);
console.log(book[0].firstChild.value)
}
Use dot notation to extract the value attribute:
function save_book(event){
var id = event.target.id;
var book = document.getElementsByClassName(id)[0];
var bookValue = book.value;
console.log(bookValue)
}
You should try this -
var dom = document.getElementsByClassName("input-block")[0].value;
console.log(dom); //Algorithms to live by

Scan for all data attributes with the same naming and insert value - jQuery

Let's say I have multiple data-foo="value" on a page and a var ID = "12". How can I target all instances of that data attribute foo on the page and add that ID to the end of it, so it becomes data-foo="value12".
The result with a templating engine would be something like data-foo="value{ID}", but I am not using one, just pure JS or jQuery.
The value of data-foo-"value" is different throughout the page.
In according to MilindAnantwar's answer.
you can using $('*[data-foo]') selector to select all elements with attribute data-foo, like this:
var ID = "12";
$('*[data-foo]').attr( "data-foo", function( i, val ) {
return val + ID;
});
See Jsfiddle (inspect elements and see html code)
You can target them using attribute equals selector and then modify their values in callback function of .attr() method:
var ID = "12";
$([data-foo="value"]).attr( "data-foo", function( i, val ) {
return val + ID;
});

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.

use variable part of ID with js

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();
});

jQuery Selecting Elements That Have Class A or B or C

I working on something where I need two functions.
1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.
['foo-a','foo-b','foo-d']
2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.
Does this element have class foo-a, foo-b or foo-d?
For the first part, I'd use map and get:
var activeGroups = $('#parent .active').map(function() {
return this.id;
}).get();
This gives you an array of id values (say, ['foo-a', 'foo-d']). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector) using join:
var activeSelector = '.' + activeGroups.join(', .');
This makes a valid jQuery selector string, e.g. '.foo-a, .foo-d'. You can then use this selector to find the elements you want using find:
var activeEls = $('#secondParent').find(activeSelector);
You can then do whatever you need to with activeEls.
var active = $("#foo").find(".active").map(function() {
return this.id;
}).get();
$("#anotherParent *").each(function() {
var that = this;
var classes = $(this).attr("class");
if(classes.indexOf(" ") !== -1) {
classes = classes.split(" ");
} else {
classes = [ classes ];
}
$.each(classes, function(i, val) {
if($.inArray(val, active)) {
// this element has one of 'em, do something with it
$(that).hide();
}
});
});
There's always .is('.foo-a, .foo-b, .foo-d'). Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint).

Categories

Resources