I am trying to delete the entered task by the delete button which is created by the end of each task. I am posting my full code here
It's a simple to-do list by using bootstrap CDN .
I want to delete the row which contains user enter task,serial number,time and date.
var task = document.getElementById("enter");
var bttn = document.getElementById("button2");
var rowIdVar = document.getElementById("test");
var rowIdVar1 = document.getElementById("id1");
bttn.addEventListener("click", add);
var x = 0;
function add() {
var val1 = task.value;
if (!val1) {
alert("Please Enter A Task");
} else {
sno();
name();
tdate();
time();
cButton();
var new1 = document.createElement("l");
rowIdVar1.appendChild(new1);
}
}
function sno() {
if (x == x) {
x = x + 1;
var list1 = document.createElement("l");
list1.innerHTML = x;
rowIdVar.appendChild(list1).setAttribute("class", "col-md-2");
}
}
function name() {
var val = task.value;
var list2 = document.createElement("l");
list2.innerHTML = val;
rowIdVar.appendChild(list2).setAttribute("class", "col-md-4");
task.value = "";
}
function tdate() {
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var result = (date + "/" + month + "/" + year);
var lm = document.createElement("l");
lm.innerHTML = result;
rowIdVar.appendChild(lm).setAttribute("class", "col-md-2");
}
function time() {
var t = new Date();
var hour = t.getHours();
var minutes = t.getMinutes();
var seconds = t.getSeconds();
var result1 = (hour + ":" + minutes + ":" + seconds);
var lm1 = document.createElement("l");
lm1.innerHTML = result1;
rowIdVar.appendChild(lm1).setAttribute("class", "col-md-2");
}
function cButton() {
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "delete");
btn.setAttribute("class", "btn btn-danger");
rowIdVar.appendChild(btn).setAttribute("class", "col-md-2");
btn.addEventListener("click", deleteElements);
}
function deleteElements() {
rowIdVar1.parentNode.removeChild(rowIdVar);
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<div class="row">
<div class="col-md-10 col-sm-10 h">
<center>
<h1>TO DO LIST...</h1>
</center><br>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-sm-10 bg">
<input type="text" class="form-control " placeholder="Enter task" id="enter">
</div>
<div class="col-md-2 col-sm=2">
<button type="button" class="btn btn-primary btn-lg" id="button2"><center>ADD</center></button>
</div>
</div><br><br>
</div>
<div class="container">
<div class="row" id="id1">
<div class="col-md-2 b">
<h1>S.no</h1>
</div>
<div class="col-md-4 b">
<h1>Enter Task</h1>
</div>
<div class="col-md-2 b">
<h1>Date</h1>
</div>
<div class="col-md-2 b">
<h1>Time</h1>
</div>
<div class="col-md-2">
</div>
</div>
</div>
<div class="row" id="test">
<div class="col-md-2"> </div>
<div class="col-md-4"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
</div>
var task = document.getElementById("enter");
var bttn = document.getElementById("button2");
var rowIdVar = document.getElementById("test");
var rowIdVar1 = document.getElementById("id1");
bttn.addEventListener("click", add);
var x = 0;
function add() {
var val1 = task.value;
if (!val1) {
alert("Please Enter A Task");
} else {
sno();
name();
tdate();
time();
cButton();
var new1 = document.createElement("l");
rowIdVar1.appendChild(new1);
}
}
function sno() {
if (x == x) {
x = x + 1;
var list1 = document.createElement("li");
list1.innerHTML = x;
rowIdVar.appendChild(list1).setAttribute("class", "col-md-2");
}
}
function name() {
var val = task.value;
var list2 = document.createElement("li");
list2.innerHTML = val;
rowIdVar.appendChild(list2).setAttribute("class", "col-md-4");
task.value = "";
}
function tdate() {
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var result = (date + "/" + month + "/" + year);
var lm = document.createElement("li");
lm.innerHTML = result;
rowIdVar.appendChild(lm).setAttribute("class", "col-md-2");
}
function time() {
var t = new Date();
var hour = t.getHours();
var minutes = t.getMinutes();
var seconds = t.getSeconds();
var result1 = (hour + ":" + minutes + ":" + seconds);
var lm1 = document.createElement("li");
lm1.innerHTML = result1;
rowIdVar.appendChild(lm1).setAttribute("class", "col-md-2");
}
function cButton() {
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "delete");
btn.setAttribute("class", "btn btn-danger");
rowIdVar.appendChild(btn).setAttribute("class", "col-md-2");
btn.addEventListener("click", deleteElements);
}
function deleteElements() {
rowIdVar.parentNode.removeChild(rowIdVar);
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<body id="body">
<div class="row">
<div class="col-md-10 col-sm-10 h">
<center>
<h1>TO DO LIST...</h1>
</center><br>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-sm-10 bg">
<input type="text" class="form-control " placeholder="Enter task" id="enter">
</div>
<div class="col-md-2 col-sm=2">
<button type="button" class="btn btn-primary btn-lg" id="button2"><center>ADD</center></button>
</div>
</div><br><br>
</div>
<div class="container">
<div class="row" id="id1">
<div class="col-md-2 b">
<h1>S.no</h1>
</div>
<div class="col-md-4 b">
<h1>Enter Task</h1>
</div>
<div class="col-md-2 b">
<h1>Date</h1>
</div>
<div class="col-md-2 b">
<h1>Time</h1>
</div>
<div class="col-md-2">
</div>
</div>
</div>
<div class="row" id="test">
<div class="col-md-2"> </div>
<div class="col-md-4"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
</div>
Related
UPdated: have been stuck on this for 3 day's now and I cannot find an answer anywhere.
I have a model that contains -input type="text" name="mycardname" id="CardName"/-
I want to post the card name into the value of the input box.
I can put it in a label or a span, but cannot find a way or example to add it to the input box.
My code is below.
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '');
$target('#CardName')('value try This');
});
});
$('#settingsModal,#monthModal').on('show.bs.modal', function (event) {
alert("this alert");
var $card = $(event.relatedTarget).closest('.card');
var $modal = $(this);
var data = $card.data();
Document.getElementById('#CardName').val("try This");
for (var item in data) {
$modal.find('[name="' + item + '"]').val(data[item]);
}
});
$('#monthModal .btn-primary').click(function () {
var $modal = $(this).closest('.modal');
var searchType = $modal.find('input[name="SearchTypeRadio"]:checked').val();
var metric = $modal.find('[name="metric"]').val();
var month = $modal.find('[name="month"]').val();
var cdName = $modal.find('[name="mycardname"]').val();
alert("SearchType: " + searchType + " Metric: " + metric + " Month: " + month + " Card Name: " + cdName);
});
$('.btnApplyColors').on('click', function () {
var $modal = $(this).closest('.modal');
var cardName = $modal.find('[name="name"]').val();
var grMin = $modal.find('[name="greenmin"]').val();
var grMax = $modal.find('[name="greenmax"]').val();
var yMin = $modal.find('[name="yellowmin"]').val();
var yMax = $modal.find('[name="yellowmax"]').val();
var rMin = $modal.find('[name="redmin"]').val();
var rMax = $modal.find('[name="redmax"]').val();
var cardTR = cardName + 'TR';
var elements = document.getElementsByClassName(cardTR); // get all elements
for (var i = 0; i < elements.length; i++) {
var tsd1 = cardName + i + 'TD1';
var tsd2 = cardName + i + 'TD2';
var td1 = document.getElementById(tsd1).innerHTML;
var td2 = parseInt(document.getElementById(tsd2).innerHTML);
alert(td1 + " - " + td2);
switch (true) {
case (td2 >= yMin && td2 <= yMax):
alert(td1 + " - " + td2 + " YMin " + yMin + " yMax " + yMax);
elements[i].style.backgroundColor = "lightyellow";
elements[i].style.color = 'brown';
break;
case (td2 >= grMin && td2 <= grMax):
alert(td1 + " - " + td2 + " grMin " + grMin + " grMax " + grMax);
elements[i].style.backgroundColor = "#E7FCE3";
elements[i].style.color = 'darkgreen';
break;
case (td2 >= rMin && td2 <= rMax):
alert(td1 + " - " + td2 + " rMin " + rMin + " rMax " + rMax);
elements[i].style.backgroundColor = "mistyrose";
elements[i].style.color = 'red';
break;
default:
alert("Hit the Default because " + td2 + " not found");
break;
}
}
$('#ScoreCardDefaults').modal('hide');
});
$(document).ready(function () {
$('input[type="radio"]').click(function () {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
// clean this up //
let startYear = 2000;
let endYear = new Date().getFullYear();
for (i = endYear; i > startYear; i--) {
$('#yearpicker').append($('<option />').val(i).html(i));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-4">
<div class="col mb-4" data-mincoolscale="71">
<div class="card text-center" data-metric="14" data-month="2020-10" data-mincoolscale="71" data-maxcoolscale="100" data-minwarmscale="51" data-maxwarmscale="70" data-minhotscale="0" data-maxhotscale="50">
<div class="card-img-top d-flex align-items-center justify-content-center bg-primary text-light metric-header">
<span class="h5 my-1">my card</span>
</div>
<div class="card-body pt-3">
<h6 class="card-title">
my card title
</h6>
<p>
<span class="metric-date">#DateTime.Now.ToString("MMMM yyyy")</span>
<button type="button" class="btn btn-sm btn-link CardModal" data-cardname="The Card Name" data-toggle="modal" data-target="#monthModal" title="Edit" aria-title="Edit">
Ccc
</button>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="monthModal" tabindex="-1" aria-labelledby="monthModalTitle" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="monthModalTitle">Display Statistics For</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span id="modal-cardname"></span>
<input type="text" name="mycardname" id="CardName" />
<div class="myRadios">
<label><input type="radio" name="SearchTypeRadio" value="Monthly"> Monthly</label>
<label><input type="radio" name="SearchTypeRadio" value="Quarterly"> Quarterly</label>
</div>
<div style="display:none" class="Monthly box">You have selected Monthly</div>
<div style="display:none" class="Quarterly box">You have selected quarterly</div>
<div style="display:none" class="Monthly box form-group">
<input type="month" id="month" name="month" class="form-control w-auto" placeholder="mm/yyyy" max="#DateTime.Now.ToString("yyyy-MM")" min="2010-01" />
</div>
<div style="display:none" class="Quarterly box form-group">
#*<label for="month">Yearly Quarter of</label>*#
<select id="QTRS">
<option value="1" selected>1st Quarter</option>
<option value="2">2nd Quarter</option>
<option value="3">3rd Quarter</option>
<option value="4">4th Quarter</option>
</select>
<select name="yearpicker" id="yearpicker"></select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
#*<a class=" btn btn-primary" asp-controller="Home" asp-action="updateSSOA"> Apply</a>*#
<button type="button" class="btn btn-primary" data-dismiss="modal">Apply</button>
</div>
</div>
</div>
</div>
I don’t know if there are multiple text boxes and buttons that are the same on this page. Do you mean to traverse all ATTRIBUTES to the text box corresponding to this button or to pass the ATTRIBUTES corresponding to the modal value into the text box?
If you pass in a corresponding ATTRIBUTES, please refer to the following example:
<input type="text" name="mycardname" id="CardName" />
<button type="button" class="btn btn-sm btn-link CardModal"
data-cardname="kls01" data-toggle="modal" data-target="#monthModal"
title="Edit" aria-title="Edit">
Launch Modal
</button>
#section Scripts{
<script>
$(function () {
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '00');
if ($target.prev().val() == '' || $target.prev().val == null) {
$target.prev().val(attributeName || '')
}
});
});
})
</script>
}
Result:
I finally figured it out:
Change:
$target('#CardName')('value try This');
to:
var myCardName = $(this).data('cardname');
$(".modal-body #mycardname").val(myCardName);
Using eonasdan/bootstrapdatetimepicker, I try to solve this:
How to set disabledTimeIntervals, minDate and maxDate for each dynamically created time-input-field? minDate and maxDate has to be set to the corresponding field, while disabledTimeIntervals has to be set to all fields, except the edited fields - also on every edit.
I do not have any glue to get this done.
Has anyone a solution for this?
$(document).ready(function() {
$("#timeday0from").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#timeday0until").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#timeday0from").on("dp.change", function(e) {
$("#timeday0until")
.data("DateTimePicker")
.minDate(e.date);
});
$("#timeday0until").on("dp.change", function(e) {
$("#timeday0from")
.data("DateTimePicker")
.maxDate(e.date);
});
});
var i = 0;
var day = "day_";
var original = document.getElementById(day + i);
function duplicateElement() {
var clone = original.cloneNode(true);
i++;
clone.id = day + i; // there can only be one element with an ID
clone.childNodes;
for (var input of $(".timeday0from", clone)) {
input.id = "time" + clone.id + "from";
}
for (var input of $(".timeday0until", clone)) {
input.id = "time" + clone.id + "until";
}
for (var select of $(".timeday0type", clone)) {
select.id = "time" + clone.id + "info";
}
for (var input of $(".timeday0from", clone)) {
input.name = "time[" + day + "][" + i + "][from]";
}
for (var input of $(".timeday0until", clone)) {
input.name = "time[" + day + "][" + i + "][until]";
}
for (var select of $(".timeday0type", clone)) {
select.name = "time[" + day + "][" + i + "][type]";
}
for (var input of $(".timeday0from", clone)) {
input.value = "";
}
for (var input of $(".timeday0until", clone)) {
input.value = "";
}
for (var select of $(".timeday0type", clone)) {
select.value = "";
}
original.parentNode.appendChild(clone);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-lg-6 col-md-12">
<div class="well">
<h3>Day</h3>
<div class="row" id="day_0">
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0from" class="control-label">Interval starts</label>
<div class='input-group date' id='timeday0from'>
<input type="text" class="form-control datepicker timeday0from" name="time[day][0][from]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0until" class="control-label">Interval ends</label>
<div class='input-group date' id='timeday0until'>
<input type="text" class="form-control datepicker timeday0until" name="time[day][0][until]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-12">
<label for="timeday0info" class="control-label">Interval-Option</label>
<select name="time[day][0][info]" class="form-control timeday0type" id="timeday0info">
<option>Bitte auswählen</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default" onclick="duplicateElement();"><span class="glyphicon glyphicon-plus"></span></button>
Creating works. But I do not have any idea, how to set maxDate, minDate and disabledTimeIntervals (overlapping of ranges should prevented) on clone/remove of elemen and update of a time-field.
What a mess - but it works!
$.fn.datetimepicker.defaults.tooltips = {
today: 'Heute',
clear: 'Auswahl leeren',
incrementMinute: 'später',
decrementMinute: 'früher',
incrementHour: 'später',
decrementHour: 'früher',
pickHour: 'Stunde wählen',
pickMinute: 'Minute wählen'
};
$.fn.datetimepicker.defaults.useCurrent = false;
$.fn.datetimepicker.defaults.ignoreReadonly = true;
$.fn.datetimepicker.defaults.allowInputToggle = true;
$.fn.datetimepicker.defaults.locale = 'de';
$.fn.datetimepicker.defaults.showClear = true;
$(document).ready(function() {
initDateTimePair('day',0);
updateMin('day',0);
updateMax('day',0);
});
var i = 0;
var original = document.getElementById('day' +'_'+ i);
function initDateTimePair(day, item){
$("#time"+day+item+"from").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#time"+day+item+"until").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
}
function updateMax(day, item){
$("#time"+day+item+"from").on("dp.change", function(e) {
$("#time"+day+item+"until").data("DateTimePicker").minDate(e.date);
if($('#time'+day+item+'until').data("DateTimePicker")){
updateDisabledTimes(day, item);
}
});
}
function updateMin(day, item){
$("#time"+day+item+"until").on("dp.change", function(e) {
$("#time"+day+item+"from").data("DateTimePicker").maxDate(e.date);
if($('#time'+day+item+'from').data("DateTimePicker")){
updateDisabledTimes(day, item);
}
});
}
function initDisabledTimes(day, item){
var arr = collectDisabledTime(day, null);
$('#time'+day+item+'from').data("DateTimePicker").disabledTimeIntervals(arr);
$('#time'+day+item+'until').data("DateTimePicker").disabledTimeIntervals(arr);
}
function updateDisabledTimes(day, item){
for(l=0; l<=i; l++) {
var arr = collectDisabledTime(day, item);
if(l!=item){
$('#time'+day+l+'from').data("DateTimePicker").disabledTimeIntervals(arr);
$('#time'+day+l+'until').data("DateTimePicker").disabledTimeIntervals(arr);
}
}
}
function collectDisabledTime(day, item){
var arr = [];
for(j=0; j<=i; j++){
if(j!=item){
var from = $('#time'+day+j+'from').data("DateTimePicker");
var until = $('#time'+day+j+'until').data("DateTimePicker");
if(until !== undefined && until.date() !== null && from !== undefined && from.date() !== null){
arr.push([$('#time'+day+j+'from').data("DateTimePicker").date().add(1,'minute'), $('#time'+day+j+'until').data("DateTimePicker").date().add(-1,'minute')]);
}
}
}
return arr;
}
function duplicateElement(day) {
var clone = original.cloneNode(true);
i++;
clone.id = day + '_' + i; // there can only be one element with an ID
clone.childNodes;
for (var input of $(".time"+day+"from", clone)) {
input.id = "time" + day + i + "from";
}
for (var input of $(".time"+day+"until", clone)) {
input.id = "time" + day + i + "until";
}
for (var select of $(".time"+day+"type", clone)) {
select.id = "time" + day + i + "info";
}
for (var input of $(".time"+day+"from", clone)) {
input.name = "time[" + day + "][" + i + "][from]";
}
for (var input of $(".time"+day+"until", clone)) {
input.name = "time[" + day + "][" + i + "][until]";
}
for (var select of $(".time"+day+"type", clone)) {
select.name = "time[" + day + "][" + i + "][type]";
}
for (var input of $(".time"+day+"from", clone)) {
input.value = "";
}
for (var input of $(".time"+day+"until", clone)) {
input.value = "";
}
for (var select of $(".time"+day+"type", clone)) {
select.value = "-1";
}
original.parentNode.appendChild(clone);
initDateTimePair(day, i);
updateMin(day, i);
updateMax(day, i);
initDisabledTimes(day, i);
updateDisabledTimes(day, i);
console.log($('#timeday'+i+'from').data("DateTimePicker").disabledTimeIntervals())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/de.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="col-lg-6 col-md-12">
<div class="well">
<h3>Day</h3>
<div class="row" id="day_0">
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0from" class="control-label">Interval starts</label>
<div class='input-group date' id='timeday0from'>
<input type="text" class="form-control datepicker timedayfrom" name="time[day][0][from]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0until" class="control-label">Interval ends</label>
<div class='input-group date' id='timeday0until'>
<input type="text" class="form-control datepicker timedayuntil" name="time[day][0][until]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-12">
<label for="timeday0info" class="control-label">Interval-Option</label>
<select name="time[day][0][info]" class="form-control timedaytype" id="timeday0info">
<option value="-1">Bitte auswählen</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default" onclick="duplicateElement('day');"><span class="glyphicon glyphicon-plus"></span></button>
I'm trying to build a currency converter. I'm using javascript and I have a good foundation but I want to know how to make the converter update in real-time without having to click a button.
How do I make it so that my converter converts from a base currency of M without needing be be within a select element & how do I make the converter update as the user types the number in, rather than having to click a button?
I've tried removing all of the available options for the .currency-1 class and only leaving M, but that still leaves a drop down menu. I want to convert from M to X (USD, GBP, CAD, EUR, etc.)
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
Any help would be appreciated!
I need the user to be able to input X amount (in currency M, no dropdown), select their native currency & have the page calculate the rate as soon as they type in the number.
Add another eventListner which is keyup so that whenever user types in the required field, it will call the convertCurrency function as below:
amountInput.addEventListener('keyup', convertCurrency);
Edit:
To remove the selection box for M, remove the select element and replace by either <p> or <span> tag. After this, you would have to get the this value by using innerText as var from = baseCurrencyInput.innerText; in the currency converter function.
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
}
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.innerText;
var to = secondCurrencyInput.value;
var result = 0;
try {
if (from == to) {
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch (err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
amountInput.addEventListener('keyup', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<p id="currency-1">M</p>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
$('#amount').keyup(function(event){
convertCurrency(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
In this script: last item is not selected to apply colorMe function
var k =0;
var userarray = [];
var dayarray = [];
var dayarray2 = [];
var dayarray3 = [];
var data = 0;
function colorMe(param,param_af,param_eve, param2)
{
/*console.log("DAY "+param);
console.log("user "+param2);*/
//console.log("k= "+k);
console.log("data= "+data);
userarray.push(param2);
//console.log("mY "+userarray[k]);
dayarray.push(param);
dayarray2.push(param_af);
//console.log("afternoon "+dayarray2[k]);
dayarray3.push(param_eve);
//console.log("evening "+dayarray3[k]);
//console.log("Day "+dayarray[k]);
var len = userarray.length;
console.log("K= "+k);
for(;data < k;data++)
{
//console.log("data="+ data);
var arr = dayarray[data];
var arr2 = dayarray2[data];
var arr3 = dayarray3[data];
$("div.morning_"+userarray[data]+" span").each(function() {
if(arr.indexOf($(this).attr("class")) > -1) {
$(this).css("color","#26F525");
}
});
$("div.afternoon_"+userarray[data]+" span").each(function() {
if(arr2.indexOf($(this).attr("class")) > -1) {
$(this).css("color","#26F525");
}
});
$("div.evening_"+userarray[data]+" span").each(function() {
if(arr3.indexOf($(this).attr("class")) > -1) {
$(this).css("color","#26F525");
}
});
}
**
//This identifies the last item, can anything be done here to apply color on matching string like the rest?
**
if(data == (localStorage.size-1)){
alert("data"+data+" k= "+k+"size= "+localStorage.size+"user= "+param2+"morn= "+param+"aftr="+param_af+"eve="+param_eve);
}
k++;
}
T'm trying to color only the last item in the array. How do I do that? Here's my fiddle: https://jsfiddle.net/axpbe377/2/
HTML structure
<div id='1'>
User 1234
<div class='morning_1234'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='afternoon_1234'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='evening_1234'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
</div>
<br/><br/>
<div id='2'>
User 4455
<div class='morning_4455'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='afternoon_4455'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='evening_4455'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
</div>
<br/><br/>
<div id='3'>
User 9868
<div class='morning_9868'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='afternoon_9868'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='evening_9868'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
</div>
https://jsfiddle.net/axpbe377/3/
<div id='1'>
User 1234
<div class='morning_1234'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='afternoon_1234'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='evening_1234'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
</div>
<br/>
<br/>
<div id='2'>
User 4455
<div class='morning_4455'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='afternoon_4455'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='evening_4455'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
</div>
<br/>
<br/>
<div id='3'>
User 9868
<div class='morning_9868'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='afternoon_9868'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
<div class='evening_9868'>
<span>Mon</span><span>Tue</span><span>Wed</span><span>Thrs</span><span>Fri</span><span>Sat</span><span>Sun</span>
</div>
</div>
SCRIPT
var data = [{
user_id: 1234,
morning: 'Sat,Sun',
afternoon: 'Tue,Thrs,Sun',
evening: ''
}, {
user_id: 4455,
morning: 'Thrs,Fri,Sun',
afternoon: 'Tue',
evening: 'Mon'
}, {
user_id: 9868,
morning: 'Tue,Wed',
afternoon: 'Tue',
evening: 'Fri,Sun'
}];
data.forEach(function(user) {
var mornings = user.morning.split(',');
var afternoons = user.afternoon.split(',');
var evenings = user.evening.split(',');
$("div.morning_" + user.user_id + " span").filter(function() {
return mornings.indexOf(this.innerHTML) > -1;
}).css('color', '#26F525');
$("div.afternoon_" + user.user_id + " span").filter(function() {
return afternoons.indexOf(this.innerHTML) > -1;
}).css('color', '#26F525');
$("div.evening_" + user.user_id + " span").filter(function() {
return evenings.indexOf(this.innerHTML) > -1;
}).css('color', '#26F525');
});
If you want to have your function call...
https://jsfiddle.net/axpbe377/5/
data.forEach(function(user){
colorMe(user.morning, user.afternoon, user.evening, user.user_id);
});
function colorMe(param, param2, param3, user_id){
var mornings = param.split(',');
var afternoons = param2.split(',');
var evenings = param3.split(',');
$("div.morning_"+ user_id +" span").filter(function(){
return mornings.indexOf(this.innerHTML) > -1;
}).css('color', '#26F525');
$("div.afternoon_"+ user_id +" span").filter(function(){
return afternoons.indexOf(this.innerHTML) > -1;
}).css('color', '#26F525');
$("div.evening_"+ user_id +" span").filter(function(){
return evenings.indexOf(this.innerHTML) > -1;
}).css('color', '#26F525');
}
I am implementing an extend form function, in which there is a label text (marked in html) that I hope to include a number to increment.
So every time when a form is extended/cloned, the label text in the extended form shows Student 1, Student 2... accordingly. Can I be advised how to do that?
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-3">
Grade 6
</div>
<div class="col-lg-3">
Male
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- Student number needs to increase when a new form is extended. -->
<label>Student 1</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label for="display_student_1_grade">Grade</label>
<div id="display_student_1_grade"></div>
</div>
<div class="col-lg-6">
<label for="display_student_1_gender">Gender</label>
<div id="display_student_1_gender"></div>
</div>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="One More Student" />
To answer the question directly, you just need to find the appropriate <label> and update the innerHTML (see below).
However, what you are doing here can be achieved using the new HTML5 template element without having to hide <span> elements. Additionally, you have to remember that when you remove a student, the counter isn't going to decrease, nor are the already added students going to update. If you want that kind of functionality, you may want to look into a Javascript MVVM, like Angular.
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
// Find the label here and update the innerHTML appropriately
newField.querySelector(".col-lg-12 label").innerHTML = "Student " + counter;
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-3">
Grade 6
</div>
<div class="col-lg-3">
Male
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- Student number needs to increase when a new form is extended. -->
<label>Student 1</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label for="display_student_1_grade">Grade</label>
<div id="display_student_1_grade"></div>
</div>
<div class="col-lg-6">
<label for="display_student_1_gender">Gender</label>
<div id="display_student_1_gender"></div>
</div>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="One More Student" />