Get value of all dynamically created hidden fields with class? - javascript

I would like to get the values of dynamically created hidden fields with a class reference.
Example of created hidden field
<input class="SelectedClaimants" id="CodesList_2__Claimant" name="CodesList[2].Claimant" type="hidden" value="Jason Statham">
This is something along the lines of what i have tried.
$('.listSelected').on('DOMSubtreeModified', function (event) {
$(".SelectedClaimants").find('input[type=hidden]').each(function () {
var testC += $(this).val();
});
});
I was aiming to have them create into an array object, but at the moment i am happy just to get the values out into a concatenated string.

Try this (the result is logged to the console). It's based onn Tushar's answer, but the selector was wrong.
$('input[type="hidden"].SelectedClaimants').map(function () {
return $(this).val();
}).get().join(',')

You can use .querySelectorAll(), spread element, for..of loop. Note, id, e.g., CodesList_2__Claimant should be unique in document.
var testC = [];
for (let el of [...document.querySelectorAll("input[type='hidden'].SelectedClaimants")]) {
testC.push(el.value)
}

Related

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 form input into an array not working

I'm working on a game and there is a form input where the user enters the number of characters. Once this happens more inputs appear for each character's name. My problem right now is reading those names into an array.
When the new inputs are created also a new button called nameButton is created and that is my issue, when I attempt to click that nothing happens when the values should be stored in an array. I put a prompt at the end of the function just to check and that does not even get called.
If you all have any suggestions please let me know here is the jsFiddle
function nameRecording(names,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=names; i++)
{ var nearTr=$this.closest('tr');
addRows=addRows+'<td>Name one:</td><td><form><input type="text" name="charcItem" class = "newR"/></form></td>';
}
addRows=addRows+'<td><div class="button" id="nameButton"> Add! </div></td></tr>';
nearTr.after(addRows);
};
$('#nameButton').click(function(){
names=$(".newR").map(function(){
return $(this).val();
});
prompt(names);
});
And there are some of my functions.
Try this way:
$(".form").on('click', '#nameButton', function () {
names = $(".newR").map(function () {
return this.value;
}).get();
prompt(names);
});
You can use event delegation using on for dynamic elements
You need to do a .get() on .map() result to convert the collection object into array.
Demo

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

Hide if html is the same

I'm using Feedburner to show feeds. sometimes the feeds have the same title. In situations where this is the case I would like to show only the first title and hide all the other titles with the same text. I tried this: JsFiddle
No luck. I can refer to them as 'a' but I don't understand how to distinguish them from one another.
Try starting with all links showing and this javascript:
$(function() {
var $feeds = $(".feedburnerFeedBlock li a");
$feeds.each(function(i) {
var $that = $(this);
$feeds.each(function(j) {
var $this = $(this);
if (j <= i) {
return true;//continue
};
if ($this.text() == $that.text()) {
$this.hide();
}
});
});
});
DEMO
Instead of using the filter function you could use an object to collect all the feed titles with their jQuery elements. The object will behave just like a HashMap in Java since objects can't contain duplicate keys - so duplicate feed titles are eliminated automatically.
var unique = { };
// Reverse elements to keep first occurence of feed title (and not the last one)
$($(".feedburnerFeedBlock li").get().reverse()).each(function(){
// Use feed title as key and jQuery element as value
unique[$(this).find("a").text()] = $(this);
}).hide();
// Show all unique elements
for (title in unique) {
unique[title].show();
}
JSFiddle: http://jsfiddle.net/Aletheios/9GKBH/1/
Besides, your code doesn't work because of several reasons. Amongst others jQuery's .html() function only returns the HTML string of the first element in the set (see documentation).

Categories

Resources