Change names of appended table row fields jQuery - javascript

I have a table in an html form containing a table that a row is added to every time a button is clicked. When each row is added, I want the name and id of each field in the new row (there are four) to be updated from "Id.0" in the first row to "Id.1" in the second row and then "Id.2" in the third, etc. I can accomplish this with the id no problem using
var next=$("#QualificationRequirements tr:last").clone();
fixIds(next,nexdex);
nexdex++;
$("#QualificationRequirements").append(next);
function fixIds(element, counter) {
$(element).find("[id]").add(element).each(function() {
this.id = this.id.replace(/\d+$/, "")+counter;
}
}
However I have found that the same logic does not apply to the name attribute, and
$(element).find("[name]").add(element).each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
causes an error that says I can't call "replace" on a null object, so it appears the name attribute is not being found.
Can anyone see what I'm doing wrong? Thanks!

The issue comes from this part of your statement: add(element)
See, element refers to the complete row, and rows don't have a name attribute. You just want to act upon the inputs inside the row that have the name attribute so you should remove that part from your code:
$(element).find("[name]").each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});

There is no name property on an HTML element. Instead you'll need to access it as an attribute:
this.setAttribute('name', this.getAttribute('name').replace(/\d+$/, "")+counter);
Working Demo

use $(this).attr('name'); to get and set the name attribute.
The full line:
$(this).attr('name',$( this).attr('name').replace(/\d+$/, "")+counter);

Try this
$(element).find("[name]").add(element).each(function() {
this.attr("name",this.attr('name').replace(/\d+$/, "")+counter) ;
});

Related

How to display results in input field from td tag

my title may be hard to understand but i didnt know how to ask this question so let me explain. Here is my script
$(this).parent("td").siblings("td:last").text(intTotal);
This script display results inside td tag <td></td>.. How do i make the intTotal to display inside input field <input id="total"> please note i have many rows and i tried using $("#total").val(intTotal) but this can only work if i had 1 row.
Here is the rest of the script
var strClass = $(this).prop("class");
var intTotal = 1;
$.each($("input:text." + strClass), function () {
var intInputValue = parseInt($(this).val());
if (!isNaN(intInputValue))
{
intTotal = intTotal * intInputValue;
}
});
$(this).parent("td").siblings("td:last").text(intTotal);
});
Thank You
Your code below sends the results to the last element of the td.
$(this).parent("td").siblings("td:last").text(intTotal);
To assign a value inside an element using jQuery, you must first select it and then edit its content using the html(), text(), val()... functions.
In your case, the code below will update the value of the input with the #total id.
$("#total").val(intTotal);

Using an If statement on .map object in Jquery

Edited for clarity. (thanks)
On my page, there are dynamically created divs that contain input elements(they clone the original). Each div refers to a unique form, but the ID of the input elements are not unique in each div(this may be a problem).
The code below successfully searches my doc for all of the divs that have been created(Their ID is medical-report(random number), gathers their input elements and then outputs each string in the array separated by a comma.
var $inputs= $("div[id^='medical-report']").find("input").clone();
$("#multi").append(($inputs).map(function() {
return $(this).val();
})
.get()
.join(", "));
}
What I want to do instead, is traverse the array (not sure if I have truly created one), and then looks at the ID of each input element and append unique paragraph text for each to an area in my page. It would basically summarize the contents of each div.
(search for inputs, and clone them)
var $inputs= $("div[id^='medical-report']").find("input").clone();
Then
pseudo code:
for each div=
If the ID is "nameofdoc" add paragraph The name of the doctor is "nameofdoc.val"
If the ID is "datereceived" add paragraph the document was received on "datereceived.val"
and so on.
Just to restate, a problem here may be that "nameofdoc" and "datereceived" are not unique ID's. The container divs however are unique.
var $inputs= $("div[id^='medical-report']").find("input").clone();
$("#multi").append(($inputs).map(function(index) {
return $(this).val();
.get();
if ($(this).is("#MEDRIN")) {
$("p").text("The medical was received on" +index);
}
})
I have read up on .each and.contents in the jquery API but I am really unsure of what direction to go in. Fiddle is below.
http://jsfiddle.net/gdoax9q2/7/
There are a number of issues here. I will list the steps that I would take to solve this problem.
Rename the function from "sayHi" to a name that describes what this function does. "generateReportSummaries" seems appropriate.
I removed all of the innerHTML stuff because I had no idea what it was doing.
Use jQuery to grab a collection of all the forms we want to create summaries for (I gave the forms each a "report-form" class to make this easier.
Create a function that will take a a form element and return a formatted element that we can append to the document. I called my function "getReportElement".
For each form element, call getReportElement and append the result to #mutli.
Implement getReportFormat to map the values for all the form's inputs - include a conditional for when input's name attribute is 'MEDRIN'. Join the values array and append it to the new element that the function returns.
function generateReportSummaries () {
/* Get a jQuery wrapped collection of all .report-form elements. */
var $forms = $('.report-form');
/* Call getReportElement for each .report-from. */
$forms.each(function () {
$('#multi').append(getReportElement($(this)));
});
}
function getReportElement ($form) {
/* Create a new paragraph element to contain our text. */
var $paragraph = $('<p></p>');
/* Get an array of the form's input values. */
/* If input is [name="MEDRIN"], add prefix text to array value. */
var mapped_values = $form.find('input').map(function () {
if ($(this).is('[name="MEDRIN"]')) {
return 'The medical was received on ' + $(this).val();
} else {
return $(this).val();
}
}).get();
/* Join our values array and set it as our paragraph element's text. */
$paragraph.text(mapped_values.join(', '));
/* Return our (jQuery-wrapped) paragraph element. */
return $paragraph;
}
I removed the input ids and replaced them with name attributes because ids should not be duplicated. Also, the datepicker was causing issues for the cloned forms, so I changed things a little to make everything work. You can see my result at: http://jsfiddle.net/76484/qLeg5wm9/

Changing name of all classes in html document with javascript

I have a List that shows Products. When I click on one, I need to change the class of the <li> so as to show that it is clicked. I got this working... But what I can't do is clear the other <li> that have been previously clicked so as to show it is not selected anymore.
This is part of my code, what am I doing wrong? btw, my logic here is to first refresh all classes to notselected, and then just update the list with my product id number. this can be seen on the second line of code.
I'm new to javascript, and did my research, and this is what I got.
function showdetails(ProductID) {
document.getElementsByName("ProductList").className = "notselected";
$("#"+ProductID).attr('class','selected');
Are you trying to do this?
function showdetails(ProductID) {
$("[name=ProductList].selected").removeClass('selected');
$("#"+ProductID).addClass('selected');
}
I think you need to iterate across all elements returned in document.getElementsByName("ProductList") and change className to each element individually.
var productLists = document.getElementsByName('ProductList');
for (i = 0; i < productLists.length; i++) {
productLists[i].className = 'notselected'
}

Javascript - removeChild removes a whole cell of a table

I have table where I can add new rows with input fields. Also there's a possibility to remove an added input field. Deleting a complete row works, but there's a problem to delete single input fields inside a cell.
Here's the code:
cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;
var feld = document.createElement("input");
feld.setAttribute("name","avz_keywords" + avz_array + "[]");
feld.setAttribute("onblur","");
feld.setAttribute("type","text");
feld.setAttribute("size","30");
cell1[1].appendChild(feld);
var remove = document.createElement("a");
remove.setAttribute("href","#");
remove.setAttribute("onclick","this.parentNode.parentNode.removeChild(this.parentNode);");
remove.innerHTML = " X";
cell1[1].appendChild(remove);
var br = document.createElement("br");
cell1[1].appendChild(br);
The problem is that the remove action completly deletes the whole cell, instead of the related input field. The strange thing, that this works on the first tier of the table without problems.
Do you see the error? Thanks for any suggestions!
Ok, you are appending the anchor element remove to cell1[1], which is a single table cell of the row with index par.rowIndex. So the parentNode to the anchor element is the cell. With this.parentNode.parentNode.removeChild(this.parentNode) you are removing the parentNode of the anchor, which is the cell.
EDIT: removed a sentence that might have been offensive ... sorry :-)
EDIT2: Possible solution:
this.previousSibling.parentNode.removeChild(this.previousSibling);
because this.previousSibling might be the input element
Since you are building your HTML with the DOM, you don't have to set attributes for events:
replace remove.setAttribute("onclick"... by something like:
remove.onclick = function(ev){
feld.parentNode.removeChild(feld);
}
feld and the onclick function are defined in the same scope, you have a closure here. It makes feld available inside the function.

How insert an input field in a table cell?

Sorry for the noob question: I want to create a table with input fields where the can add new ones, if they are needed. But I can'T figure out how add another input field inside a cell where another input field already exists.
My code is:
var par=obj.parentNode;
while(par.nodeName.toLowerCase()!='tr')
{ par=par.parentNode; }
// this gives me the index of the row.. works fine.
cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;
// this puts the content of the cells into the array "cell1"
var feld = cell1[1].createElement("input");
feld.setAttribute("name","avz_keywords" + avz_array + "[]");
feld.setAttribute("onblur","");
feld.setAttribute("type","text");
feld.setAttribute("size","30");
// Now I create a input element
// And now comes the problem:
cell1[1].appendChild(feld); // --> doesn't work
Has anyone a suggestion for me?
I got the idea to work without a table, theoratically that would work with my way. But that wouldn't be satisfying :/
If you look in a debugging console, you should see something like
TypeError: Object #<HTMLDivElement> has no method 'createElement'
Instead of creating the element from cell1[1], use document.createElement()
var feld = document.createElement("input");
You should use document.createElement("input"); instead of cell1[1].createElement("input");
As always (and as also stated in another answer here), the JavaScript console should be the first place to look for hints on what the problem is!
And wouldn't it actually be much easier if each table cell you want to add values to got a separate ID? Something containing perhaps the row index and the column index ... Then you could just select it directly.

Categories

Resources