passing url parameters to hidden field with javascript - javascript

I need help with below code.
What I need to do is to pass the URL parameters to these two hidden fields.
http://www.yoursite.com/index.php?fieldOne=Work&fieldTwo=Play
It doesn't seem to be working. Also I cannot add id to the form field.
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
<script>
function FillForm() {
var FormName = "myformname";
var qLoc = location.href.indexOf('?');
if(qLoc < 0) { return; }
var q = location.href.substr(qLoc + 1);
var list = q.split('&');
for(var i = 0; i < list.length; i++) {
var kv = list[i].split('=');
if(! eval('document.'+FormName+'.'+kv[0])) { continue; }
kv[1] = unescape(kv[1]);
if(kv[1].indexOf('"') > -1) {
var re = /"/g;
kv[1] = kv[1].replace(re,'\\"');
}
eval('document.'+FormName+'.'+kv[0]+'.value="'+kv[1]+'"');
}
}
FillForm();
</script>`

NULL had it kind of there with the simplification (albiet there is a small error in your code regarding the iteration over the query). Here is NULL's simplification corrected, and also my guess as to why you're not getting the desired results:
<form name="myformname">
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
</form>
<script type="text/javascript">
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query[i].split("=");
//alert(split);
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}
</script>
1) Make sure you're using a form tag with an id. I can't see your HTML.
2) Be sure that you are not seeing new data appear in the hidden <input>'s? I advise using a debugger and checking the live DOM tree as opposed to the source code. Some debuggers don't update the source in real-time.
EDIT:
Based on new information from the questioning party, here is another stab at a fix:
<script type="text/javascript">
$(document).ready(function(){
var formName = "dSOfferAllE10Test-1349977611926";
var query = location.href.split("?").pop().split("&");
var len = query.length;
var split, elem;
for (var i = 0; i < len; i++ ) {
split = query[i].split("=");
$('form[name="'+formName+'"]').find('input[name="'+split[0]+'"]').each(function(){
$(this).val(split[1].replace(/"/g, '\\"'));
});
}
});
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​
This uses jQuery, so make sure that you attach a reference to jQuery in your <head> (or at least near the top of the <body> if you don't have access to the <head>. Best to grab the snippet from the Google-hosted version: https://developers.google.com/speed/libraries/devguide#jquery

You can simplify your code:
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query.split("=");
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}

Related

Looping error in Javascript with eventHandler

I have the following Javascript code within and HTML page. Its function is to display elements on the form based on the user pressing a + button and if the element is not needed then it removes it via the user pressing the - button. Currently its throwing an error "TypeError: docs[n]" is undefined after the following sequence of events:
Select button to add elements
Remove elements not needed
Add elements back (Error Thrown)
Any help would be most appreciated
`<script language="JavaScript">`
var idx = 0;
var d;
//Make getElementsByClassName work for all of IE revs
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
function add_fields(e) {
// for some reason, adding the new fields wipes out existing values, so save and restore
var docs = document.getElementsByClassName("doc");
var revs = document.getElementsByClassName("rev");
++idx;
/* console.log("test " + idx); */
var saveDocs = new Array(idx);
var saveRevs = new Array(idx);
for (n=0; n < idx; n++) {
saveDocs[n] = docs[n].value; **//Error is thrown here**
saveRevs[n] = revs[n].value;
}
node = document.getElementById("content");
theNewRow = document.createElement("tr");
theNewCell = theNewRow.insertCell(0);
theNewCell.innerHTML = "Approver Name";
theNewCell.setAttribute("style","font-size: 12pt");
theNewCell1 = theNewRow.insertCell(1);
theNewCell1.innerHTML = "<input type='text' class='doc' style='width:180px;' id='docNum0'/>";
theNewCell1.setAttribute("style","padding-left: 10px");
theNewCell2 = theNewRow.insertCell(2);
theNewCell2.innerHTML = "Approver Email";
theNewCell2.setAttribute("style","font-size: 12pt");
theNewCell2.setAttribute("style","padding-left: 10px");
theNewCell3 = theNewRow.insertCell(3);
theNewCell3.innerHTML = "<input type='text' class='rev' style='width:180px;' id='rev0'/> <input class='minusThing' type='button' style='font-size:10px' value='- '/>";
theNewCell3.setAttribute("style","padding-left: 0px");
node.appendChild( theNewRow );
// restore old arrays and add the id tags to the fields just added
docs = document.getElementsByClassName("doc");
revs = document.getElementsByClassName("rev");
for (n=0; n < idx; n++) {
docs[n].value = saveDocs[n];
revs[n].value = saveRevs[n];
}
docs[idx].id = "docNum" + idx;
revs[idx].id = "rev" + idx;
}
//for Loop the entries
function myfunction() {
alert('Inside Function')
var values = "";
for (n=0; n <= idx; n++)
{
var doc = document.getElementById("docNum"+n).value;
var rev = document.getElementById("rev"+n).value;
//alert(doc+rev);
//Call VbScript Sub and pass value
PassValues(doc,rev);
```
If you've removed all the docs, document.getElementsByClassName("doc"); is going to return an empty array. If you're incrementing idx before your loop, the loop will execute once and try to access docs[0], which is undefined.

How to insert data from a url to a HTML field with "data-field-id" or "data-val-type"?

(EDIT: I have not merged with the duplicate question mentioned because I am NOT a highly experienced coder, so have used language most 'non-coders' will use. So this question and the answer might actually provide value for people like us.)
I have this code which pre-populates an email input field based on the id of the field, with text taken from the url *
Example - mywebsite.com&?mail=some#example.com, then the email string will be inserted in the email field on the page.
CURRENT CODE:
var mail = document.querySelector('input.emailfieldclass');
if (mail) {
var t = document.location.href.split('?')[1];
if (t) {
var params = {};
var lst = t.split('&'), l = lst.length;
for (var i = 0; i < l; i++) {
var p = lst[i].split('=');
if (!p[1]) continue;
params[p[0]] = p[1];
}
if (params.mail) {
mail.value = params.mail;
}
}
}
PROBLEM:
1) The above code works for a normal html input element with an id and/or class.
2) But how to make it work when I have a form with the following email field attributes, without any specific id's:
<input placeholder="Email" data-field-id="field32" data-val-type="email">
Limitations:
Cannot add my own id or class to this field. Can only work with the above data attributes.
Here you go with the data-selector, mentioned in the comments by guradio.
var mail = document.querySelector('[data-val-type=email]');
console.log(mail);
/*
if (mail) {
var t = document.location.href.split('?')[1];
if (t) {
var params = {};
var lst = t.split('&'), l = lst.length;
for (var i = 0; i < l; i++) {
var p = lst[i].split('=');
if (!p[1]) continue;
params[p[0]] = p[1];
}
if (params.mail) {
mail.value = params.mail;
}
}
}
*/
<input placeholder="Email" data-field-id="field32" data-val-type="email">

How can I get the text to which a Nested Style is applied in InDesign

I am trying to write a script that will convert all characters to lowercase if a particular nested style is applied. I can't seem to figure out the correct syntax to get the text.
I originally tried the following, which worked to an extend, but lowercased the entire paragraph rather than only the text that has the character style applied:
function lowerCaseNest(myPStyle, myCStyle){
var myDocument = app.documents.item(0);
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
app.findTextPreferences.appliedParagraphStyle = myPStyle;
var missingFind = app.activeDocument.findText();
var myDoc = app.documents[0];
for ( var listIndex = 0 ; listIndex < missingFind.length; listIndex++ ) {
for (i = missingFind[listIndex].nestedStyles.length-1;i>=0; i--) {
for (j = missingFind[listIndex].nestedStyles[i].parent.characters.length-1;j>=0; j--) {
if (missingFind[listIndex].nestedStyles[i].parent.characters[j].contents.appliedCharacterStyle(myCStyle)) {
var myString = missingFind[listIndex].nestedStyles[i].parent.characters[j].contents;
if (typeof(myString) == "string"){
var myNewString = myString.toLowerCase();
missingFind[listIndex].nestedStyles[i].parent.characters[j].contents = myNewString;
}
}
}
}
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
}
I then tried playing around with appliedNestedStyles, but can't seem to figure out how to retrieve the text that the nested style is applied to.
Could anyone help with this?
Thanks!
John
Unless I am wrong the appliedNestedStyle can be looked after in the F/C dialog by targeting the applied characterStyle:
GREP
Find : .+
Format : character style => myCharStyle
then
var found = doc.findGrep();
…
I actually took a different tack, and figured out something that works:
function lowerCaseNest(myPStyle, myCStyle){
for (var i = 0; i < app.activeDocument.stories.length; i++){
for (var j = 0; j < app.activeDocument.stories[i].paragraphs.length; j++){
var myP = app.activeDocument.stories[i].paragraphs[j];
if (myP.appliedParagraphStyle.name==myPStyle) {
for (k=0; k<myP.characters.length; k++) {
if(typeof(myP.characters[k].appliedNestedStyles[0]) != 'undefined'){
if(myP.characters[k].appliedNestedStyles[0].name == myCStyle) {
var myC = myP.characters[k].contents;
if (typeof(myC)=='string'){
var myNewString = myC.toLowerCase();
myP.characters[k].contents = myNewString;
}
}
}
}
}
}
}
}
Still would be interested in knowing if there's an easier way to handle this, as I'm afraid this may take longer to run on long documents, since it's dealing with every paragraph individually.

How to get a HTML element by searching the content of innerHTML?

How to get a HTML element by searching the content of innerHTML?
For example, Search
I want to get the "a" tag by searching word "Search" using javascript.
Thank you
var aTags = document.querySelectorAll('a');
var searchaTag = '';
for(i = 0; i<aTags.length; i++ ) {
if(aTags[i].text == 'Search') {
searchaTag = aTags[i];
break;
}
}
If you have no idea where the element can be, iterate over each element:
var all = document.querySelectorAll('*'); //OR document.getElementsByTagName("*")
for(var i = 0; i < all.length; i++ ) {
if(all[i].innerHTML === "search") {
console.log(all[i].tagName);
}
}
If you have some clue you can narrow your search by looking inside that area:
var all = document.querySelector('#my-Container').getElementsByTagName('*');

Posting variable data with variable names using jquery

I am trying to adjust the code in this question for my needs. I need to extract the title attributes from selected elements and post them but my attempt at adjusting it is not quite working...
function submit(id) {
var answers = document.getElementsByClassName("selected");
var answersobject = {qid: id}
for (var i = 0 ; i < answers.length ; i++){
var j = i + 1;
var ans = "a" + j;
answersobject[ans] = answers[i].getAttribute['title'];
}
var loc = "testsub.php";
$.redirectPost(loc, answersobject);
}
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
}
});
Currently it redirects but no data is being posted.

Categories

Resources