Commands in Javascript code are overwritten by the last one - javascript

I have stacked with my javascript code. In my app I am also using jQuery for faster writing some of the parts.
The thing is that after adding functionality to input files only the one added to the last is working. I found that maybe the reason is this same name of function with this same parameters. So to be sure I added to one my function which I want to use and to the other (I mean the first one) alert with simple text.
This is my code:
newRow.innerHTML = "<a href='#' class='editName'>"+ddList.ddElements[ddList.ddEl.id]+'</a>';
newRow.innerHTML += ' X:<input type="text" id="x'+ddList.ddEl.id+'" name="x'+ddList.ddEl.id+'" size=3 value=0>';
var xField = document.getElementById('x'+ddList.ddEl.id);
xField.relatedElement = newRow;
newRow.innerHTML += ' Y:<input type="text" id="y'+ddList.ddEl.id+'" name="y'+ddList.ddEl.id+'" size=3 value=0>';
var yField = document.getElementById('y'+ddList.ddEl.id);
yField.relatedElement = newRow;
$(xField).blur(function(){alert('Handler for X.blur() called.')});
$(yField).blur(function(){ddList.setObjectPosition(yField,obj,'y');});
if(RegExprText.test(ddList.ddEl.id))
{
newRow.innerHTML += '<br>Kolor:';
var element = document.createElement('input');
element.setAttribute('id', 'c'+ddList.ddEl.id);
element.setAttribute('name', 'c'+ddList.ddEl.id);
element.setAttribute('type', 'text');
element.setAttribute('class', 'color');
element.setAttribute('size', '6');
newRow.appendChild(element);
var myPicker = new jscolor.color(element, {});
$(element).blur(function(){ddList.setColor(element,obj);});
}
var links = newRow.getElementsByTagName('a');
var editLink = links[links.length-1];
editLink.relatedElement = newRow;
$(editLink).click(function(){ddList.deleteObject(obj,newRow);});
So when I have got only X and Y input fields then only Y is active. When I have got X, Y and colorPicker then only colorPicker works.
Interesting thing is that always is working last line of code - editLink.
And I have been trying to change
xField.relatedElement = newRow;
on
newRow.addChild(xField);
It doesn't work either.
Thanks for answers in advance.

First you do
xField.relatedElement = newRow;
And then you change
newRow.innerHTML
which will of course be reflected in the relatedElement.
If you want three different DOM elements, you have to make three different DOM elements, and not just one that you assign to three places and whose content you change three times.

Related

Adding code to div clears input val

I have a JS function that adds divs of the class PizzaBox to an empty div called PizzaBoxHolder. Why is it that whenever a new line is created, the user-inputted values in the inputs are replaced with the placeholders? Also, as a side note, should I even be using a place holder for a color input?
function newBox
{
numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
var pizzaBoxCode = "<div class = 'PizzaBox'>"
+ " <h6>Box number " + numOfBoxes + "</h6>"
+ " <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
+ " <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
+ "</div>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
PizzaBoxHolder.innerHTML += pizzaBoxCode;
}
Any help is appreciated. Thanks!
The way you're currently doing it, is resetting the entire innerHTML of your main PizzaBoxHolder element. By resetting the HTML, you're losing the current values. If you change the code to create an element, and then call .appendChild, it'll work as expected. The reason is, you're only appending a node to the current element.
var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder");
PizzaBoxHolder.appendChild(pizza);
Working fiddle.

How to set values in dynamically created text boxes

In my app I am creating some dynamic textboxes by clicking an add button. We can put some values and time also. Now my need is that when the page loads, I want a given number of textboxes to be created and populated by a set of values. I am able to create the text boxes onload but cannot set the values. Here I am giving a fiddle where I have created my functionality. How can I set some values dynamically? Here is the fiddle MYFIDDLE
And also I want timepicker function in those onload created boxes.
function getTextBoxAfterValiddation(val){
var str_array = ['jeet','chatterjee'];
var randomId = '\''+"#interviewName"+val+'\'';
var nameId = "interviewName"+val+"";
var allNames = str_array.replace(/((\[)|(\]))/g,"");
alert(randomId)
$(randomId).val(arr[val]);
return '<input class="txt1" name = "DynamicTextBox" type="text" id = "'+nameId+'"/>';
}
for(var i = 0; i < 4; i++){
var div = $("<div />");
div.html(getTextBoxAfterValiddation(i));
$("#TextBoxContainer").append(div);
}
When you dynamically generate each element increment a counter and use that value as the elements id. Then you can put html or values into each element using jquery. In the example below every time i click a button with id "addphys" i append a new div on. Later i can grab values from each div because i know the count and each new div id is phys1, phys2, phys3...
var numphys = 0;
$("#addphys").click(function(){
$("#test").append("<div class=\"addedphys\"><p id=\"phys"+ numphys + "\"><p><label>Physician Username:</label><input type=\"text\" class=\"inputbox\" id=\"physusername" + numphys + "\" name=\"pass\"></p><p><label>Physician Password:</label><input type=\"text\" class=\"inputbox\" id=\"physpassword" + numphys + "\" name=\"pass\"></p></p></div>");
numphys += 1;
});
Hope that helps.

How can I update the attributes of an HTML element inside a table cell?

I have a table which looks essentially like this
<!DOCTYPE html>
<html lang="en">
<body>
<table class="ui table" id="items">
<tbody>
<tr data-toggle="fieldset-entry">
<td><input id="items-0-quantity" name="items-0-quantity" type="text" value=""></td>
<td><input id="items-0-description" name="items-0-description" type="text" value=""></td>
</tr>
</body>
</html>
Using javascript, I'd like to have a button which adds a new row to the table, and I'd like the inputs in that new row to have id="items-1-xxx", and name="items-1-xxx, i.e. where there's a 0 in the original row I'd like a 1 in the new row.
I can make a new table row by cloning the old one, but I have not figured out how to modify the name and id attributes of the input.
Here's a sketch of what I've tried:
function cloneRow() {
var table = document.getElementById("items");
var original_row = table.rows[table.rows.length - 1];
var new_row = original_row.cloneNode(true);
// We have a new row and now we need to modify it as
// described in the question. The only way I've found
// is to grab the inner HTML:
var cell_contents = original_row.cells[0].innerHTML;
// Now we could do a bunch of string parsing and manipulations
// to increment the 0 to a 1 and stuff the modified HTML into
// new_row, but it seems there must be a better way.
// Finally insert the new row into the table.
original_row.parentNode.insertBefore(new_row, original_row.nextSibling);
}
What is the right way to update the input elements' id and name?
You could just build a new <td> and assign document.querySelectorAll('#items tr').length as the x in items-x-...:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length
, newitemQuantityText = 'items-' + itemcount + '-quantity'
, newitemDescriptionText = 'items-' + itemcount + '-description'
, newitem = document.createElement('tr')
, newitemQuantity = document.createElement('td')
, newitemDescription = document.createElement('td')
, newitemQuantityInput = document.createElement('input')
, newitemDescriptionInput = document.createElement('input');
newitemQuantityInput.id = newitemQuantityText;
newitemQuantityInput.name = newitemQuantityText;
newitemQuantity.appendChild(newitemQuantityInput);
newitemDescriptionInput.id = newitemDescriptionText;
newitemDescriptionInput.name = newitemDescriptionText;
newitemDescription.appendChild(newitemDescriptionInput);
newitem.appendChild(newitemQuantity);
newitem.appendChild(newitemDescription);
document.querySelector('#items').appendChild(newitem);
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items"></table>
However using good old innerHTML reads way better:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length;
items.innerHTML += '<tr><td>' +
'<input id="item-' + itemcount + '-quantity" name="item-' + itemcount + '-quantity">' +
'</td><td>' +
'<input id="item-' + itemcount + '-description" name="item-' + itemcount + '-description">' +
'</td></tr>';
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items">
</table>
You can separately reconstruct the node itself by using
createAttribute()
createElement()
Fiddle: http://jsfiddle.net/ztb9gq3d/1/
This is not the data oriented approach the question asks for, but a reasonably simple solution is
numRows = table.rows.length;
// Use a regexp so we can replace all instances of the number
// corresponding to what is currently the last table row.
var re = new RegExp((numRows - 1).toString(), "g")
for (var i = 0; i <= originalRow.cells.length - 1; i++) {
var originalHTML = originalRow.cells[i].innerHTML;
var newHTML = originalHTML.replace(re, numRows.toString());
newRow.cells[i].innerHTML = newHTML;
}
Obviously this only works if the number we replace doesn't exist elsewhere in the HTML string, so this is not a particularly good solution.
However, we could use a more complex regexp.
This solution does have the advantage that we don't need to hard-code anything except the parts we want to replace into the regexp.
Therefore, if the HTML in the table were to acquire additional parts in future development this solution will still work, up to the quality of the regexp as already mentioned.

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

Dynamically Load Div Elements and Assign IDs

I understand how to dynamically load HTML, I am having trouble understanding how I load it, assign, and keep track of IDs for elements inside the loaded div.
This is my main block
<div id="add-equip-container">
<div id="add-equip-content">
</div>
<button id="add-equipment">Add More Equipment</button>
<button id="submit-equipment">Submit Equipment</button>
</div>
Now, every time add-equipment is clicked, I want to load the following block into add-equip-content.
<div class="add-equip-form">
<input id="?" type="text" placeholder="Equipment Description..."/></br>
<input id="?" type="text" placeholder="Equipment Number"/></br>
<input id="?" type="text" placeholder="Other Stuff..."/></br>
</div>
Each block would be inserted beneath the previous one loaded. I have no idea how to assign and keep track of the various IDs that will be dished out during this operation. I would love a solution that does not involve jQuery. I am trying to lean vanilla JavaScript before I get into frameworks.
I am sure there may be a question or blog or something on this already, but I just don't know the best keywords to search for. Any time I use "Dynamically Load HTML" in the search keywords, all I get is AJAX Tutorial results.
Thanks in advance for any help!
One solution would be not actually load the HTML, but to create it via Javascript. This would be useful in your case as you are adding the same code to the page, only with different ID's. I would write a function like this:
var form_index = 0;
//elem is the element you are appending to.
function addForm(elem) {
//create the container
var form_container = document.createElement("div");
form_container.className = "add-equip-form";
//description input
var desc = document.createElement('input');
desc.id = "equip-desc-" + form_index;
desc.type = "text";
desc.placeholder = "Equipment Description...";
//Equipment number input
var num = document.createElement('input');
num.id = "equip-num-" + form_index;
num.type = "text";
num.placeholder = "Equipment Number";
//Other
var other = document.createElement('input');
other.id = "equip-other-" + form_index;
other.type = "text";
desc.placeholder = "Other Stuff...";
//append inputs
form_container.appendChild(desc);
form_container.appendChild(num);
form_container.appendChild(other);
//append form
elem.appendChild(form_container);
form_index++;
}
Then, to access your created ID's, all you need to know is the index of the containing div within your parent elem. See here for a javascript solution. Once you have the index, getting the form data is as easy as using your index to query based on ID's.
This should do it. You may or may not need to do the elements.push(content) if you don't need to refer back to these elements in an array. Could just iterate a counter instead.
var add_equip_content = document.getElementById('add-equip-content'),
add_equip_btn = document.getElementById('add-equipment'),
elements = [];
add_equip_btn.addEventListener('click', addEquipment, true);
function addEquipment(event){
var content = document.createElement('div'),
html = '';
content.className = 'add-equip-form';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Description..."/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Number"/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Other Stuff..."/></br>';
content.innerHTML = html;
add_equip_content.appendChild(content);
elements.push(content);
}

Categories

Resources