How to get parameter name as array? - javascript

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

Related

Set value of textfield with javascript

I am creating a Safari extension that autofill the email.
I managed to get this working but on some sites, the textfield appears to be filled in by the value, but when the website tries to get that value, it gets nothing.
For clarification, my code works on e.g. Facebook, Github, Stackoverflow,.. . But it doesn't work on e.g. developer.apple.com, www.back4app.com, Microsoft,.. .
I've tried to see what the autofill of keychain in safari does, and this shows met the the email actually get's filled in in the HTML tag. This doesn't happen with my code. But the email is always filled in in the textfield that you see on the webpage.
function handleMessage(event) {
var arguments = event.message;
var emailStr = arguments["Email"];
var nameInputs = document.getElementsByTagName('input');
for (var i = 0; i < nameInputs.length; i++) {
var theFieldName = nameInputs[i].name.toLowerCase();
var theFieldType = nameInputs[i].type.toLowerCase();
if (theFieldName.indexOf("email") !== -1) {
if (!(emailStr === undefined)) {
nameInputs[i].value = emailStr;
filledInEmail = 1;
}
}
else if (theFieldType.indexOf("email") !== -1) {
if (!(emailStr === undefined)) {
nameInputs[i].value = emailStr;
filledInEmail = 1;
}
}
}
}
I'm guessing those sites are listening to the input change event. Try this:
function handleMessage(event) {
var arguments = event.message;
var emailStr = arguments["Email"];
var nameInputs = document.getElementsByTagName('input');
for (var i = 0; i < nameInputs.length; i++) {
var theFieldName = nameInputs[i].name.toLowerCase();
var theFieldType = nameInputs[i].type.toLowerCase();
if (theFieldName.indexOf("email") !== -1) {
if (!(emailStr === undefined)) {
nameInputs[i].value = emailStr;
nameInputs[i].dispatchEvent(new Event('change'));//trigger change event
filledInEmail = 1;
}
}
else if (theFieldType.indexOf("email") !== -1) {
if (!(emailStr === undefined)) {
nameInputs[i].value = emailStr;
nameInputs[i].dispatchEvent(new Event('change'));//trigger change event
filledInEmail = 1;
}
}
}
}

Modal Form Submit Button Not Working When Clicked

I created a modal dropdown form with four dropdown lists, with the fourth dropdown containing a link to a document to display once user clicks the submit button. All four dropdowns work fine, however when clicking the submit button the document does not display. The form simply continues to display. Any help is appreciated.
var selectedOptions = {};
$('#link1').on('change', function () {
var a = $(this).val();
selectedOptions['1'] = a;
selectedOptions['2'] = a;
selectedOptions['3'] = a;
if (a !== '') {
for (var i = 0; i < dataSecondSelect[a].length; i++) {
$('#link2').append($("<option></option>")
.attr("value", dataSecondSelect[a][i])
.text(dataSecondSelect[a][i]));
}
}
});
$('#link2').on('change', function () {
var a = $(this).val();
selectedOptions['1'] = a;
selectedOptions['2'] = a;
selectedOptions['3'] = a;
if (a !== '') {
for (var i = 0; i < dataThirdSelect[a].length; i++) {
$('#link3').append($("<option></option>")
.attr("value", dataThirdSelect[a][i])
.text(dataThirdSelect[a][i]));
}
}
});
$('#link3').on('change', function () {
var a = $(this).val();
selectedOptions['1'] = a;
selectedOptions['2'] = a;
selectedOptions['3'] = a;
if (a !== '') {
for (var i = 0; i < dataFourthSelect[a].length; i++) {
$('#link4').append($("<option></option>")
.attr("value", dataFourthSelect[a][i].link)
.text(dataFourthSelect[a][i].form));
}
}
});
$('#clickButton').on('click', function () {
var error = false;
$(".error").remove();
$(".validation-error").removeClass('validation-error');
$('#myModal select').each(function () {
// validate first
if ($(this).val() === "") {
var _message = "Please select an option";
$(this).addClass('validation-error');
$(this).after($('<div class="error"></div>').text(_message));
error=true;
}
});
if (error) { return; }
// form is now validated so get the link
var _index = $("#link4").val();
var _form = dataFourthSelect[_index][0].link;
resetForm($(this)[0]);
$('#myModal').modal('hide');
openDoc(_form);
});
function resetForm(e) {
$(".error").remove();
$(".validation-error").removeClass('validation-error');
e.form.reset();
}
</script>
while going through your given code, i noticed the #link4 does not exists.
so the line var _index = $("#link4").val(); will return undefined which will subsequently fails the following line of code
var _form = dataFourthSelect[_index][0].link;
hope this helps.

How to use breakline for this code?

in my code i'm using onclick method for a button. when i click this button dynamically it shows multiple textboxes with remove button. all this process are successfully running. but all the textboxes are displaying continuously. i want to display one textbox per line. Where i have to add br tag or /n ?
This is 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);
}
}
});
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, 'WYPT',
input.inputId);
me.waypointIndex++;
}, false);
You should also append <br> tag after each <input>:
parentNode.appendChild(input);
parentNode.appendChild(removeInput);
parentNode.appendChild(document.createElement('br'));
Or it might be better to use <div> wrapper as Rajesh mentioned:
var wrapper = document.createElement('div');
parentNode.appendChild(wrapper);
wrapper.appendChild(input);
wrapper.appendChild(removeInput);

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

Sort only array elements JavaScript which has a CSS property

I want to create an unordered list. The order should be given by their id (Which is a number. The smallest is at the bottom.)
BUT if a certain li does not have a a CSS property (text-decoration:line-through in my case.) Then they should be at the bottom anyway.
I am trying to make a To Do list, where checked elements are at the bottom, but when you uncheck them, they jump back to place.
http://codepen.io/balazsorban44/pen/Gjzwbp
const inputArea = document.getElementById('todo-input');
const list = document.getElementById('tasks');
tasks = [];
function loaded() {
inputArea.focus();
}
function enter() {
if (event.keyCode == 13) {
addTask()
}
}
function refresh(array) {
var task = document.createElement('li');
const checkBox = document.createElement('input');
checkBox.setAttribute('type', 'checkbox');
checkBox.setAttribute('onclick', 'toggleCheckBox()');
task.appendChild(checkBox);
task.appendChild(document.createTextNode(array[array.length - 1].task));
task.id = array[array.length - 1].timestamp.getTime()
list.appendChild(task);
return list;
}
function addTask() {
if (inputArea.value != '') {
tasks.push({
timestamp: new Date(),
task: inputArea.value
});
inputArea.value = '';
inputArea.focus();
refresh(tasks);
doneOrUndone();
inputArea.placeholder = 'Click + or press Enter.'
} else {
inputArea.placeholder = 'Write something'
}
}
function doneOrUndone() {
var done = 0
const out = document.getElementById('out')
for (var i = 0; i < tasks.length; i++) {
if (document.getElementsByTagName('li')[i].style.textDecoration != '') {
done++
}
}
out.value = parseInt(done) + '/' + parseInt(tasks.length) + ':'
}
function toggleCheckBox() {
const task = event.target.parentNode
if (task.style.textDecoration == '') {
task.style.textDecoration = 'line-through';
list.appendChild(task)
doneOrUndone()
} else {
task.style.textDecoration = ''
for (var i = 0; i < tasks.length; i++) {
if (task.id < tasks[i].timestamp.getTime() && list.childNodes[0].style.textDecoration == 'line-through') {
if (task.id > list.childNodes[0].id) {
list.insertBefore(task, list.childNodes[0]);
break;
}
} else {
list.insertBefore(task, list.childNodes[i]);
break
}
}
doneOrUndone()
}
}
I think the real problem is that when setting style.textDecoration to line-through, the actual property that is set is textDecorationLine.
Your line if (task.style.textDecoration == '') is therefore always true.
You can replace textDecoration with textDecorationLine and it should work.
http://codepen.io/anon/pen/bwzzkP
The underlying cause of this problem is, in my opinion, that you're using an element's style attribute to monitor state. I'd advice to either:
Store state in javascript, or
Store state in a class, or
Store state in a custom data- attribute
For example:
const task = event.target.parentNode;
const isDone = task.getAttribute("data-done");
task.style.textDecoration = !isDone ? 'line-through' : '';
task.setAttribute("data-done", !isDone);

Categories

Resources