Adding text values to dynamically create text inputs - javascript

I am trying to build a dynamic form. I have the clone and masking down along with it submits and post to my database but now I am trying to take the value from the previous id #endtime_* and make it the value of the new dynamically created input field of #starttime_*. The ids start with 1. For Example: the first row is: then next is 2 and so on.
As a bonus maybe someone could also tell me how to make each created row alternate in color. odd rows blue and even rows white say.
Thanks so much in advance!
Here is the code thus far.
<script type="text/javascript">
function maskInput(){
$.mask.definitions['~'] = "[+-]";
$(".time").mask("99:99 aa");
$("input").blur(function() {
$("#info").html("Unmasked value: " + $(this).mask());
}).dblclick(function() {
$(this).unmask();
});
}
var clone;
function cloneRow(){
var rows=document.getElementById('TimeCard').getElementsByTagName('tr');
var index=rows.length-1;
clone=rows[index-0].cloneNode(true);
var inputs=clone.getElementsByTagName('input'), inp, i=0,n ;
while(inp=inputs[i++]){
inp.name=inp.name.replace(/\d/g,'')+(index+1);
}
var select=clone.getElementsByTagName('select'), sel, i=0,n ;
while(sel=select[i++]){
sel.name=sel.name.replace(/\d/g,'')+(index+1);
}
maskInput();
}
function addRow(){
var tbo=document.getElementById('TimeCard').getElementsByTagName('tbody')[0];
tbo.appendChild(clone);
cloneRow();
}
function checkDOM(){
var rows=document.getElementById('TimeCard').getElementsByTagName('tr');
for(var i=0;i<rows.length;i++){
alert(rows[i].getElementsByTagName('input')[0].name);
}
}
onload=cloneRow;
</script>

when youre creating your new inputs in cloneRow, after they're in the dom you can just take your names/index and work them then.
$('#starttime_'+index).attr('value',$('#endtime_'+index-1).attr('value'));
for your rows, you need to just give everyother one a different/extra class and then style it accordingly
.odd { background-color:#cfcfcf; }
then, in your cloneRow()
clone=rows[index-0].cloneNode(true);
if (index%2) $(clone).addClass("odd"); //added this line
var inputs=clone.getElementsByTagName('input'), inp, i=0,n ;

It's difficult to guess what you really want when you provided no HTML code, but I built something that should at least point you to the correct direction. I made it into a jsfiddle but I'll post it here as well. So assuming your HTML is something like this:
<div id="inputs">
<input class="endtime" id="endtime_123" type="text" value="endtime_123"/>
</div>
Then this JavaScript will create you new inputs whose starttime equals the endtime of the other input:
$(function() {
$('#inputs .endtime').each(function(index) {
var endtime = $(this).attr('id').substring(8);
$('#inputs').append("<input class='starttime' id='starttime_'"+endtime+"' value='starttime_"+endtime+"'/>");
});
});

Related

Using jQuery to insert tags into box?

What I’m looking to create is something like the Stack overflow tag insert. I want to be able to type the tag into the insert box and when I click the ‘Add’ button, it adds it to the box above. I also want it to push the new tag into the ‘SelectedTags’ array. If the user removes it from the box, it'll need to be removed from the array. I guess I would need to push into the array first then populate the box based on the arrays content? I’ve tried creating it in JSFiddle but can’t get it working. Can someone help using the JSFiddle example? http://jsfiddle.net/uVxXg/117/
I assume this is what make it look like a tag?
$("#tags").tagit({
availableTags: SelectedTags
});
This is how you do it:
$(document).ready(function() {
var sampleTags = [];
$('#tags').tagit({
availableTags: sampleTags,
afterTagRemoved: function(evt, ui) {
console.log(ui.tagLabel)
for(var i = 0; i < sampleTags.length; i++) {
if (sampleTags[i] == ui.tagLabel) {
sampleTags.splice(i, 1); //Here is the update
}
}
}
});
$('form').submit(function(e) {
var inp = $('#tagInput').val();
$('#tagInput').val('');
$('#tags').tagit('createTag', inp);
sampleTags.push(inp);
e.preventDefault();
console.log(sampleTags)
});
$("#array").click(function(e){
console.log("MyArray",sampleTags)
})
});
Try out the fiddle, and when you add something to the SelectedTags array you will then have the tags as "find wile type" in the tags input.

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

How to iterate over htmlCollection

I'm having some difficulty with this. In Backbone, I have a function like this:
functionOne: function(){
$('#myTExtbox-' + budgetLine.attr('id')).on('change keyup paste', function(){
that.mySecondFunction(this);
});
}
In this case, the this is a textbox, which is in a table, inside a div. Then:
mySecondFunction: function(tb){
var tbody = tb.parentElement.parentElement.parentElement.parentElement.parentElement;
//gets main parent, which is a tbody, inside a table, inside a div
}
I then want to iterate over tbody, to go through each row and find a textbox in a specific cell. The problem is that this code:
$.each(tbody, function(index, item){
cost = item;
var t= index;
});
Doesn't seem to allow me to get to any of the items. In this example, if I try to do something like:
item.getElementById('test');
I get an error:
TypeError: Object #<HTMLCollection> has no method 'getElementById'
Why can't I iterate over this object and access objects within?
Thanks
UPDATE
Here's a fiddle: http://jsfiddle.net/HX8RL/14/
Essentially, what should happen is this: When a text box changes, I want to iterate over all the rows in the tb's parent table and sum all the Tb values. Keeping in mind, all the tb's in the same cell position, as there could be other tb's in other places that I dont want to include.
There wont be any collection of TBody
try using children() instead
$.each(tbody.children('tr'), function(index, item){
cost = item;
var t= index;
});
Demo Fiddle
Iterate over all input elements directly to get values.
var tbody = tb.parentElement.parentElement.parentElement;
alert(tbody.id);
var input = $('#tbody').find('input');
alert(input);
console.log(input);
for (var i = 0; i < input.length; i++) {
alert(input[i].value);
alert(i);
}
See fiddle-http://jsfiddle.net/HX8RL/18/
I think there are a few things going wrong here. You know you can only have one ID per page? So you have to do document.getElementByid('test') instead.
Since you are also using jQuery you can use the find function, item.find('#test'). But I think this wouldn't solve you problem. Not sure what you want to achieve, maybe I can help you if you explain a bit more in detail what your problem is.
Also
tb.parentElement.parentElement.parentElement.parentElement.parentElement;
can be written as (in jQuery)
$(tb).parents('tbody');
I've setup a fiddle, maybe it can help you.
Code used in fiddle:
var myFuncs = (function() {
function funcA() {
$('input').on('keyup', function() {
funcB(this);
});
}
function funcB(myInput) {
var $table = $(myInput).parents('table');
$table.find('tr > td > input').each(function() {
var $input = $(this);
if($(myInput).attr('id') != $input.attr('id'))
$input.val("I'm called from another input");
});
}
return {
funcA : funcA
}
})();
myFuncs.funcA();

performing sortable using JavaScript

i have a situation where i need to achieve this, in a table having n rows. if i click on a row in a table and then click on another row. the content in row of first click should go to content in row of second click and then each row should be shifted by on step backward or forward. this can be taken equivalent to JQUERY sortable.
Example:
|1|2|3|4| if i click on 1 and 4 then it should be |2|3|4|1|
how to record two clicks, and the contents of my rows are div elements containing many input elements. I thought of this idea and is this a good way to achieve sortable or is there a still better way, i want to do it using java script.
thanks in advance.
my script fucntion goes like this. I really should have thought for a little longer. i used flags here, i got two questions more, can i do that with out flags?, is there a better way?
<script>
var flag=0;
var id1;
var id2;
function Myfunction(id)
{
if(flag==0)
{
id1=id;
flag=1;
}
else
{
id2=id;
var x=document.getElementById(id1).innerHTML;
var num1=parseInt(id1);
var num2=parseInt(id2);
for(var i=num1;i<num2;i++)
{
var j=i.toString();
var k=(i+1).toString();
document.getElementById(j).innerHTML=document.getElementById(k).innerHTML;
}
document.getElementById(id2).innerHTML=x;
flag=0;
}
}
</script>
I made up a little http://jsfiddle.net/zxKeg/. Works with jQuery only, no additional plugins needed. Hope this will help you!
JS Code:
$(document).ready(function() {
var $table = $('table');
var $toCopy = null;
$table.on('click', 'tr', function() {
if($toCopy === null || $toCopy[0] == this) {
$toCopy = $(this);
}
else {
$toCopy.remove();
$(this).after($toCopy);
$toCopy = null;
}
});
});

Categories

Resources