Duplicating data (option) in a HTML select - javascript

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('');

Related

How to access values of Input in a List

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.

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] +"/";
}

Validating forms with JavaScript not working as expected

I have two problems one I can't get the Regex (for email) I created to fire properly when I add it to my logic. It seems to make the field which was fine (by entering correct input) invalidate when I tab away...
The second problem is the select dropdown. I am not sure what is the best practice but I essentially would like the select dropdown to remain with the error messages until either the user has selected a proper state.
This is my code:
var ValidationChecker = (function validationHndlr() {
'use strict';
var doc = document;
var form;
var emailRegExp;
var formElements;
emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
form = doc.getElementsByTagName('form')[0];
formElements = form.elements;
function addMultipleListeners(element, events, handler, useCapture, args) {
if (!(events instanceof Array)) {
throw 'addMultipleListeners: ' +
'please supply an array of eventstrings ' +
'(like ["click","mouseover"])';
}
//create a wrapper to be able to use additional arguments
var handlerFn = function(e) {
handler.apply(this, args && args instanceof Array ? args : []);
}
for (var i = 0; i < events.length - 1; i += 1) {
element.addEventListener(events[i], handlerFn, useCapture);
}
}
for (let i = 0, l = formElements.length; i < l; i++) {
var elId = doc.getElementById(formElements[i].id);
addMultipleListeners(elId, ['focus', 'blur', 'keyup'], function(e) {
if ((formElements[i].value == '') || (formElements[i].value == null) || ((formElements[i].type == 'email') != emailRegExp) ) {
formElements[i].classList.add('invalid-input');
formElements[i].nextElementSibling.style.display = 'block';
formElements[i].nextElementSibling.innerHTML = 'Not valid!';
}
}, false);
elId.addEventListener('keyup', function(e) {
console.log('keyup working?');
if ((formElements[i].value != '') && (formElements[i].value.length > 2)) {
formElements[i].classList.remove('invalid-input');
if (formElements[i].nextElementSibling.type !== 'submit') {
formElements[i].nextElementSibling.style.display = 'none'
}
}
}, false);
}
})();

database is catching wrong result from javascript

can anyone help me please? So I'm making a web app where a user can crack the vault code by clicking the numbers from 1-40. They are only allowed to click 6 sets of numbers for example "6", "20", "1", "40", "27", "15". So I have a data variable "guess" in my database with int(12) as the var numbers in this JS below. The problem is whenever I try "40", "39", "38", "37", "36", "35". The database will catch "2147483647" and I'm getting confused why, there must be something wrong in what I'm doing. I'm not really professional with JS and I'm just following some guides. This was working when I had the 0-9 numbers in the vault and int(6) in the data var "guess" inside the database. Please help, thank you!
var numbers = document.querySelectorAll('.number');
var screenSpans = document.querySelectorAll('#screen span');
var clear = document.getElementById('clear');
var enter = document.getElementById('enter');
var errorModal = document.getElementById('digitAmountAlert');
var currEmail = document.getElementById('currEmail').innerHTML.replace(/\s/g, '');
var lastModal = document.getElementById('lastModal');
var main = document.getElementById('main');
var guess = '';
var reset;
clear.addEventListener('click', function(){
reset = 0;
for (var i = screenSpans.length - 1; i >= 0; i--) {
if (screenSpans[i].innerHTML != '' && reset == 0){
screenSpans[i].innerHTML = '';
reset = 1;
}
};
});
enter.addEventListener('click', function(){
reset = 0;
for (var i = 0; i < screenSpans.length; i++) {
// Catch if they have not entered enough digits
if (screenSpans[i].innerHTML == ''){
errorModal.className = 'modal';
setTimeout(function(){
errorModal.className = 'modal hide';
}, 4000);
} else {
guess = guess+screenSpans[i].innerHTML;
if (guess.length == 12){
$.ajax({
url: "submit.php",
method: "POST",
data: { guess: guess, email: currEmail }
});
lastModal.className = 'modal';
main.className = 'hide';
}
}
};
guess = '';
});
for (var i = numbers.length - 1; i >= 0; i--) {
numbers[i].addEventListener('click', function(){
reset = 0;
nextSpan(this.innerHTML);
});
};
function nextSpan (currNumber){
for (var i = 0; i < screenSpans.length; i++) {
if (screenSpans[i].innerHTML == '' && reset == 0){
screenSpans[i].innerHTML = currNumber;
reset = 1;
}
};
}
/*
|---------------------------------------------------
| FORM SUBMIT CHECK
|---------------------------------------------------
*/
var submitButton = document.getElementById('startButton');
var form = document.getElementById('form');
var goAhead = true;
submitButton.addEventListener('click', function(){
var i, j, q = [];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].nodeName == "INPUT"){
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
var inputValue = encodeURIComponent(form.elements[i].value)
if ((inputValue == '' || inputValue == null) && (form.elements[i].name != 'online')){
// NOT COMPLETE
goAhead = false;
console.log(form.elements[i].name)
}
}
}
if (goAhead){
// SUBMIT
document.getElementById('form').submit();
} else {
this.innerHTML = "Please fill out all the fields & try again";
setTimeout(function(){
submitButton.innerHTML = "Let's Play!";
}, 7000);
goAhead = true;
}
});

how to reindex object start from 0

I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});

Categories

Resources