How to access values of Input in a List - javascript

For my Project I need to have a site, which can generate a custom amount of Inputs, which will become buttons in another page.
And I need the values for the Input in order to Label the Buttons correctly.
HTML
<h2>settings:</h2>
<p>Add Amount of Checks:</p>
<input id="NumOfButtons"
name="NumOfButtons"
pattern=""
size="30"
spellcheck="false"
title="Amount of Checks"
value="">
<script>
let input = document.getElementById("NumOfButtons");
let listTA = new Array;
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
var x = parseInt(document.getElementById("NumOfButtons").value);
listTA = new Array(x);
for (let i = 0; i < x; ++i) {
var textarea = document.createElement("input");
textarea.name = "input";
textarea.maxLength = "100";
textarea.id = "TextAreaID"
listTA[i] = textarea;
document.getElementById("Buttons").appendChild(textarea);
}
}
});
</script>
<div id="Buttons">
<br />
<button onclick="sendDataAndGoToKontrolle()">save & continue</button>
<p>Reset F5</p>
</div>
<script>
function sendDataAndGoToKontrolle() {
var filtered;
if (listTA != null) {
let x = new Array;
for (let i = 0; i < listTA.length; ++i) x[i] = listTA[i].document.getElementById("TextAreaID").value;
if (!(x.length === 0)) {
for (let i = 0; i < x.length; ++i) {
if (x[i] === null) {
var filtered = x.filter(function (el) { return el != null; });
console.log("TextAreas filtered!")
} else console.log("Nothing to filter!")
}
} else console.log("Nothin written in TextAreas!");
} else console.log("No TextArea created!");
if (!(filtered === null)) {
//Send Prüfungen to Controller
$.ajax({
url: "#Url.Action("NewIDSettingsPage")",
type: "GET",
data: { Prüfungen: filtered },
success: function () {
console.log("Successfully sent!");
//window.location.href = '/home/NewIDSettingsPage';
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log("ERROR: " + errorMessage);}});
} else console.log("ERROR");
}
</script>
The result should be a list/Array of string(values of the Inputs).
If you need any further information, please write a Comment and I will look to reply quickly.

Do not give all the input elements the same id. textarea.id = "TextAreaID" is wrong.
If you want to group the inputs together you should set the class:
textarea.className = "TextAreaClass"
Or if you want to give each one an id, append i to the id to make it unique:
textarea.id = "TextAreaID"+i;
When trying to get the values of your inputs you have the following:
x[i] = listTA[i].document.getElementById("TextAreaID").value;
Which doesn't make a lot of sense. What you should probably be doing is:
x[i] = listTA[i].value;
Because you have stored the element in the array, you don't need to get the element from the document.

Related

How to get parameter name as array?

in my code i'm using google map api. here i used onclick method for button. if i clicked that dynamically it shows multiple textboxes. here i enter values for all text fields. But when i passing the parameter name into servlet page it takes only the first value of text box. how to get all the values?
My code
var button = document.getElementById('waypoint-input');
button.addEventListener("click", function () {
var parentNode = document.getElementById('waypoints-list');
var input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Enter a waypoint location';
input.id = 'waypoint' + me.waypointIndex;
input.inputId = me.waypointIndex;
**input.name = 'waypointlist';**
input.addEventListener('input', function () {
if (input.value == "") {
var waypoint = me.waypts.filter(function (obj) {
return obj.key === input.inputId;
})[0];
if (waypoint != null && typeof waypoint !== "undefined") {
var waypointIndexToRemove = me.waypts.map(function (el) {
return el.key;
}).indexOf(input.inputId);
me.waypts.splice(waypointIndexToRemove, 1);
me.route();
}
}
});
var removeInput = document.createElement('button');
removeInput.innerHTML = 'Remove';
removeInput.onclick = function () {
parentNode.removeChild(input);
parentNode.removeChild(removeInput);
var childInputs = parentNode.getElementsByTagName('input');
if (childInputs.length > 0) {
for (var i = 0; i < childInputs.length; i++) {
childInputs[i].inputId = i;
}
}
if (input.value != "" && input.value != null) {
var waypointIndexToRemove = me.waypts.map(function (el) {
return el.key;
}).indexOf(input.inputId);
me.waypts.splice(waypointIndexToRemove, 1);
for (var i = input.inputId; i < me.waypts.length; i++) {
me.waypts[i].key = me.waypts[i].key - 1;
}
me.route();
}
me.waypointIndex--;
}
parentNode.appendChild(input);
parentNode.appendChild(removeInput);
var waypointAutocomplete = new google.maps.places.Autocomplete(input, { placeIdOnly: true });
me.setupPlaceChangedListener(waypointAutocomplete, 'WAYPOINT', input.inputId);
me.waypointIndex++;
}, false);
I found the solution to my question.
There is no changes to my script. I simply call the parameter name in servlet page. The name is waypointlist. And I change my servlet code little bit.
That is
String[] waypointlist=request.getParameterValues("waypointlist");
String waypointarray="";
for(int i=0;i<waypointlist.length;i++)
{
waypointarray += waypointlist[i] +"/";
}

How do I set a javascript variable inside a for loop to be used afterwards

So, I'm creating a login form, and when certain criteria aren't met to continue after the form, I am setting a variable to be tested after I've tested all the criteria. IF that variable ($cantcontinue) is set to 'true' I want to send a console message with the criteria that isn't met. Here is my code:
function testfields() {
// Ask if logging in or Creating Account
//Logging In:
if (document.getElementById("tEmail").style.display != "unset") {
var loginelements = ["Username", "Password"];
var text = "";
var i;
for (i = 0; i < loginelements.length; i++) {
//Check all fields are full:
if (document.getElementById(loginelements[i]).value == "") {
document.getElementById(loginelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(loginelements[i] + " is not set,")
} else {
document.getElementById(loginelements[i]).style.background = '#f7f7f7'
}
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
//Create a new Account:
} else {
var createelements = ["Username", "Password", "tEmaili", "tConfirmi"];
var text = "";
var i;
for (i = 0; i < createelements.length; i++) {
//Check all fields are full:
if (document.getElementById(createelements[i]).value == "") {
document.getElementById(createelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(createelements[i] + " is not set,")
} else {
document.getElementById(createelements[i]).style.background = '#f7f7f7'
}
}
//If passwords Match
if (document.getElementById("Password").value != document.getElementById("tConfirmi").value) {
var cantcontinue = true;
document.getElementById("tConfirmi").style.background = '#ff6060'
document.getElementById("tConfirmi").value = ''
console.log(" Passwords didn't Match,");
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
}
}
$cantcontinue !== cantcontinue;//....
Also
if (cantcontinue != true) {
equals:
if (!cantcontinue) {
Sidenote: Please don't use "$" unless you're using jQuery. It reminds me of PHP ( brrrrr...)

Duplicating data (option) in a HTML select

I have a text box that is used to search for data in a database (Order Number). The data returned (Products) is then added into a select as an option. The data is then removed from select when the user changes the data in the text box.
The functionality of this is somewhat working as I wanted, however I am having the options duplicated and not all of the options are removed.
I am unsure to where I am going wrong within the code, and would appreciate some guidance.
$(document).ready(function() {
$('#order_number').on('keyup', function(e) {
var myCustomer = document.getElementById('customer');
myCustomer.value = "";
var mySelect = document.getElementById('product');
var products_from_query = '';
var code = (e.keyCode || e.which);
// do nothing if it's an arrow key
if (code == 37 || code == 38 || code == 39 || code == 40) {
return;
}
var keyword = $('#order_number').val();
if (keyword.length) {
$.ajax( {
url: '../stocks/order_search',
type: 'GET',
dataType: 'json',
data: "keyword=" + keyword,
success: function(data) {
var length = mySelect.options.length;
for (i = 0; i < length; i++) {
mySelect.options[i] = null;
}
for (var i = 0; i < data.length; i++) {
newOption = document.createElement('option');
newOption.value = data[i]['ProductName'];
var options_seperator = ' - ';
var options_product_name = data[i]['ProductName'];
var options_product_description = data[i]['ProductDescription'];
var options_data = options_product_name.concat(options_seperator).concat(options_product_description);
if (typeof newOption.textContent === 'undefined') {
newOption.innerText = options_data;
} else {
newOption.textContent = options_data;
}
mySelect.appendChild(newOption);
};
myCustomer.value = data[0]['Customer'];
}
})
}
});
});
You need to add following one line before ajax call.
mySelect.html('');

removing eventhandler seems not to work

I have the next code (code does not run like copied here) that I would like to use for addressing errors on an input field of a form. The field is checked when the focus of the field is lost. An ajax request checks if the entry is allowed for that field (based on a lookup table). The two user functions set and remove error class around the input field.
When an error occurs, I want the field in error to have the only focus of the whole form (user has to correct this field before a different field is selected).
That last requirement does not work in the code. The focus is handed intermitted to the fields. It seems like if I have to click more then needed as well.
Question: What am I doing wrong?
$(document).ready(function() {
var errors = [];
//check value in lookup table with ajax
$("body").on("blur", "input[data-table]", function() {
var name = $(this).attr("id");
var table = $("input[name=" + name + "]").data().table;
var value = $(this).val();
var len = value.length;
//Only if an entry has been made in the field
if (len > 0) {
var jqxhr = $.post("/controller/lookup.php", {
table: table,
value: value
}, function() {});
//Done with the request
jqxhr.done(function(data) {
var e = JSON.parse(data).error;
if (e == "true") {
//set error
setError(name);
//prevent focus on other
$("body").on("click", "input", function(e) {
if (!(e.target.id == name))
$("input#" + name).focus();
});
} else {
removeError(name);
$("body").off("click", "input");
}
});
//A failure has occured
jqxhr.fails(function(xhr, msg) {
//TODO: exception handling
});
}
//if the field has been cleared remove error
removeError(name);
});
function setError(name) {
//Check if error already exists
if (!getErrors(name)) {
var e = getErrorIndex(name);
if (e > -1) errors[e].error = true;
else errors.push({
name: name,
error: true
});
var span = "<span class=\"glyphicon glyphicon-exclamation-sign\" style=\"color: red; float: left\"></span>";
//Decorate errors
$("input#" + name).parent().addClass("has-error");
$("input#" + name).after(span);
};
}
function removeError(name) {
var e = getErrorIndex(name);
if (e > -1) {
errors[e].error = false;
$("input#" + name).parent().removeClass("has-error");
$("input#" + name).next().remove();
}
}
function getErrors(needle) {
for (var i = 0; i < errors.length; i++) {
if (errors[i].name === needle) return errors[i].error;
}
return false;
}
function getErrorIndex(needle) {
for (var i = 0; i < errors.length; i++) {
if (errors[i].name === needle) return i;
}
return -1;
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Retrieving rich text box sharepoint in javascript

I have CustomNewForm for inserting items in the sharepoint list.
The fields are "Reason" and "Reason OverView"; both Multiple Line Rich Text fields. I need to copy some text from "Reason" to "Reason Overview".(A substring)
I tried to get this done with workflow but couldn't find a solution to get a substring of a form field.
I am trying to get the value from "Reason" field in javascript; but unable to do so.
MY CODE :: (not working)
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
alert('Hi');
Original.innerHTML=Reason.innerHTML;
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>
Any way to get this done??
I solved it using this
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
var reasonText = RTE_GetEditorDocument(Reason.id);
var reasonOverviewText = reasonText.body.innerText;
if(reasonOverviewText.length>=20)
{
reasonOverviewText = reasonOverviewText.substring(0,20)+'......';
Original.innerText = reasonOverviewText;
}
else
{
Original.innerText = reasonOverviewText;
}
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>

Categories

Resources