I'm having Javascript with this code:
function addRowss(frm) {
var start = new Date(document.myform.bookstart.value);
var ends = new Date(document.myform.bookend.value);
var starts = document.myform.bookstart.value;
var yeara = starts.substring(0, 2);
var montha = starts.substring(3,6);
var datea = starts.substring(7,11);
var num3 = (ends - start)/1000/60/60/24;
var i;
for(i=0;i <= num3; i++)
{
var theday = yeara+'-'+getnumo(montha)+'-'+datea;
var resday = new Date(theday);
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Date: <input type="text" class="datepick" name="qty[]" id="date'+rowNum+'" value="'+theday+'"> Price: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
yeara++;
}
}
What I want to do is text name[] will be automatically filled by my start date to my end date. For example, if I fill '06-Aug-2015' at start input and '06-Sep-2015' at end input, it will result about 30 textbox field which it's value will be filled by its date... so it will result:
[2015-08-06][ empty ]
[2015-08-07][ empty ]
[2015-08-08]
...
[2015-09-06][ empty ]
Note: [ ] = textbox
Right now I can add many textbox (attachment pic), but I can't set the value of this textbox as I want. Any idea?
You should write a function to parse that format to a Date object, it's a non–standard format so no guarantee that the Date constructor will parse it correctly in all browsers. Then create a function to create a date string from a Date object in the format you require. Now you can generate the rows and just call the functions to add the formatted strings, incrementing the date by one day as you go along.
Here's how I'd rewrite your code to do that, you can get rid of the rowNum variable, I've modified the remove listener and function so it's not required.
// '06-Sep-2015' to Date
function parseDMY(s) {
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var b = s.split('-');
return new Date(b[2],months[b[1].toLowerCase().substring(0,3)],b[0]);
}
// Date to '06-Sep-2015'
function formatDate(date) {
var months = ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'];
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '-' + months[date.getMonth()] + '-' + date.getFullYear();
}
function addRows(frm) {
var start = parseDMY(frm.bookstart.value);
var ends = parseDMY(frm.bookend.value);
var markup = '';
var num3 = Math.round((ends - start)/8.64e7);
var rowNum = 0;
for(var i=0; i <= num3; i++) {
var theday = formatDate(start);
++rowNum;
markup += '<p id="rowNum' + rowNum + '">Date: <input type="text" class="datepick" name="qty[]" id="date' +
rowNum + '" value="' + theday + '"> Price: <input type="text" name="name[]" value="' +
frm.add_name.value + '"> <input type="button" value="Remove" onclick="removeRow(this);"></p>';
start.setDate(start.getDate() + 1);
}
document.getElementById('itemRows').innerHTML = markup;
}
function removeRow(el) {
var node = el.parentNode;
node.parentNode.removeChild(node);
}
<form id="bookingForm">
<table>
<tr><td>Start date<td><input name="bookstart" value="05-Aug-2015">
<tr><td>End date<td><input name="bookend" value="08-Aug-2015">
<tr><td><input name="add_name" value="the name">
<tr><td><input type="reset"><td><input type="button" value="Add rows" onclick="addRows(this.form)">
</table>
<div id="itemRows"></div>
</form>
Related
I'm working on a tool for my job to auto generate task comments to streamline agent workflow. I'm trying to use a selector to differentiate between ticket types and generate a comment string accordingly.
The problem I'm running into is I can't seem to get the page to tell the the selector has changed, and it will only give the if condition and ignore the else.
I'm certain I'm missing something simple but can't seem to figure it out.
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth() + 1) + '-' + today.getDate() + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date + ' ' + time;
setInterval(1000);
if (tick = 1) {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "# attempt, contacted CX #";
}
}
btn1.addEventListener('click', fun1);
</script>
</html>
A few issues to address:
your comparison needs a double equal - ==
tick itself is just an html element, you can't compare it to a number, you need to get the currently selected index
you use id=ticket twice, so when you get the html element by that ID, it grabs the first one, which is a label.
I believe this code should fix your issues
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket-label"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date+' '+time;
setInterval(1000);
if (tick.selectedIndex == 0){
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"# attempt, contacted CX #";
}
}
btn1.addEventListener('click',fun1);
</script>
</html>
Your value for tick would be a string and you are checking it as integer. Try by changing it to, if (tick == "1").
Label attribute id is same as of select attribute. Try by changing the label id. All HTML attributes must have unique id / name.
In Plain JavaScript, you get the selected option value as follow
var e = document.getElementById("tick");
var value = e.options[e.selectedIndex].value;
Hope this helps! :)
Given below function is not working in my ASP.NET application.
function sum() {
var txtFirstNumberValue = document.getElementById('txtrd').value;
var txtsecondNumberValue = document.getElementById('txtintalment').value;
var txtthirdNumberValue = document.getElementById('txtprd').value;
var txtfourNumberValue = document.getElementById('Penality').value;
var txtFiveNumberValue = document.getElementById('txtint').value;
var txtsixNumberValue = document.getElementById('txtsbint').value;
var result = (parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtthirdNumberValue) + parseFloat(txtfourNumberValue) + parseFloat(txtFiveNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtsixNumberValue)).toFixed(2);
if (!isNaN(result)) {
document.getElementById('txttp').value = result;
}
}
Please help. Thank you.
There is a typo error in txtSecondNumberValue variable you declare variable as txtsecondNumberValue and accessing as txtSecondNumberValue.
Please correct the variable name.
var txtsecondNumberValue = document.getElementById('txtintalment').value;
var result = (parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtthirdNumberValue) + parseFloat(txtfourNumberValue) + parseFloat(txtFiveNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtsixNumberValue)).toFixed(2);
Here is the working example,
function sum() {
var txtFirstNumberValue = document.getElementById('txtrd').value;
var txtsecondNumberValue = document.getElementById('txtintalment').value;
var txtthirdNumberValue = document.getElementById('txtprd').value;
var txtfourNumberValue = document.getElementById('Penality').value;
var txtFiveNumberValue = document.getElementById('txtint').value;
var txtsixNumberValue = document.getElementById('txtsbint').value;
var result = (parseFloat(txtFirstNumberValue) + parseFloat(txtsecondNumberValue) + parseFloat(txtthirdNumberValue) + parseFloat(txtfourNumberValue) + parseFloat(txtFiveNumberValue) + parseFloat(txtsixNumberValue)).toFixed(2);
if (!isNaN(result)) {
document.getElementById('txttp').value = result;
}
}
div{
display:grid;
grid-template-columns:1fr 9fr;
}
input {
width:100px;
}
<div>First: <input id="txtrd" type="number" value="10">
Second: <input id="txtintalment" type="number" value="10">
Third: <input id="txtprd" type="number" value="10">
Fourth: <input id="Penality" type="number" value="10">
Fifth: <input id="txtint" type="number" value="10">
Sixth: <input id="txtsbint" type="number" value="10">
Result: <input id="txttp" type="number" value="" disabled>
</div>
<button type="button" onclick="sum()">Calculate</button>
I'm creating a dropdownlist of year.
How can I automatically populate the dropdownlist?
For example, I will be adding a dropdown value 1980, can I use jQuery to populate it to the current year, so I will not need to type all the year?
You can use a for loop between 1980 and the current year, which you can retrieve through the getFullYear() property of a Date object. Try this:
var html = '';
for (var i = 1980; i <= new Date().getFullYear(); i++) {
html += '<option value="' + i + '">' + i + '</option>';
}
$('#mySelect').html(html);
Working example
If you'd prefer to start with the current year and work down, you can use a negative iteration, like this:
for (var i = new Date().getFullYear(); i >= 1980; i--) {
html += '<option value="' + i + '">' + i + '</option>';
}
It's simple using a for loop and adding to string like:
var nowY = new Date().getFullYear(),
options = "";
for(var Y=nowY; Y>=1980; Y--) {
options += "<option>"+ Y +"</option>";
}
$("#years").append( options );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="years"></select>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear
http://api.jquery.com/append/
You can use a for loop (http://www.w3schools.com/js/js_loop_for.asp)
function fillDates(startDate){
yr = new Date().getFullYear();
options = "";
for(var i=startDate, i<=yr, i++){
options += ("<option value = "+i+">"+i+"</option");
}
$("select").append(options);
}
fillDates(1908);
chong there are lots of answers, i am little bit let to update my answer to jsFiddle.
fiddle : https://jsfiddle.net/eua98tqa/8/
HTML:
<html>
<head>
</head>
<body>
<select>
</select>
</body>
</html>
jQuery:
var fromYear = 1980;
var currentYear = new Date().getFullYear();
for (var i = fromYear; i <= currentYear; i++) {
$("select").append('<option value="' + i + '">' + i + '</option>');
}
I have more than one year dorpdowns, for which I wanted to compute year list from one specific year till current year. Commenting my final solution, may be somebody can find this useful:
function populateYearList(minYear, currentYear, selectElement){
var max = currentYear, min = minYear;
for (var i = min; i<=max; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
selectElement.append(opt);
}
//selecting current year by default and adding "selected" attribute to it
$(selectElement).val(max)
.find("option[value=" + max +"]")
.attr("selected","selected");
}
calling on page load
var selectElement = $('.select-class');
populateYearList('2015', currentYear, selectElement);
please refer code below
<input type="text" id="inputyear">
<select id="selectyear">
</select>
<input type="button" value="Generate" onclick="FillYears()">
<script type="text/javascript">
function FillYears(){
for(var i=parseInt($("#inputyear").val());i<=(new Date().getFullYear());i++)
{
$("#selectyear").append($("<option>"+i+"</option>"));
}
}
</script>
I'm simply trying to take inputs from html input fields.
The problem is, my function always evaluate the inputs to 0.
What should I do my code to work as I expected (to take inputs from fields and pass them to my javascript functions). If there is alike answered questions asked before, please refer.
Please do not propose jQuery solutions - I can't follow its full of parantheses syntax.
P.S. Zeros on ternary, are just for avoiding NaNs. Nothing else.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<strong>Data</strong>
<hr>Price:
<input type="text" id="price" value="0">
<br>Prepay:
<input type="text" id="prepay" value="0">
<br>Percent:
<input type="text" id="percent" value="0">
<br>Month:
<input type="text" id="month" value="0" onchange="refactorTable('payment-plan')">
<br>
<hr>
<strong>Table</strong>
<table id="payment-plan" border="1">
<thead>
<tr>
<td>Month</td>
<td>Amount</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var Sum = parseInt(document.getElementById('price').value);
var PrePayment = parseInt(document.getElementById('prepay').value);
var Percent = parseInt(document.getElementById('percent').value);
var Month = parseInt(document.getElementById('month').value);
//console.log(Sum +" -- "+ PrePayment +" -- "+ Percent +" -- "+ Month);
function monthlyPaymentPlan(Sum, PrePayment, Percent, Month) {
var BigJohn = Sum - PrePayment;
//console.log(BigJohn);
var monthly = Math.ceil((BigJohn + BigJohn * Percent) / Month);
return Month > 0 ? monthly : 0;
}
function lastMonth(Sum, PrePayment, Percent, Month) {
return Month > 0 ? Sum - monthlyPaymentPlan(Sum, PrePayment, Percent, Month) * (Month - 1) : 0;
}
function refactorTable(tbl_id) {
var table = document.getElementById(tbl_id).getElementsByTagName('tbody')[0];
table.innerHTML = "";
var i = 0;
var rows = document.getElementById('month').value;
rows = parseInt(rows);
for (i = 0; i < rows - 1; i++) {
table.insertRow(-1).innerHTML = "<td>" + (i + 1) + "</td><td>" + monthlyPaymentPlan(Sum, PrePayment, Percent, Month) + "</td>";
}
table.insertRow(-1).innerHTML = "<td>" + rows + "</td><td>" + lastMonth(Sum, PrePayment, Percent, Month) + "</td>";
}
</script>
</body>
</html>
You are getting the values when the page renders, instead of when the function is supposed to run. Place your assignments inside a function and call the function.
// Define the variables globally so they can be used in any function
var Sum;
var PrePayment;
var Percent;
var Month;
// Call this function to set the values of the global variables.
function getValues() {
Sum = parseInt(document.getElementById('price').value);
PrePayment = parseInt(document.getElementById('prepay').value);
Percent = parseInt(document.getElementById('percent').value);
Month = parseInt(document.getElementById('month').value);
}
// Call the getValues function first to set the values and then continue on
// with your function calculations.
function refactorTable(tbl_id) {
getValues();
// Do the rest...
}
You need to get the values at the time the function is called. Right now you're getting the values on page load (which is 0).
function refactorTable(tbl_id) {
var Sum = parseInt(document.getElementById('price').value);
var PrePayment = parseInt(document.getElementById('prepay').value);
var Percent = parseInt(document.getElementById('percent').value);
var Month = parseInt(document.getElementById('month').value);
var table = document.getElementById(tbl_id).getElementsByTagName('tbody')[0];
table.innerHTML = "";
var i=0;
var rows = document.getElementById('month').value;
rows = parseInt(rows);
for(i=0; i<rows-1; i++) {
table.insertRow(-1).innerHTML = "<td>" + (i+1) + "</td><td>" + monthlyPaymentPlan(Sum, PrePayment, Percent, Month) + "</td>";
}
table.insertRow(-1).innerHTML = "<td>" + rows + "</td><td>" + lastMonth(Sum, PrePayment, Percent, Month) + "</td>";
}
You have need to update input variable value on change of id="month" so you can get updated value.
var Sum = '';
var PrePayment = '';
var Percent = '';
var Month = '';
function inputsval() {
Sum = parseInt(document.getElementById('price').value);
PrePayment = parseInt(document.getElementById('prepay').value);
Percent = parseInt(document.getElementById('percent').value);
Month = parseInt(document.getElementById('month').value);
}
function refactorTable(tbl_id) {
inputsval();
//Your other code.....
}
var Sum = parseInt(document.getElementById('price').value);
This is not defining a function, or a macro. This is a one-time calculation of a number, and it seems this is going to happen when the page starts up. So, it won't ever change from its first value (0).
You should probably move these declarations inside of refactorTable. Thankfully, you already have them set up to be passed as arguments.
I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code
<script>
function fillin(entire,name,id,key) {
if (entire.checked == true) {
var split_info = new Array();
split_info = name.split(":");
var div = $("#Inputfields"+id);
var till = (div.children("input").length)/4;
var current_count = 0;
for (var j=0;j<till;j++) {
if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") {
document.getElementById("insertname_"+j+"_"+id).value = split_info[0];
document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1];
break;
} else
current_count = current_count+1;
if (current_count == till) {
var x= addnew(id);
x =x+1;
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
document.getElementById("insertname_"+x+"_"+id).text = split_info[0];
//alert(document.getElementById("insertname_"+x+"_"+id).value);
//document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1];
}
}
} else {
}
}
</script>
<script>
function addnew(n) {
//var id = $(this).attr("id");
var div = $("#Inputfields"+n);
var howManyInputs = (div.children("input").length)/4;
alert(howManyInputs);
var val = $("div").data("addedCount");
var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">';
var fin = a+b+d+c;
$(fin).appendTo(div);
div.data("addedCount", div.data("addedCount") + 1);
return howManyInputs;
}
</script>
UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x
The problem is probably here:
document.getElementById("insertname_"+x+"_"+id).text
There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do:
document.getElementById("insertname_"+x+"_"+id).innerHTML = ...
or
$("#insertname_"+x+"_"+id).text(...);
Also, these lines:
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
.value there should be replaced with .val(), because those are jQuery objects.
I have reworked a lot of your code for a lot of reasons. Compare the two.
function fillin(entire, name, id, key) {
if (entire.checked) {
var split_info = [];
split_info = name.split(":");
var div = $("#Inputfields" + id);
var till = (div.children("input").length) / 4;
var current_count = 0;
var j = 0;
for (j = 0; j < till; j++) {
var myj = j + "_" + id;
if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") {
$("#insertname_" + myj).val(split_info[0]);
$("#insertnumber_" + myj).val(split_info[1]);
break;
} else {
current_count = current_count + 1;
}
if (current_count === till) {
var x = addnew(id) + 1;
div.find("#insertname_" + x + "_" + id).val(split_info[0]);
alert(div.find("#insertname_" + x + "_" + id).val());
$("#insertname_" + x + "_" + id).val(split_info[0]);
}
}
}
}
function addnew(n) {
var div = $("#Inputfields" + n);
var howManyInputs = (div.children("input").length) / 4;
alert(howManyInputs);
var myi = (howManyInputs) + '_' + n + '"';
var val = div.data("addedCount");
var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">';
var fin = a + b + d + c;
$(fin).appendTo(div);
div.data("addedCount", val + 1);
return howManyInputs;
}