Adding input fields and setting their ids dynamically - javascript

$(document).ready(function() {
function getData1() {
var innerhtml1 = $('.load1').html();
$('.main_div').append(innerhtml1);
}
getData1();
$(document).on('click', '.add_question', function() {
let lengthQstn = $('.main_div').children().length;
let questionHtml = $('.load1').html();
let appendQstn = questionHtml.replace(/0/g, lengthQstn).replace(/add_question/g, "remove_question").replace(/add question/g, "remove question");
$('.main_div').append(appendQstn);
})
$(document).on('click', '.add_option', function() {
var dataParent = $(this).attr('data-parent');
let lengthOpt = $("#option_" + dataParent).children().length;
lengthOpt++;
var dataParent = $(this).attr('data-parent');
let optionHtml = $('.load2').html();
let appendOpt = optionHtml.replace(/count/g, lengthOpt).replace(/0/g, dataParent);
$("#option_" + dataParent).append(appendOpt);
})
$(document).on('click', '.remove_question', function() {
var dataParent = $(this).attr('data-parent');
$("#question_" + dataParent).remove();
})
$(document).on('click', '.remove_option', function() {
var dataParent = $(this).attr('data-parent');
var dataIndex = $(this).attr('data-id');
$("#row_" + dataParent + '_' + dataIndex).remove();
})
})
.hide {
display: none;
}
.remove_option,
.remove_question {
background-color: rgb(204, 177, 177);
}
.add_question,
.add_option {
background-color: rgb(201, 233, 222);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<div class="container">
<center>
<h2>New Form</h2>
</center>
<div class="main_div">
</div>
</div>
<div class="load1 hide">
<div class="parent_div mb-5 mt-5" id="question_0">
<div class="div1">
<div class="row">
<div class="col-6">
<label id="question_0">Question_0</label>
<input type="text" name="question_0" id="question_0" class="form-control">
</div>
<div class="col-3">
<button id="add_question_0" class="form-control add_question mt-4" data-parent="0">add_question</button>
</div>
</div>
</div>
<div class="div2" id="option_0">
<div class="row" id="row_0_1">
<div class="col-6">
<label id="option_0_1">option_0_1</label>
<input type="text" name="option_0_1" id="option_0_1" class="form-control">
</div>
<div class="col-3">
<button id="add_option_0" class="form-control add_option mt-4" data-parent="0">add
option</button>
</div>
</div>
<div class="row" id="row_0_2">
<div class="col-6">
<label id="option_0_2">option_0_2</label>
<input type="text" name="option_0_2" id="option_0_2" class="form-control">
</div>
</div>
</div>
</div>
</div>
<div class="load2 hide">
<div class="row" id="row_0_count">
<div class="col-6 option_0_count">
<label id="option_0_count">option_0_count</label>
<input type="text" name="option_0_count" id="option_0_count" class="form-control">
</div>
<div class="col-3">
<button id="remove_option_count" class="form-control remove_option mt-4" data-parent="0" data-id="count">remove option</button>
</div>
</div>
</div>
I have made a page for dynamically appending input fields for new questions, as well as new options.
All are input fields only, I have to generate an index for the fields.
But, when I click on "add option" the options input fields are appending but the index is not being generated correctly; also I have to generate an index similarly for the buttons too. Please help with this part.
Also, I have to dynamically remove the added option fields too when clicked on "remove option" button, I have commented it as of now.

Related

How to disable a button if all of the inputs is empty in asp.net core

I'm trying to submit a form. I have a binding dropdown list and an input field. The dropdown list has three input fields. 0 = pending, 1 = accepted, and 2 = denied. I want to store data if the dropdown value is not 0/pending. If the dropdown is changed/ not pending or the comment input field have not empty, then the Save button enables. Otherwise, the save button is disabled.
function success() {
if (document.getElementById("textsend").value === "") {
document.getElementById('button').disabled = true;
} else {
document.getElementById('button').disabled = false;
}
}
<div class="row border-top pt-2">
<div class="col-md-4">
<span>Decision</span><span asp-validation-for="Heating.Status"></span>
<select asp-for="Heating.Status" asp-items="Html.GetEnumSelectList<ApplicationDecision>()" class="form-control">
<option></option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span>Comments</span><span></span>
<textarea class="form-control " id="textsend" onkeyup="success()" style="height:100px" maxlength="2000"></textarea>
</div>
</div>
<div class="row border-top p-2">
<div class="col">
<input type="submit" id="button" value="Save" class="btn btn-blueTwo float-right" disabled />
</div>
</div>
But I can't use the dropdown list to add these conditions. Couldn't you please help me?
Finally, I solved this problem.
<script>
$(document).ready(function () {
$('.save-btn').attr('disabled', true);
$('#CommentResponse').change(function () {
let cmtData = $("#CommentResponse").val();
if (cmtData !=null ) {
$('.save-btn').attr('disabled', false);
}
if(cmtData == "")
{
$('.save-btn').attr('disabled', true);
}
})
$('#StatusResponse').change(function () {
let statusData= $(this).val();
if (statusData != 0) {
$('.save-btn').attr('disabled', false);
}
else
{
$('.save-btn').attr('disabled', true);
}
})
});
</script>
<div class="row border-top pt-2">
<div class="col-md-4">
<span>Decision</span><span asp-validation-for="BurnOut.Status"></span>
<select asp-for="BurnOut.Status" id="StatusResponse" asp-items="Html.GetEnumSelectList<ApplicationDecision>()" class="form-control ">
<option></option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span>Comments</span><span asp-validation-for="BurnOut.Remarks"></span>
<textarea class="form-control " id="CommentResponse" asp-for="BurnOut.Remarks" style="height:100px" maxlength="2000"></textarea>
</div>
</div>
<div class="row border-top p-2">
<div class="col">
<input type="submit" value="Save" class="btn btn-blueTwo float-right save-btn" />
</div>
</div>

How to show data when do you click button

When I input data in text input and then click button "Save Task" data will show is list in bottom descend. Now i console.log I want to show data when after click button. I don't know how to get data show when after click button "Save Tasks" so I did console.log
app.html
<div class="form-group" *ngIf="saveTask">
<div class="form-row">
<div class="form-group col-md-12">
<label for="subjectTask" class="control-label">Subject Task</label>
<input formControlName="subjectTask" type="text" class="form-control" id="subjectTask"
placeholder="Subject Task">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="assignDev" class="control-label">Assign Dev</label>
<select formControlName="assignTasks" name="assignTasks" class="form-control" id="assignTasks">
<option value="">choose dev...</option>
<option *ngFor="let staff of Staff" [ngValue]="staff.fullName">
{{staff.firstName}} {{staff.lastName}}
</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="deadline" class="control-label">Deadline</label>
<input formControlName="deadlineDate" type="number" class="form-control" id="deadlineDate"
placeholder="Deadline">
</div>
</div>
<div class="form-row">
<div class="form-group mr-5">
<button type="button" class="btn btn-light btn-cancel">Cancel</button>
</div>
<div class="form-group">
<button type="button" class="btn btn-success" (click)="onTasksSubmit()">Save Tasks</button>
</div>
</div>
</div>
app.ts
onTasksSubmit() {
const subject = this.editTicket.controls.subjectTask.value
const assignTasks = this.editTicket.controls.assignTasks.value
const deadlineDate = this.editTicket.controls.deadlineDate.value
this.newTask = {
subject, assignTasks, deadlineDate
}
this.depositTasks.push(this.newTask)
this.clearTask()
console.log(this.newTask);
// this.saveTask = false;
}
clearTask() {
this.editTicket.patchValue({
subjectTask: '',
assignTasks: '',
deadlineDate: ''
})
}
saveTasks() {
if (this.depositTasks.length != 0) {
console.log('do');
for (let i = 0; this.depositTasks.length > i; i++) {
console.log(this.depositTasks);
this.ticketService.setAddTasks(
this.id,
this.depositTasks[i]
)
}
}
}
<p *ngFor="let task of depositTasks">{{task?.subject}}</p>
try to use the depositTasks array in template as shown above.

Javascript concatenate multiple string variables and display in span

I have a simple page that makes a flyer. I have the data displaying and am stuck with taking three of the variables and displaying them in a span for tear-off. Here's what I have so far. I've tried a few different approaches trying to get the Title, Name, and Phone to print out in the div. I'm using the multi-event listener to trigger the function to place the data in the span using the getElementsByClassName handler. Any direction is much appreciated.
// JavaScript Document
// Fill Flyer text Areas
// Flyer Title
var inputBoxTitle = document.getElementById('title_input');
inputBoxTitle.onkeyup = function(){
document.getElementById('title').innerHTML = inputBoxTitle.value;
}
// Contact Name
var inputBoxConName = document.getElementById('con_name_input');
inputBoxConName.onkeyup = function(){
document.getElementById('con_name').innerHTML = inputBoxConName.value;
}
// Contact Email
var inputBoxEmail = document.getElementById('email_input');
inputBoxEmail.onkeyup = function(){
document.getElementById('email').innerHTML = inputBoxEmail.value;
}
// Contact Phone
var inputBoxPhone = document.getElementById('phone_input');
inputBoxPhone.onkeyup = function(){
document.getElementById('phone').innerHTML = inputBoxPhone.value;
}
// Animal Name
var inputAnimalName = document.getElementById('name_animal_input');
inputAnimalName.onkeyup = function(){
document.getElementById('animal_name').innerHTML = inputAnimalName.value;
}
// Lost/Found Date
var inputLostDate = document.getElementById('date_lost_input');
inputLostDate.onkeyup = function(){
document.getElementById('date_lost').innerHTML = inputLostDate.value;
}
// Lost or Found
var inputLostFound = document.getElementsByName('lost_input');
(function (){
for(var i = 0; i < inputLostFound.length; i++){
inputLostFound[i].onclick = function(){
document.getElementById('lost_found').innerText = this.value;
}
}
})();
// Microchipped Radio
var inputMicro = document.getElementsByName('micro_input');
(function (){
for(var i = 0; i < inputMicro.length; i++){
inputMicro[i].onclick = function(){
document.getElementById('micro').innerText = this.value;
}
}
})();
// Color
var inputColor = document.getElementById('color_input');
inputColor.onkeyup = function(){
document.getElementById('color').innerHTML = inputColor.value;
}
// Breed
var inputBreed = document.getElementById('breed_input');
inputBreed.onkeyup = function(){
document.getElementById('breed').innerHTML = inputBreed.value;
}
// Animal Sex
var inputSex = document.getElementsByName('sex_input');
(function (){
for(var i = 0; i < inputLostFound.length; i++){
inputSex[i].onclick = function(){
document.getElementById('sex').innerText = this.value;
}
}
})();
// Description
var inputDescription = document.getElementById('description_input');
inputDescription.onkeyup = function(){
document.getElementById('description').innerHTML = inputDescription.value;
}
// Tear Offs
var res = inputBoxTitle + "<br>" + inputBoxConName + "<br>" + inputBoxPhone;
$('inputBoxTitle, inputBoxConName, inputBoxPhone').onkeyup, function(){
document.getElementsByClassName('tear_off_data').innerHTML = document.write(res);
}
.main-row {
flex-wrap: nowrap;
word-break: break-all;
}
.column, .rotate {
border: 1px dashed;
-webkit-box-flex: 1;
flex: 1 1 0;
}
.rotate {
height: 270px;
white-space: nowrap;
width: 0;
}
.rotate > div {
-webkit-transform: translate(0px, 110px) rotate(-90deg);
transform: translate(0px, 110px) rotate(-90deg);
}
.rotate > div > span {
border-bottom: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.js" integrity="sha512-nxKp6INemMtUWHV+BToAOXm2ZV4+LCc/sw+4j2fyVJG088hHf7Rt/h8qCYT7bTsEtqkDCXo6sbtFlkro3Zo3HA==" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
</head>
<body>
<!---- Start Data Input for Flyer ---->
<div class="container" style="margin-bottom: 10px;">
<div class="jumbotron"><h1>San Antonio Pet Rescue</h1>
<p>locating lost and found/stray, dogs and cats</p>
</div>
<div class="row">
<div class="col-sm">Insert Your Title Here<input type="text" id="title_input" name="title_input" placeholder="Title"></div>
<div class="col-sm">Contact Name<input type="text" id="con_name_input" name="con_name_input" placeholder="Contact Name"></div>
<div class="col-sm">Contact Phone<input class="phone_us" type="tel" id="phone_input" name="phone_input" placeholder="xxx-xxx-xxxx"></div>
<div class="col-sm">Contact Email<input type="email" id="email_input" name="email_input" placeholder="Contact Email"></div>
</div>
<div class="row">
<div class="col-sm">Animal Name if Known<input type="text" id="name_animal_input" name="name_animal_input" placeholder="ex: Duke, Gracie, Ben, Unknown"></div>
<div class="col-sm">Date Found/Lost<input type="date" id="date_lost_input" name="date_lost_input"></div>
<div class="col-sm">Predominate Color<input type="text" id="color_input" name="color" placeholder="ex: Black, Rust, Black and White, Dark Brown..."></div>
<div class="col-sm">Breed of Animal<input type="text" id="breed_input" name="breed_input" placeholder="ex: Calico, Doberman, Apaloossa..."></div>
</div>
<div class="row">
<div class="col-3 col-sm">Lost/Found<input type="radio" id="lost" name="lost_input" value="Lost">Lost <input type="radio" id="found" name="lost_input" value="Found">Found</div>
<fieldset class="form-group">
<div class="row">
<div><legend class="col-form-label col-sm-2 pt-0">Sex</legend></div>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="sex_input" id="male" value="Male" checked>
<label class="form-check-label" for="male">
Male
</label>
</div>
<div class="col-2 form-check">
<input class="form-check-input" type="radio" name="sex_input" id="female" value="Female">
<label class="form-check-label" for="female">
Female
</label>
</div>
</div>
</div>
</fieldset>
<div class="col-2 col-sm">Microchipped<input type="radio" id="micro_input" name="micro_input" value="Yes">Yes <input type="radio" name="micro" value="No">No <input type="radio" name="micro" value="Unknown">Unknown</div>
</div>
<div class="row">
<div class="col-sm col-6"><label>Add description here</label><textarea id="description_input" name="description_input" placeholder="Identifying Markings and Features, limit 316 characters including spaces
(Note: For found animals, you may want to withold specific details in order to screen for the animal's owner)" wrap="virtual" rows="10" cols="45"></textarea></div>
<div class="col-sm col-5"><label>Select Your Picture Here</label><input type="file" /></div>
</div>
<div class="row">
<div class="col-sm col-12" style="background-color: #e9ecef">Program sponsored by, Bruce Osborne, your JBGoodwin REALTORS for home sales & purchases and Apartment Leases.
For every home purchased or apartment leased through your referrals to Bruce, he will donate $50 to the pet rescue of your choice.</div>
</div>
</div> <!---- Container, Main ---->
<!---- Start Flyer Rendering ---->
<div class="container" style="border: dashed; height: 1200px; width: 1571px">
<div class="row">
<div class="h2 text-center" style="margin: 10px;">SA Pet Rescue</div>
</div>
<div class="row">
<div class="h5 text-center" style="margin: 10px;">locating lost and found/stray, dogs and cats</div>
</div>
<div class="container-md h1 text-center" id="title"></div>
<div class="container-md h1 text-center" id="preview"><img id="myImg" src="#" alt="your image here" width="700" height="400"></div> <!---- Display image ---->
<div class="row container-md">
<div class="col-4 container-md h3 text-center" id="con_name"></div>
<div class="col-4 container-md h3 text-center" id="phone"></div>
<div class="col-4 container-md h3 text-center" id="email"></div>
</div>
<div class="row">
<div class="col-2 container-md h5 text-center" id="animal_name"></div>
<div class="col-2 container-md h5 text-center">Microchipped <span id="micro"></span></div>
<div class="col-2 container-md h5 text-center" id="sex"></div>
<div class="col-2 container-md h5 text-center" id="breed"></div>
<div class="col-2 container-md h5 text-center" id="color"></div>
<div class="col-2 container-md h5 text-center"><span id="lost_found"></span> On <span id="date_lost"></span></div>
</div>
<div class="container-md h3 text-center" id="description"></div>
<div class="container-fluid">
<div class="col-xs-9">
<div class="row main-row">
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
<div class="rotate">
<div class="h5 tearoff"><span class="tear_off_data"></span></div></div>
</div>
</div>
</div>
</div>
<div class="container my-5"></div>
</body>
<script src="flyer-text.js"></script>
<script type="text/jscript">
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img'); // $('img')[0]
img.src = URL.createObjectURL(this.files[0]); // set src to file url
}
});
});
</script>
</html>
You are missing .value after the element variables.
You also don't need to call document.write().
The 'Tear-offs' section should be:
var res = inputBoxTitle.value + "<br>" + inputBoxConName.value + "<br>" + inputBoxPhone.value;
$('inputBoxTitle, inputBoxConName, inputBoxPhone').onkeyup, function(){
document.getElementsByClassName('tear_off_data').innerHTML = res;
}
EDIT: I also noticed that you are declaring for loops inside of separate functions. You don't need to do this!
Example:
(function (){
for(var i = 0; i < inputLostFound.length; i++){
inputLostFound[i].onclick = function(){
document.getElementById('lost_found').innerText = this.value;
}
}
})();
Can simply be written as:
for(var i = 0; i < inputLostFound.length; i++){
inputLostFound[i].onclick = function(){
document.getElementById('lost_found').innerText = this.value;
}
}

How to sum the values from dynamically created input fields

I have created Dynamic Add / Remove fields. Everything is working perfectly. I want sum of values from Amount field to be displayed on real time basis using JavaScript. I have tried but am unable to do. I am not much familiar with JavaScript.
Following is code:
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
You can use add keyup event listener and calculate sum as:
function calculateSum() { //Add a calculateSum function
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum(); //Call calculateSum to update the sum valaue
return false;
});
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum); //update when keyup
Demo:
var i = 0;
jQuery(document).ready(function($) {
function calculateSum() {
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
I think you can do it with this code:
function calcAmount(){
var amount = 0;
$('input[name="allocate_amount[]"]').each(function(){
amount = amount + $(this).val();
});
return amount;
}
jQuery(document).ready(function($) {
$("input[name="allocate_amount[]]").blur(function(){
$("#sum").html(calcAmount());
});
});
Okay, I try to update your code: and it works fine:
main changes:
- assign ids to input fields
- make changes in function
have a look to jsfiddle
https://jsfiddle.net/dupinderdhiman/ygvphmxq/31/
Main changes:
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" id='value1' name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id='value2' name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount. <span id="sum"></span></i></small>
</div>
</div>
<script type="text/javascript">
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
debugger;
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
return false;
});
});
</script>
</body>
</html>

How to reset cascading select lists?

I have three cascading select lists. When I try to reset them with this code:
function resetSearch(advancedSearch){
document.getElementById("advancedSearch").reset();
submitQuery();
};
It resets the select lists, but because the select lists are cascading, so one depends on another to fill the select list with the correct values, it sets the values of the lists that are selected at that moment to the default.
So in my case I have three selectlists, one for the table names, one for the field names and one for the attributes. When I select a table it gives me the matching column names and attributes. If I than push teh reset button, it resets the table name to default, but the fieldnames and attribute select lists are set to the default of the other table.
Here is a picture to clarify my question:
This is my form with the select lists in it and the reset button;
<form action="javascript:submitQuery()" id="advancedSearch">
<!-- Search by name input field -->
<div class="form-group">
<div id= "selectListContent">
<div class="row">
<div id="content-a">
<div class='content-row'>
<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>
<div class="select_column col-md-6">
<label for="invoerColumnNaam">Select column:</label>
<span>
<select class="form-control" name="column_names" id="slctField">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="select_attribute col-md-9">
<label for="invoerAttribuutNaam">Select attribute:</label>
<span>
<select class="form-control" name="attribute_names" id="slctAttribute">
</select>
</span>
</div>
</div>
</div>
</div>
<!-- Buttons search en reset voor tab advanced search -->
<div class="form-group">
<div class="col-md-6">
<button type="reset" class="btn btn-block btn-primary" onclick="resetSearch()">
<span class="glyphicon glyphicon-repeat" aria-hidden="true"></span> &nbsp Reset
</button>
</div>
</div>
</div>
I assume that you have some event which populates other selects when value in first select is chosen. In that case you need to trigger it after form is reset.
For e.g.:
function resetSearch() {
$('#slctTable').closest('form')[0].reset();
$('#slctTable').trigger('change');
}
To clarify: how reset could 'know' that for 'table 1' correct list of fields is 'field1' and 'field2' and for 'table 2' it is 'other1' and 'other2'? It can just set selection to first items of lists.
var data = {
'table1': {
'tab1_column1': ['tab1_col1_attr_1', 'tab1_col1_attr_2'],
'tab1_column2': ['tab1_col2_attr_1', 'tab1_col2_attr_2']
},
'table2': {
'tab2_column1': ['tab2_col1_attr_1', 'tab2_col1_attr_2'],
'tab2_column2': ['tab2_col2_attr_1', 'tab2_col2_attr_2']
}
}
function resetSearch() {
$('#slctTable').closest('form')[0].reset();
$('#slctTable').trigger('change');
}
$(function() {
var table = $('#slctTable'),
field = $('#slctField'),
attr = $('#slctAttribute');
table.on('change', function() {
field.html('').val('');
$.each(data[$(this).val()], function(k, v) {
field.append($("<option />").val(k).text(k))
});
field.trigger('change');
});
field.on('change', function() {
attr.html('').val('');
$.each(data[table.val()][$(this).val()], function(k, v) {
attr.append($("<option />").val(v).text(v))
});
});
$.each(data, function(k, val) {
table.append($("<option />").val(k).text(k))
});
//populate fields for the first time
table.trigger('change');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="javascript:submitQuery()" id="advancedSearch">
<!-- Search by name input field -->
<div class="form-group">
<div id="selectListContent">
<div class="row">
<div id="content-a">
<div class='content-row'>
<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>
<div class="select_column col-md-6">
<label for="invoerColumnNaam">Select column:</label>
<span>
<select class="form-control" name="column_names" id="slctField">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="select_attribute col-md-9">
<label for="invoerAttribuutNaam">Select attribute:</label>
<span>
<select class="form-control" name="attribute_names" id="slctAttribute">
</select>
</span>
</div>
</div>
</div>
</div>
<!-- Buttons search en reset voor tab advanced search -->
<div class="form-group">
<div class="col-md-6">
<button type="reset" class="btn btn-block btn-primary" onclick="resetSearch()">
<span class="glyphicon glyphicon-repeat" aria-hidden="true"></span> &nbsp Reset
</button>
</div>
</div>
function resetSearch(advancedSearch){
change for this:
function resetSearch(){
I have create from your initial HTML and description this Codepen with cascading population of field. I do not see your problem. Could you provide more explaination or to say if this resolve your problem?
Codepen: http://codepen.io/anon/pen/ezmErd
HTML
<form class="container" action="javascript:submitQuery()" id="advancedSearch">
<div class="form-group">
<div id="selectListContent">
<div class="row">
<div id="content-a">
<div class='content-row'>
<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>
<div class="select_column col-md-6">
<label for="invoerColumnNaam">Select column:</label>
<span>
<select class="form-control" name="column_names" id="slctField">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="select_attribute col-md-9">
<label for="invoerAttribuutNaam">Select attribute:</label>
<span>
<select class="form-control" name="attribute_names" id="slctAttribute">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-3">
<button type="reset" class="btn btn-block btn-primary" onclick="resetSearch('advancedSearch')">
<span class="glyphicon glyphicon-repeat" aria-hidden="true"></span> &nbsp Reset
</button>
</div>
</div>
</form>
JS
var table = document.getElementById("slctTable"),
field = document.getElementById("slctField"),
attrib = document.getElementById("slctAttribute"),
populate = function (dropdown, name) {
for (var i = 0, temp; i < 4; i++) {
temp = document.createElement("option")
temp.value = i + 1;
temp.textContent = name + " " + +(i + 1);
dropdown.appendChild(temp);
}
},
submitQuery = function () {
console.log("Submit !");
},
resetSearch = function (advancedSearch) {
document.getElementById(advancedSearch).reset();
submitQuery();
};
// Populate dynamicly the first Dropdown.
populate(table, "Table");
// When you select an item of first Dropdown...
table.addEventListener("change", function() {
field.innerHTML = "";
// ...populate dynamicly the second Dropdown.
populate(field, "Field");
});
// When you select an item of second Dropdown...
field.addEventListener("change", function() {
attrib.innerHTML = "";
// ...populate dynamicly the last Dropdown.
populate(attrib, "Attribute");
});

Categories

Resources