I'm new in javascript. i have a JS function that add and remove input fields. its working fine with my JS function. But I want when delete a field its Id looks like:
I have
no. 1
no. 2
no. 3
After Delete 2:
no. 1
no. 2
already i got this answer:
Reset JavaScript Counter after Deleting a field
But i want it with plain javascript. Can anyone help?
<script>
var count = 1;
function add_new(){
count++;
var div1 = document.createElement('div');
div1.id = count;
var delLink = '<button type="button" onclick="deleteLink('+count+')" class="btn btn-primary">Delete</button>';
div1.innerHTML = document.getElementById('add_link1').innerHTML+delLink;
document.getElementById('add_link').appendChild(div1);
document.getElementById("input_link1").id = count;
document.getElementById("input_link2").id = count;
document.getElementById("input_link3").id = count;
}
function deleteLink(eleId){
var ele = document.getElementById(eleId);
var par = document.getElementById('add_link');
par.removeChild(ele);
}
</script>
After deleting an element call the following function to reset Id of existing elements and also reduce the count.
function reset_counter(deletedCount) {
for (var impactedElementId = deletedCount + 1; impactedElementId < count; impactedElementId++) {
var currentElement = document.getElementById(impactedElementId);
currentElement.id = impactedElementId - 1;
var button = currentElement.firstChild;
button.innerHTML = 'Delete ' + currentElement.id;
button.setAttribute('onclick', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
The full code is available here: AddDeleteElements Sample Code
Related
my first ever question pretty sure I'm being a bit daft here, but am a beginner and would appreciate your help.
Im working on a webpage where there is a html table listing several columns of data.
When the page loads it runs a jquery script which counts the different types of "incidents" and plots them in another table which then another jquery script populates a graph.
I have a third script (javascript) which after a button is clicked, runs an if loop, which looks at the data in the first column and if it does not match the criteria then the row is deleted.
So far so good, the issue is that I want the script which populates the table for the graph to run again, but Im not sure how to call it from my if loop.
Ive put the two scripts below, basically I want to call the 1st script in the second script.
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')");
$("#result").html(NumFireAlarms.length + " Fire Alarm");
var firealarms = NumFireAlarms.length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = firealarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')");
$("#result").html(NumLockout.length + " Lockout Out of Office Hours");
var lockouts = NumLockout.length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = lockouts
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')");
$("#result").html(NumLockout.length + " Lockout Day Time");
var lockoutsDayTime = NumLockoutDayTime.length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = lockoutsDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')");
$("#result").html(NumSensitiveIncident.length + " Sensitive Incident");
var SensitiveIncident = NumSensitiveIncident.length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = SensitiveIncident
});
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var start_date = document.getElementById("start_date").value;
var end_date = document.getElementById("end_date").value;
var staff_type = document.getElementById("Job_Title").value;
var i;
var count = 0;
var table_length = document.getElementById("incidents").rows;
var TL = table_length.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
var date_column = document.getElementById("incidents").rows[i].cells.item(1).innerHTML;
var staff_colunm = document.getElementById("incidents").rows[i].cells.item(8).innerHTML;
if (category_column === incident_category)
{
alert("yay")
count++
}
else if (category_column !== incident_category)
{
alert("boo")
document.getElementById("incidents").deleteRow(i);
//CALL FIRST SCRIPT HERE??
}
}
}
I removed a few bits of code that did not seem to do anything, but I'm sure you can put them back. I think you might want something like this:
function updateTable(){
var elResult = document.getElementById("result");
var elNumIncidentType = document.getElementById("no_of_incident_type");
var firealarms: document.querySelectorAll("#incidents tr:contains('Fire Alarm')").length;
var lockouts: document.querySelectorAll("#incidents tr:contains('Lockout Out of Office Hours')").length;
var lockoutsDayTime: document.querySelectorAll("#incidents tr:contains('Lockout Day Time')").length;
var sensitiveIncident: document.querySelectorAll("#incidents tr:contains('Sensitive Incident')").length;
elResult.innerHTML = "";
elResult.innerHTML += "<div>" + firealarms + " Fire Alarm</div>";
elResult.innerHTML += "<div>" + lockouts + " Lockout Out of Office Hours</div>";
elResult.innerHTML += "<div>" + lockoutsDayTime + " Lockout Day Time</div>";
elResult.innerHTML += "<div>" + sensitiveIncident + " Sensitive Incident</div>";
elNumIncidentType.rows[1].cells[1].innerHTML = firealarms;
elNumIncidentType.rows[2].cells[1].innerHTML = lockouts;
elNumIncidentType.rows[3].cells[1].innerHTML = lockoutsDayTime;
elNumIncidentType.rows[4].cells[1].innerHTML = sensitiveIncident;
}
function filterForGraph() {
var elIncidents = document.getElementById("incidents");
var incident_category = document.getElementById("Incident_Category").value;
var table_length = document.getElementById("incidents").rows.length;
for (var i = table_length - 1; i >= 1; i--) {
var currentIncident = elIncidents.rows[i].cells;
var category_column = currentIncident.item(0).innerHTML;
if (category_column != incident_category) { elIncidents.deleteRow(i); }
}
updateTable();
}
$(function(){ updateTable(); });
Hi JonSG tried your code and it didnt work not sure why, but it gave me some ideas to work with and I think Ive cracked it
function Populate_Incident_No_Table() {
//previously function called updateTable
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')").length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = NumFireAlarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')").length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = NumLockout
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')").length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = NumLockoutDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')").length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = NumSensitiveIncident
});
}
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var i;
var TL = document.getElementById("incidents").rows.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
if (category_column !== incident_category)
{
document.getElementById("incidents").deleteRow(i);
}
}
Populate_Incident_No_Table();
drawGraph();
}
I think the issue was how I was trying to call the functions. So what I've done to achieve what I wanted (please excuse any bad terminology / phrasing).
First I tried to name the function $(function updateTable(){ this did not work when I then tried to call the function like this updateTable();
Second thing I tried was putting the updateTable() function "inside" a function and call that function. This has worked for me I dont know why.
Thanks for your help without it I would not have thought to try what I did
I am trying to make a script that will clone a div, cards in bootstrap 4, and change text in the div. I want this to happen a certain number of times., depending on the variable. However, when I use the script below I'm getting 8 cards (7 clones), instead of the 3 clones that it is supposed to be making. Does anyone know what is happening here?
$(document).ready(function(){
var cards = 3;
var id = "";
var newClass = "";
var i;
for(i = 0; i < cards; i++) {
id = id + "1";
newClass = newClass + "1"
$(".listings").clone().addClass(newClass).appendTo("body");
$("."+newClass).attr("id",id);
$("#" + id + " " + "h1").text("$5000");
}
});
change
.addClass(newClass)
to
.prop("class",newClass)
I'm trying to add inputs iteratively, and be able to run a calculation independently on each, but can not seem to apply the closure principles. The calculation function is only working on the last item added. I've tried using a for loop within as well as around the main function (addIt()) but it only seems to make things worse...
Here's the basic html:
<button class="btn btn-default btn-block" onClick="addIt('Item'+count)">Add One</button>
<form>
<div id="itemForm"></div>
<form>
And here is my overly complex and inelegant js (by the way, I'm open to better ways of doing this, so please don't hesitate to jump all over this):
count = 0;
addIt = function(p) {
count++;
var itFrm = document.getElementById("itemForm");
var itDiv = document.createElement("div");
var children = itFrm.children.length + 1
itDiv.setAttribute("id", "itemDiv")
itDiv.appendChild(document.createTextNode(p));
itFrm.appendChild(itDiv);
var remove = document.createElement("a");
var linkText = document.createTextNode("Remove It");
remove.setAttribute("href", "#");
remove.setAttribute("onClick", "removeIt()");
remove.appendChild(linkText);
var brk = document.createElement("br");
var num = document.createElement("input");
num.setAttribute("id", "numInput"+count);
num.setAttribute("type", "number");
num.oninput = function () {
var numInput = document.getElementById('numInput'+count).value ;
var divisor = 10;
var result = document.getElementById('result'+count);
var myResult = (Number(numInput) / Number(divisor));
result.value = myResult;
};
num.setAttribute("placeholder", "Set number...");
var clc = document.createElement("input");
clc.setAttribute("id", "result"+count);
clc.setAttribute("readonly", "readonly");
clc.setAttribute("placeholder", "After Calculation...");
var hr = document.createElement("hr");
itDiv.appendChild(remove);
itDiv.appendChild(num);
itDiv.insertBefore(brk, num);
itDiv.appendChild(clc);
itDiv.appendChild(hr);
};
function removeIt(elem) {
var elem = document.getElementById('itemDiv');
elem.parentNode.removeChild(elem);
return false;
};
I tried to setup a jsfiddle here but for some reason the removeIt function doesn't work there, although it's working locally for me, but only removes the oldest iteration. Any thoughts on how I've botched that are welcomed and appreciated as well.
var countString = count.toString();
num.oninput = function() {
var numInput = document.getElementById('numInput' + countString).value;
var divisor = 10;
var result = document.getElementById('result' + countString);
var myResult = (Number(numInput) / Number(divisor));
result.value = myResult; };
It was a scoping issue with count. Its basically a global variable so the closure will look for it. Use a local variable that gets re declared on each button press to fix it.
I have an age value which I'm using as a condition to enter an IF statement. The IF statement populates random values in to a field (this is a childs math game). After the fields are populated the user can enter their answers and then check them using a 'Check Answers' button. Once the 'Check Answers' block is run the IF statement gets ran again(!), which causes the math problems to change - new random values are created.
How can I prevent the IF statement from running after the page has already loaded; causing the values to change each time the 'Check Answers' button is clicked?
Here is is the relevant javascript:
$(document).ready(function () {
var getAge = localStorage.getItem('setAge');
var userResponse = new Array();
var answer = new Array();
if (getAge >= 1 && getAge <= 7) {
var operator = new Array('+', '-');
for (var counter = 0; counter <= 2; counter++) {
var index = Math.round(Math.random());
var1 = Math.floor((Math.random() * 5) + 1);
var2 = Math.floor((Math.random() * 10) + 1);
// these add the values to the mathQuestions.aspx
$('#a' + counter).text(var1);
$('#b' + counter).text(operator[index]);
$('#c' + counter).text(var2);
answer[counter] = eval(var1 + operator[index] + var2);
}
// this stores the users answers in userResponse[]
for (var counter = 0; counter <= 2; counter++) {
$('#d' + counter).change(function () {
for (var counter = 0; counter <= 2; counter++) {
userResponse[counter] = $('#d' + counter).val();
// window.alert("userResponse = " + userResponse[counter]);
}
});
}
// Button3 = 'Check Answers'
$('#Button3').click(function () {
for (var counter = 0; counter <= 2; counter++) {
window.alert('userResponse after checking the answers = ' + userResponse[counter]);
if (answer[counter] != userResponse[counter]) {
$('#span' + counter).val(answer[counter]);
}
}
});
});
I'm still learning all of this so I could have others errors that are contributing to my problem. To my knowledge the root problem is caused by the IF statement running again. Also, in case it's relevant I'm using Visual Studio Express 2012 for Web using some ASP controls (table, buttons, input, etc).
My guess is that the issue is not within the code you've posted, but within your HTML; Based on the code you've posted does contain a click-event, but this could never cause the 'randomize'-part to be ran again.
Could it be that your HTML looks like:
<form>
<button>Check answers</button>
</form>
or
<form>
<input type="submit" value="Check answers">
</form>
Having a button or submit inside a form-attribute results in a 'submit-action' when you hit the button. The result is that you first see the alert-message from the click-event. Next the page is reloaded and the whole document.ready() script will be executed again.
A simple solution could be:
$('#Button3').click(function (event) {
event.preventDefault()
/* ... */
}
This stops the form from submitting.
http://api.jquery.com/event.preventdefault/
I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/