Using action in Javascript to submit form - javascript

I'm trying to submit a form using javascript. This is the code I've used to set the action to the form and then submit it. These 2 lines are in the onclick method defined for a button.
document.form1.action = fin_string;
document.forms["form1"].submit();
The problem here is that the fin_string gets replaced by something else when I do this. For eg. when fin_string = "http://www.gmail.com" this works, however when I keep fin_string as some other string (relative to the current path with attached parameters) it gets changed. alert(fin_string), shows the string correctly but when I use the string to set the action on the form and submit it, it gets changed.
This is what I want the fin_string to be (relative to the current path)
remote-service/FeedMergerManualTrigger?locales=en_GB-en_SG&deleteOutputFile=Y&localFilePath=c:/go/
but this is what the browser goes to when I assign it an action and submit the form.
remote-service/FeedMergerManualTrigger?LMN=UK&ZJ=SG&localResourcesMode=on&EUPath=c:/go/&delete_op=Y.
Any idea what's going on?

Have such code instead, it will assign hidden form elements instead of adding to the query string thus it won't get changed:
var fin_string = "remote-service/FeedMergerManualTrigger";
var arrData = {"locales": "en_GB-en_SG", "deleteOutputFile": "Y", "localFilePath": "c:/go/"};
var oForm = document.forms["form1"];
oForm.action = fin_string;
for (var key in arrData)
AddOrUpdate(oForm, key, arrData[key]);
//encodeURIComponent(arrData[key])
oForm.submit();
function AddOrUpdate(oForm, sName, sValue) {
var oInput = oForm.elements[sName];
if (!oInput) {
oInput = document.createElement("input");
oInput.type = "hidden";
oInput.name = sName;
oForm.appendChild(oInput);
}
oInput.value = sValue;
}

Related

USB Barcode scanner repeat scans without server call

Not sure if my terminology is correct on all of this. I know my code is not efficient either. Looking for functional over efficiency at this point. (just a teacher trying to solve logistical issues).
I have a webapp that we use to check students into and out of the library. Because of COVID, we are trying to touch the keyboard less and have a faster check-in process. To do this, we have a USB scanner that will scan student IDs.
My Webapp loads template html and then adds names etc to the different select elements. When a student checks in, the name appears on the other half of the window and waits for them to click the checkout next to their name. I believe this is done on what is called client side.
To add the barcode scanner, I added a form element with a text input. Is this the only way to have the barcode scanner interact with the client side?
<form><input type="text" id = "barcodeInput" size="1"></form>
I then have some jQuery that tests to see that the input is a barcode (Prefix and return key pressed), if so, the student ID number from the barcode is then put through a loop to find the matching id in the select options of student names (ids are stored in the values and student names are stored in the text). Default action is also prevented here
All of this works and I can get 1 student to add to the "checked in" panel of my app.
I cannot get the scanner to work on a second student. I think this has to do with the fact that I'm using the form input element and that might require a server call but I cannot do that since I need to have a growing list of students who are checked into the library.
I borrowed this and am currently using
$(document).ready(function() {
var barcode=""; //sets my variable
$(document).keydown(function(e) //looking to intercept the barcode scanner output
{
var code = (e.keyCode ? e.keyCode : e.which); //don't really know what this does since I borrowed this
if(code==13&&(barcode.substring(1,5)=="SCAN"))// Enter key hit & from scanner
{
e.preventDefault(); //stops the enter key from actually "running" and stops the barcode from going into the input field (I think)
barcode = barcode.slice(5);// remove the prefix so I am left with student number aka barcode
alert(barcode); //lets me know I'm getting the correct student number
processBarcode(barcode); //sends to process barcode
}
else if(code==9)// Tab key hit //I may not need these next 10ish lines
{
e.preventDefault();
alert(barcode);
}
else
{
e.preventDefault();
barcode=barcode+String.fromCharCode(code);
}
});
});
This find the student in the select element and then changes the select element to read that name and also posts the name on the "Who is checking in" Table cell
function processBarcode(barcode){
var name = "";
$("#studentNameSelect option").each(function(){ //runs through the select element that has all student names...the name is in the parameter "text" and student ID # is in the parameter val
if($(this).val()==barcode){ //looking to see if the student ID # matches the specific option in the select element
name = $(this).text(); //figure out the student name based on ID #
$(this).prop('selected', true); //set the select element to show this specific option
$("#selectedName").html(name); //puts student name in a table cell so they know they are picking the correct name
//$("#barcodeInput").trigger("reset"); //here I'm trying to get the form element input to reset so I can use it again...this didn't work so its commented out
$("#teacherNameSelect").focus(); //puts the focus onto the next select item so I can do other things
return false; //breaks the each loop once student name has been found
}
});
}
And then this is the code that moves the name onto the "checked in" panel so that the next student can check in
function buildAttendanceRow(stringPackage){ //this function takes info from the selection panel and builds a table row in the "I'm at the library" panel. Students click check out when they leave the library
console.log(stringPackage);
var package = JSON.parse(stringPackage); //receives a package of info from the selects, I do send this to a server function to email teachers that student arrived to the library...
console.log(package);
var html = "";
var hiddenId = new Date().getTime().toString(); //this cell is used to keep track of a specific instance of a student checked into the library so I can remove later and then mark in a backend spreadsheet database
var nameCell = '<td class="package" id="'+hiddenId+'">'+package.student+'</td>';
var checkOutButton = '<input type="button" value="Check Out" id="COButton">';
var checkoutButtonCell = '<td class="center">'+checkOutButton+'</td>';
html+="<tr>"+nameCell+checkoutButtonCell+"</tr>";
$("#checkedInTable").append(html); //puts the new table row into the checked in table
$('#'+hiddenId).data("package",package); //stores info so I can remove table row and update database
var lastTableRow = $('#checkedInTable tr:last');
var button = lastTableRow.find('#COButton');
//add the click function for removing row and sending checked out info to server for email and for database purposes
button.click(function(e){
var x = e.pageX;
var y = e.pageY;
var o = {
left: x,
top: y
};
$("#progressMonitor").show().offset(o);
$(this).prop("disabled",true);
var row = $(this).closest('tr');
var carrierCell =$('#'+hiddenId);
var d = new Date();
var payload = new Object(); //this object gets transferred to the server function, the user interface doesn't refresh here, it just has a dynamic html table built and shrunk as kids check in or check out
payload.checkInTime = carrierCell.data("package").checkInTime;
payload.timeIn = carrierCell.data("package").timeIn;
payload.student = carrierCell.data("package").student;
payload.teacherEmail = carrierCell.data("package").teacherEmail;
payload.teacherName = carrierCell.data("package").teacherName;
payload.reason = carrierCell.data("package").reason;
payload.checkOutTime = d;
payload.timeOut = d.getTime();
var stringPayload = JSON.stringify(payload);
row.hide();
alternateRowColors($("#checkedInTable"));
google.script.run.withSuccessHandler(emailAndRecordsSuccess).withFailureHandler(emailAndRecordsFailure).emailAndRecords(stringPayload);//calling the server function
});
var numRows = $("#checkedInTable tr" ).length;
if(numRows>2){
alphaSortTable(); //puts the student names in alpha order so it is easier for them to checkout of the library
}
alternateRowColors($("#checkedInTable"));
$("#progressMonitor").hide();
$("#barcodeInput").focus(); //here is me trying to get the scanner back into the input field so there is somewhere for the scanner data to go; I expected this to be all I needed to do, but at this point, even though the input is focused, the the scanner won't fire onto the document or into the field or anything like that
alert($("#barcodeInput").val()); //this is telling me that there is no value in the input field at this point, I thought there might be info stored here screwing up the scanner
}
The solution was to rebind a function to the document after my client side work was done.
Changed this into a named function:
$(document).ready(function() {
var barcode="";
$(document).keydown(function(e)
{
var code = (e.keyCode ? e.keyCode : e.which);
if(code==13&&(barcode.substring(1,5)=="SCAN"))
{
e.preventDefault();
barcode = barcode.slice(5);
processBarcode(barcode);
}else if(code==9)// Tab key hit
{e.preventDefault();
}else{
e.preventDefault();
barcode=barcode+String.fromCharCode(code);
}
});
});
Now I have:
function getBarcode(){
var barcode="";
$(document).keydown(function(e)
{
var code = (e.keyCode ? e.keyCode : e.which);
if(code==13&&(barcode.substring(1,5)=="SCAN"))
{
e.preventDefault();
barcode = barcode.slice(5);
processBarcode(barcode);
}else if(code==9)// Tab key hit
{e.preventDefault();
}else{
e.preventDefault();
barcode=barcode+String.fromCharCode(code);
}
});
and
$(document).ready(function() {
getBarcode();
}
and I can call
getBarcode();
anywhere to re-connect the document to be looking for the barcode scanner.

re-populate form, after saving form data to serialized array Javascript

I am creating a form that I want users to be able to edit. The user will fill the form, save that form, fill the form with the next entry, save that form, etc. A clickable div is created each time the form is saved so that the user can go back and see their inputs to ensure they are correct before final submission of all forms. I've been able to save the form data doing this:
var formArray = $('form#popsetForm').serializeArray();
My question: I would now like to fill the form back with the data in formArray when the user clicks on the div. Is there an easy command that will allow me to just provide the array as input and it will auto-fill the form? The below is not real code but what I'm hoping exists.
$('form#popsetForm').populate(formArray)
I don't know if a solution already exists but something like this should work with serializeArray.
function restoreForm(form, formArray) {
formArray.forEach(function (pair) {
var selector = `input[name="${ pair.name }"], textarea[name="${ pair.name }"]`
var input = $(form).find(selector)
input.val(pair.value);
})
}
https://jsfiddle.net/aycnx0gd/4/
Or like this for regular ol' formData
function restoreForm(form, formData) {
for (var key of formData.keys()) {
var selector = `input[name="${ key }"], textarea[name="${ key }"]`
var input = $(form).find(selector)
var newVal = formData.get(key)
input.val(newVal);
}
}
https://jsfiddle.net/aycnx0gd/2/
I would consider simply hiding the form from view, eliminating the need to repopulate it at all.
Your form submit handler might look something like this:
$('#some_common_parent_element_to_all_forms').on('submit', 'form', function() {
var $currentForm = $(this);
// not shown - your form submit logic here
// on success of form submittal execute following...
// hide submitted form
$currentForm.hide();
// was form submitted previously?
// if so, we don't want to generate a new form
if($currentForm.data('submitted') !== true) {
// clone form
var $newForm = $currentForm.clone();
// reset cloned form
$newForm.get(0).reset();
// mark submitted form as submitted
$currentForm.data('submitted', true);
// append new form to DOM
$('#some_common_parent_element_to_all_forms').append($newForm).show();
// create new div to be able to "navigate" to submitted form
var $formNavContainer = $('#some_element_that_holds_nav_divs');
var currentNavCount =
$formNavContainer.find('.form_navigation').length;
var formDisplayNum = currentNavCount + 1;
var $newNav =
$('<div class="form_navigation">Form ' + formDisplayNum + '</div>');
$newNav.data('target-form-index', currentNavCount);
$newNav.appendTo($formNavContainer);
} else {
// this form was previously submitted
// perhaps we just reveal most recently created form
$('#some_common_parent_element_to_all_forms form').last().show();
}
}
And a click handler for navigation divs may look like:
$('#some_element_that_holds_nav_divs').on('click', '.form_navigation', function() {
var $clickedNav = $(this);
var formIndex = $clickedNav.data('target-form-index');
var $allForms = $('#some_common_parent_element_to_all_forms form');
var $selectedForm = $allForms.get(formIndex);
$allForms.hide();
$selectedForm.show();
});
This approach will allow you to create X number of forms, each storing their own set of form data. "Navigating" between forms then simply becomes a matter of showing/hiding the individual forms.

Sharepoint 2013 People Picker Change event in Javascript

I want People picker Change Event in Javascript as i have to do some task if user is selected/changed in people picker using ClassName.
i have tried the following
$(".Assignedname").bind('input propertychange', function() {
alert("Onchange event" );
})
this fires when i type anything (i.e. text is changed ) , but not fires when user is selected in peoples picker.
Kindly give me some solution. thanks
Once the people picker is initialized, you can access it in the js dictionary and assign a function to the OnValueChangedClientScript property of the picker. The function accepts two parameters, where the second parameter (userInfo) is a collection of users in the picker
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[pickerId + "_TopSpan"];
picker.OnValueChangedClientScript = function (elementId, userInfo) {
for (var x = 0; x < userInfo.length; x++) {
console.log(userInfo[x].Key);
}
alert("Total number of " + userInfo.length + " users is selected")
};
You need to get the picker id for SharePoint Client People Picker change event. I have got the same using OnUserResolvedClientScript as below. Here to get the picker div I have followed the approach of getting it via the people picker text box id and the title name which you can get the by inspecting the element. put the below code in $(document).ready function. Happy Coding
SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', function() {
var pickerDiv = $("[id^='Employee_x0020_Name'][title='Employee Name']");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[pickerDiv[0].id];
picker.OnUserResolvedClientScript = function(peoplePickerId, selectedUsersInfo) {
//It will get the desired display name of the people from picker div, similarly any other property can be accessed via selectedUsersInfo
var empname = selectedUsersInfo[0].DisplayText;
console.log(empname);
}
});
I used jQuery and a focusout event on the input field, instead, to achieve the same effect:
$('input[title="Title of my field"]').focusout(function() {
alert("Focusout event fired." );
doPeoplePickerStuff(); // function for doing validation
});
This has the advantage of being able to check the value of that field whenever they click on anything else - with the exception of the Submit button, if they click that immediately after typing in the field. Here's how I deal with that:
Create a new Submit button and hide the other one:
$('input[name*="diidIOSaveItem"]').parent().append('<input type="button" id="btnSubmit" onclick="doValidation()"></input>'); $('input[name*="diidIOSaveItem"]').hide();
Create the doValidation() function for your new Submit button:
function doValidation() {
doPeoplePickerStuff(); // do validation on the field here
if (personFound == true) {
$('input[name*="diidIOSaveItem"]').click(); // clicks the real button so it does what it normally would
}
}
If you're firing the event in order to grab its value and do validation on it, use:
var personFound = false;
function doPeoplePickerStuff() {
var personFieldSpan = $('span[id*="OriginalTitleOfMyField"]');
var personFieldValue = stripExtraTextFromPeoplePicker(personFieldSpan.text());
if (personFieldValue != "") { // you could do comparisons against the existing value, too, by getting the original value(s) via REST call
personFound = true;
}
}
function stripExtraTextFromPeoplePicker(person) {
var newPerson = person;
console.log("Span text: " + newPerson);
newPerson = newPerson.replace('Title of my field','');
newPerson = newPerson.replace('Enter a name or email address...','');
newPerson = newPerson.replace('Enter names or email addresses...','');
newPerson = newPerson.replace('xSuggestions are available. Use up and down arrows to select.','');
newPerson = newPerson.replace('Suggestions are available. Use up and down arrows to select.','');
newPerson = newPerson.replace('\r','');
newPerson = newPerson.replace('\n','');
newPerson = newPerson.replace('\t','');
newPerson = newPerson.trim();
return newPerson;
}

How to change a URL parameter on a link that has # as href and is submitted inside a form

I'm working on a drupal module and it gets images from an API, adds selectable search-filters and generates pagination. If I go to e.g. the 7th pagination page and add a filter that only spans 3 pages it will result in not showing anything at all.
Solution: on upon adding a filter, go back to the 1st page. Now is my problem that that page is an url parameter and the links made by the filter are set to href='#' so basically this page yes.
So I try to debug the javascript that handles the on click:
$('#blabla .filter-url').click(function(e) {
e.preventDefault();
var link = $(e.currentTarget);
console.log(link);
var filter_key = link.data('filter-key');
var filter_value = link.data('filter-value');
// var active = link.hasClass('active');
var filters_input = $('#blabla input[name="filters"]');
var current_filters = JSON.parse(filters_input.val() || '{}');
current_filters.filters = current_filters.filters || [];
var exists = ($.grep(current_filters.filters, function(e, i){
return e.key == filter_key;
}).length);
if (exists) {
//Remove current filter from list
current_filters.filters = $.grep(current_filters.filters, function(e, i){
return e.key != filter_key;
});
link.removeClass('active');
}
// Add current filter to list
current_filters.filters.push({
key: filter_key,
value: filter_value,
});
link.addClass('active');
filters_input.val(JSON.stringify(current_filters));
$('#formname').submit();
});
the link object:
The link object has a {0, context and length} object in which both 0 and context contain multiple instances of the url, which one should I edit?
I just want to manipulate the URL / get parameter page=xxx to be page=0, so it goes back to the 1st page. How to achieve this?
I was searching in the wrong place. At the end of the onclick-function it submits the form. I had to change the action of this form like this:
var old_form_action = $('#formname').attr('action');
var new_form_action = old_form_action.replace(/(page=)[^\&]+/, '$1' + '0');
$('#formname').attr('action', new_form_action);

OnClick Java Script Button - If field equals x then update other field to a, else update other field to B

I am working in a custom object and new to JavaScript. I want to create a button that basically says if a field equals "x" then update a different field to "A", if that field equals "y" then update the other field to "B", if the field is null then send an alert.
I got the button to work to update the field I need, but when I tried to create the if/then I got syntax errors.
Here is what I have so far:
{!REQUIRESCRIPT("/soap/ajax/27.0/connection.js")}
var objPrice_Quote__c = new sforce.SObject('Price_Quote__c');
objPrice_Quote__c.Id = '{!Price_Quote__c.Id}';
objPrice_Quote__c.Status__c = 'Customer Approval';
var result = sforce.connection.update([objPrice_Quote__c]);
location.reload(true);
I don't even see an if statement within your code.... try this.
var theFieldToSet = document.getElementById("field1");
var button = document.getElementById("button");
button.onclick = function () {
if (theFieldToSet.innerHTML == "x") {
theFieldToSet.innerHTML = "A";
}
};

Categories