Needing to validate that user inputs date that is not before 2014 or after the current date. I tried splitting the date entry by "/" and then using parseInt to catch if the [2] spot was less than 2014 but it doesn't seem to work!
<!DOCTYPE HTML>
<html>
<head>
<style>
form {border-style: inset;
border-color: blue;
height: 360px;
width: 775px;
margin: auto;
}
</style>
<script>
//Declares 3 arrays
var fullNames = new Array(100);
var dates = new Array(100);
var opinions = new Array(100);
//Global variable
var numOfRatings = 0;
</script>
<script>
//Validates fields are not empty, date is correct then assigns data to arrays
function validateData()
{
var fullNameStr = document.getElementById("FullName").value;
var dateStr = document.getElementById("Date").value;
var opinionStr = document.getElementById("opinion").value;
if (!fullNameStr||!opinionStr||!dateStr) {
alert("Please complete all fields.");
return;
}
else {
var dateVal = dateStr;
var dateParts = dateVal.split("/");
if (parseInt(dateParts[2]) < "2014") {
alert("Invalid date!");
}
else {
fullNames[numOfRatings] = fullNameStr;
dates[numOfRatings] = dateStr;
opinions[numOfRatings] = opinionStr;
numOfRatings++;
document.getElementById("FullName").value = "";
document.getElementById("Date").value = "";
document.getElementById("opinion").value = "";
}
}
}
</script>
<script>
//Displays data held in arrays
function displayData()
{
var col;
var pos;
document.getElementById("list").value = "FULL NAME DATE RATING\n";
for (pos = 0; pos < numOfRatings; pos++)
{
document.getElementById("list").value += fullNames[pos];
for (col = fullNames[pos].length; col <= 25; col++)
document.getElementById("list").value += " ";
document.getElementById("list").value += dates[pos];
for (col = dates[pos].length; col <= 15; col++)
document.getElementById("list").value += " ";
document.getElementById("list").value += opinions[pos]+ "\n";
}
}
</script>
<script>
//Clears form
function clearData()
{
var pos;
for (pos = 0; pos < numOfRatings; pos++)
{
fullNames[pos] = "";
dates[pos] = "";
opinions[pos] = "";
}
numOfRatings = 0;
}
</script>
</head>
<h1 style ="text-align:center; border-bottom:1px solid #999999">Internet Technologies Membership</h1>
<form name ="ratingForm">
<table cellpadding="10">
<td>
<tr>
<td>Full Name:</td>
<td><input type="text" id="FullName" name="FullName"></td>
<td>Date:</td>
<td><input type="date" id="Date" name="Date"></td>
<td>Opinion:</td>
<td>
<select name="opinion" id="opinion">
<option value="★★★★★">Excellent</option>
<option value="★★★★">Very Good</option>
<option value="★★★">Good</option>
<option value="★★">Fair</option>
<option value="★">Poor</option>
<option value="0">Very Bad</option>
</select>
</td>
</tr>
</table>
<br>
<center>
<textarea name="list" id="list" rows="10" cols="100">
</textarea>
<br>
<br>
<input type="button" value="RATE" onClick="validateData();">
<input type="button" value="DISPLAY" onClick="displayData();">
<input type="reset" value="CLEAR" onClick="clearData();">
<br>
</center>
</form>
</html>
The date will be retrieved in YYYY-MM-DD format irrespective of what is displayed in the input box.
Try to split it by hyphen (-).
Also while comparing use 2014 as a number instead of string
var dateParts = dateVal.split("-");
if (parseInt(dateParts[0]) < 2014)
if (parseInt(dateParts[2]) < "2014") {
The above part of code is checking the dateParts[2] (an Int) with a string.
You have to make the "2014" part as an Integer too.
So the above line should be
if (parseInt(dateParts[2]) < 2014) {
Also I would suggest using MomentJS for any DateTime related functionality.
Related
I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.
I have a textbox where users input the owner's name and I want to copy it automatically or on button click on a textbox inside my dynamic table. How can I possibly do it using javascript? I needed the exact copy of the inputted value on the first textbox to be the value of the textbox inside the dynamic table. Please help
window.onload = function() {
var ModelArray = {
"Mammals": {
"Dog": {
"Dog Food": ["Milk"]
},
"Cat": {
"Cat food": ["Milk"]
},
"Tiger": {
"Meat": ["Water"]
},
"Monkey": {
"Banana": ["Water"]
}
},
"Reptiles": {
"Snake": {
"Rat": ["None"]
},
"Turtle": {
"Plant": ["Water"]
},
"Lizard": {
"Insects": ["None"]
},
"Crocodile": {
"Meat": ["Water"]
}
}
}
//Get html elements
var model = document.getElementById("MODEL");
var destination = document.getElementById("destination");
var criteria = document.getElementById("criteria");
var material_form = document.getElementById("material_form");
//load models
for (var model_value in ModelArray) {
model.options[model.options.length] = new Option(model_value, model_value);
}
//model changed -> destination value
model.onchange = function() {
destination.length = 1;
criteria.length = 1;
material_form.length = 1;
if (this.selectedIndex < 1) {
criteria.options[0].text = ""
return;
}
destination.options[0].text = "Select Animal..."
for (var destination_value in ModelArray[this.value]) {
destination.options[destination.options.length] = new Option(destination_value, destination_value);
}
if (destination.options.length == 2) {
destination.selectedIndex = 1;
destination.onchange();
}
}
//destination changed -> criteria value
model.onchange();
destination.onchange = function() {
criteria.length = 1;
material_form.length = 1;
if (this.selectedIndex < 1) {
criteria.options[0].text = ""
return;
}
criteria.options[0].text = ""
for (var criteria_value in ModelArray[model.value][this.value]) {
criteria.options[criteria.options.length] = new Option(criteria_value, criteria_value);
}
if (criteria.options.length == 2) {
criteria.selectedIndex = 1;
criteria.onchange();
}
}
//criteria changed -> material form value
criteria.onchange = function() {
material_form.length = 1;
if (this.selectedIndex < 1) {
material_form.options[0].text = ""
return;
}
material_form.options[0].text = ""
var material_form_value = ModelArray[model.value][destination.value][this.value];
for (var i = 0; i < material_form_value.length; i++) {
material_form.options[material_form.options.length] = new Option(material_form_value[i], material_form_value[i]);
}
if (material_form.options.length == 2) {
material_form.selectedIndex = 1;
// material_form.onchange();
}
}
}
function SaveData() {
var DataList = [];
var table = document.getElementById("bod");
var rowLength = table.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = table.rows.item(i).cells;
//gets amount of cells of current row
//var cellLength = oCells.length-2;
//loops through each cell in current row
var item = {};
item["destination"] = oCells.item(0).innerHTML;
item["criteria"] = oCells.item(1).innerHTML;
item["material"] = oCells.item(2).innerHTML;
DataList.push(item)
}
var request = new XMLHttpRequest()
request.open("POST", "DOM_SAVE.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(JSON.stringify(DataList));
console.log(DataList);
}
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = destination.value;
row.insertCell(1).innerHTML = criteria.value;
row.insertCell(2).innerHTML = material_form.value;
row.insertCell(3).innerHTML = '<input type ="button" value="Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(4).innerHTML = '<input type ="text" name = "owner">';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
Owner: <input type="text" name="field10" id="field10" readonly="true" />
<td><b>MODEL: </b></td>
<td>
<select id="MODEL" NAME="MODEL" size="1" required>
<option value="" selected="selected">Select Model...</option>
</select>
</td>
<b>DESTINATION: </b></td>
<tr>
<td>
<select ID="destination" NAME="destination[]" required>
<option value="" selected="selected">Select Model First...</option>
</select>
<select ID="criteria" NAME="criteria[]" contenteditable="true" required>
</select>
<select ID="material_form" NAME="material_form[]" required>
</select>
<input type="button" id="add" value="Add Destination" onclick="Javascript:addRow()">
</td>
</tr>
</center>
<div id="mydata" style="text-align: center">
<center>
<table id="myTableData" border="1" style="text-align:center;"><br>
<thead>
<tr>
<td style="padding: 0 10px 0 10px"><b>DESTINATION</b></td>
<td style="padding: 0 10px 0 10px"><b>CRITERIA</b></td>
<td style="padding: 0 10px 0 10px"><b>MATERIAL FORM</b></td>
<td style="padding: 0 10px 0 10px"><b>.............</b></td>
<td style="padding: 0 10px 0 10px"><b>Owner Name</b></td>
</tr>
</center>
</thead>
<tbody id="bod">
</tbody>
</table>
</div><br>
<center>
<input type="submit" name="submit" value="Submit">
Yes you can. I know the question is dated, but hope it will help future searchers.
Using javascript you can copy value from one textbox to another:
HTML:
<input type='text' onblur="sync()" id='from'/>
<input type='text' id='to'/>
Javascript
<script type="text/javascript">
function sync() {
src = document.getElementById("from");
dest = document.getElementById("to");
dest.value = src.value;
}
</script>
I'm trying to create this form where I can have a button which will add a duplicate, and a button that will delete the current 'new form'. All functionality is working aside from the removal of the form-- I'm trying to use JQuery's .remove function but this error began presenting itself as soon as I added it.
I'm almost 100% certain that all parentheses/brackets are aligned-- I ran it through several linting sites to make sure.
Any ideas from looking at the javascript portion of the code?
<!DOCTYPE html>
<html>
<head>
<title>Add a New Course</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.buttonHolder {
text-align: center;
}
</style>
</head>
<body onload="loadXMLDoc_makeCatArray()">
<form action="" id="courseForm">
<div class = "div1">
<fieldset>
<legend>Enter course info:</legend>
Course title: <br>
<input type="text" id="displayName1" value=""><br>
Category: <br>
<select name="categoryDropdown" id="category1"></select><br>
Duration: <br>
<input type="time" id="duration1" value=""><br>
Subcategory: <br>
<input type="text" id="subcategory1" value=""><br>
Description: <br>
<textarea rows="4" cols="60" id="description1"></textarea><br>
URL: <br>
<input type="text" id="url1" value=""><br>
ID: <br>
<input type="text" id="id1" value=""><br>
Table ID: <br>
<input type="text" id="tableId1" value=""><br>
<div class="buttonHolder">
<input type="button" value="Submit All" onclick="javascript: loadXMLDoc();">
<input type="button" value="New Course" onclick="javascript: addCourseForm();">
</div>
</fieldset>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/vkbeautify.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/MicrosoftAjaxCore.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="https://unpkg.com/sharepointplus#5.1.0/sharepointplus-5.1.js"></script>
<script>
//Initialize the number of forms being submitted as 1
var count = 1;
function addCourseForm()
{
//Get the course form element
var course = document.getElementById("courseForm");
//Error checking here, making sure we got courseForm
if (course)
{
//Create a new <div> element which contains the form
var newDiv = document.createElement("div");
newDiv.className = "div" + (count + 1);
var divName = "div" + (count + 1);
newDiv.innerHTML = '<fieldset> <legend>Enter course info:</legend> Course title: <br> <input type="text" id="courseTitle' + (count + 1) + '"><br> Category: <br> <select name="categoryDropdown" id="category' + (count + 1) + '" value=""></select><br> Duration: <br> <input type="time" id="duration' + (count + 1) + '" value=""><br> Subcategory: <br> <input type="text" id="subcategory' + (count + 1) + '" value=""><br> Description: <br> <textarea rows="4" cols="60" id="description' + (count + 1) + '"></textarea><br> URL: <br><input type="text" id="url' + (count + 1) + '" value=""><br> <div class="buttonHolder"> <input type="button" value="Submit All" onclick="javascript: loadXMLDoc();"> <input type="button" value="New Course" onclick="javascript: addCourseForm();"> <input type="button" value="Remove Course" onclick="removeCourseForm(' + divName + ');"> </div> </fieldset>';
//Appends the new <p> element to the other forms
course.appendChild(newDiv);
//Add one to the number of forms being submitted
count++;
loadXMLDoc_makeCatArray();
}
}
function removeCourseForm(paragraph) {
$("." + paragraph).remove();
count--;
}
function loadXMLDoc_submitFormData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
submitFormData(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/curriculumdata.xml", true);
xmlhttp.send();
}
function submitFormData(xml)
{
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
for (var x = 1; x <= count; x ++) {
var p = xmlDoc.getElementsByTagName("course")[1];
var p_prime = p.cloneNode(false);
xmlDoc.getElementsByTagName("curriculumdata")[0].appendChild(p_prime);
var br = xmlDoc.createElement("br");
var elements = ["category", "description", "displayName", "duration", "id", "subcategory", "tableId", "url"];
for (var y = 0; y < elements.length; y++){
console.log(elements[y] + x);
newElement = xmlDoc.createElement(elements[y]);
if (y == 0) {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).text);
} else {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).value);
}
newElement.appendChild(newText);
console.log(newElement);
xmlDoc.getElementsByTagName("course")[xmlDoc.getElementsByTagName("course").length - 1].appendChild(newElement);
}
};
var clientContext = new SP.ClientContext('https://splm.sharepoint.com/sites/OCB');
var oList = clientContext.get_web().get_lists().getByTitle('Course List');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
var documents = new XMLSerializer().serializeToString(xmlDoc.documentElement);
documents = vkbeautify.xml(documents);
oListItem.set_item('xml_data', documents);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
};
function onQuerySucceeded() {
alert('Course successfully added');
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function loadXMLDoc_makeCatArray() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
catArray(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/curriculumdata.xml", true);
xmlhttp.send();
}
function catArray(xml){
eleArray = [];
var xmlDoc = xml.responseXML;
ele = xmlDoc.getElementsByTagName("course");
for (i = 0; i < ele.length; i++) {
if(!(eleArray.includes(ele[i].getElementsByTagName("category")[0].childNodes[0].nodeValue))){
eleArray.push(ele[i].getElementsByTagName("category")[0].childNodes[0].nodeValue);
}
}
var sel = document.getElementsByName('categoryDropdown')[count - 1];
for(var i = 0; i < eleArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = eleArray[i];
opt.value = eleArray[i];
console.log(opt);
sel.appendChild(opt);
}
};
</script>
</body>
</html>
First, your HTML is not valid because you cannot have anything after </body> except </html>. All that scripting should be moved to just before the closing body tag. Additionally, it's invalid to nest a fieldset in a p. You could make that p a div.
Next, count --; needs to be count--;
The unexpected input is the space after the count variable reference.
And your manually built HTML string needs to be looked at because you have nested double quotes in double quotes and you are concatenating nothing after count:
onclick="javascript: removeCourseForm("p' + count + '");">
This would also result in the same error because you have a trailing + but then nothing to concatenate it to.
Having said that....You really shouldn't be taking this approach in the first place.
Instead of creating an huge string of concatenated HTML (which is where your issue lies), just clone the first fieldset. Now, because we're going to clone, we want to get away from using id attributes and instead use .querySelector() and .querySelectorAll() to find elements based on CSS selectors.
You also should stop using .getElementsByTagName() because it has performance impact and you aren't interested in the collection that it returns anyway, you are passing an index to the collection. Instead use .querySelector().
Lastly, don't use inline event handlers (onclick). Do you event binding in JavaScript.
See the comments below.
Here's a working example.
<!DOCTYPE html>
<html>
<head>
<title>Add a New Course</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.buttonHolder {
text-align: center;
}
</style>
</head>
<body>
<form action="" id="courseForm">
<fieldset>
<legend>Enter course info:</legend>
Course title:
<br>
<input type="text" class="displayName">
<br> Category:
<br>
<select name="categoryDropdown" class="category"></select>
<br> Duration:
<br>
<input type="time" class="duration">
<br> Subcategory:
<br>
<input type="text" class="subcategory">
<br> Description:
<br>
<textarea rows="4" cols="60" class="description"></textarea>
<br> URL:
<br>
<input type="text" id="url1">
<br> ID:
<br>
<input type="text" id="id1">
<br> Table ID:
<br>
<input type="text" id="tableId1">
<br>
<div class="buttonHolder">
<input type="button" value="Submit All" class="submitAll">
<input type="button" value="New Course" class="newCourse">
</div>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/vkbeautify.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/MicrosoftAjaxCore.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="https://unpkg.com/sharepointplus#5.1.0/sharepointplus-5.1.js"></script>
<script>
//Get the course form element
var course = document.getElementById("courseForm");
document.querySelector(".submitAll").addEventListener("click", loadXMLDoc_submitFormData);
document.querySelector(".newCourse").addEventListener("click", addCourseForm);
function addCourseForm() {
var firstFS = document.querySelector("fieldset");
//Error checking here, making sure we got courseForm
if (course) {
// >>> **** Clone the current fieldset ***** <<<<
var newFS = firstFS.cloneNode(true);
// Create and configure remove button
var removeBtn = document.createElement("button");
removeBtn.textContent = "Remove Course";
removeBtn.type = "button";
removeBtn.addEventListener("click", function() {
// Call the remove function but pass the fieldset
// that this button is part of
removeCourseForm(this.closest("fieldset"));
});
// Append the new button to the new fieldset
newFS.querySelector("div.buttonHolder").appendChild(removeBtn);
//Appends the new <p> element to the other forms
course.appendChild(newFS);
// ***********************************************
loadXMLDoc_makeCatArray();
}
}
function removeCourseForm(fs) {
fs.remove();
}
function loadXMLDoc_submitFormData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
submitFormData(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/curriculumdata.xml", true);
xmlhttp.send();
}
function submitFormData(xml) {
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
for (var x = 1; x <= count; x++) {
var p = xmlDoc.getElementsByTagName("course")[1];
var p_prime = p.cloneNode(false);
xmlDoc.querySelector("curriculumdata").appendChild(p_prime);
var br = xmlDoc.createElement("br");
var elements = ["category", "description", "displayName", "duration", "id", "subcategory", "tableId", "url"];
for (var y = 0; y < elements.length; y++) {
console.log(elements[y] + x);
newElement = xmlDoc.createElement(elements[y]);
if (y == 0) {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).text);
} else {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).value);
}
newElement.appendChild(newText);
console.log(newElement);
xmlDoc.querySelectorAll("course")[xmlDoc.getElementsByTagName("course").length - 1].appendChild(newElement);
}
};
var clientContext = new SP.ClientContext('https://splm.sharepoint.com/sites/OCB');
var oList = clientContext.get_web().get_lists().getByTitle('Course List');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
var documents = new XMLSerializer().serializeToString(xmlDoc.documentElement);
documents = vkbeautify.xml(documents);
oListItem.set_item('xml_data', documents);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
};
function onQuerySucceeded() {
alert('Course successfully added');
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function loadXMLDoc_makeCatArray() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
catArray(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/curriculumdata.xml", true);
xmlhttp.send();
}
function catArray(xml) {
eleArray = [];
var xmlDoc = xml.responseXML;
ele = xmlDoc.getElementsByTagName("course");
for (i = 0; i < ele.length; i++) {
if (!(eleArray.includes(ele[i].querySelector("category").childNodes[0].nodeValue))) {
eleArray.push(ele[i].querySelector("category").childNodes[0].nodeValue);
}
}
var sel = document.querySelector('categoryDropdown')[count - 1];
for (var i = 0; i < eleArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = eleArray[i];
opt.value = eleArray[i];
console.log(opt);
sel.appendChild(opt);
}
};
loadXMLDoc_makeCatArray();
</script>
</body>
</html>
So I ended up fixing this problem rather simply:
I called the function removeCourseForm() without any parameters, and then generated the div name inside of that function.
function removeCourseForm() {
var divName = "div" + count;
$("." + divName).remove();
count--;
}
This seems to have remedied the whole issue and it works nicely now :)
I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>