I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.
Here the main javascript
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.
<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">
I tried 2 functions call.
document.getElementByName("satisfaction_case_number").value = getParameterByName("case")
and
document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")
I have to say I'm kinda blind here. Any flag would be appreciated.
Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.
I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks
Wait till the window has loaded then execute it;
window.onload = function () {
document.getElementsByName("satisfaction_case_number")[0].value = getParameterByName('case');
}
The form is being dynamically generated after the rest of your content has loaded, It's unreliable to rely on timing as connection speeds can vary, using
window.onload will ensure the page is fully loaded before executing.
I tested this by throttling my browser connection to "Slow 3G" and it still worked, Your original piece of code that selected the element by name wasn't selecting the first entry in the NodeList, to do this you need to add [0] before the .value
You can try document.querySelector('input[id *= satisfaction_case_number]').value = 'example'
setTimeout(function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}, 1000);
or try to modify the code that creates HubSpot form:
hbspt.forms.create({
// ...
onFormReady: function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}
});
Related
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads
var app_page_id = 40;
var app_pattern_page_id = 32;
var app_id;
var checksum;
var lang;
$(document).ready(function() {
app_id = $("#pFlowId").val();
checksum = $("#pInstance").val();
createMyFlow();
function createMyFlow(){
var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc, $v('pFlowStepId'));
lang = jQuery.parseJSON(result.get()).lang;
createMyArea();
result = loadDataFromMyOra();
if(result !== null)
findPattern(result);
}
function createMyArea(){
var textArea;
for ( var key in lang){
textArea = '<tr><td align="right"><label for="P'+app_page_id+'_VALUE_'+key+'">';
textArea += '<span class="optional">Name '+languages[key][0]+': </span></label></td>';
textArea += '<td align="left" valign="middle">';
textArea += '<input type="hidden" name="p_arg_names" />';
textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
textArea += '</td></tr>';
$('.formlayout').append(textArea);
}
}
function findPattern(patterns)
{
var item = "";
for ( var key in patterns){
item = patterns[key]+"";
item = item.replace(/,/g,",");
item = item.replace(/“/g,'"')
document.getElementById("P"+app_page_id+"_VALUE"+key).value = item; //error here
}
}
});
The error indicates document.getElementById("P"+app_page_id+"_VALUE"+key) is null. Work backwards and think of all the reasons it might be null:
What does "P"+app_page_id+"_VALUE"+key evaluate to? Does an element with this id exist in the DOM? (You can manually inspect the DOM tree with browser dev tools, or try running getElementById() in the dev console.)
An element with that id probably doesn't exist. You point out you are trying to create it, but is there any reason that createMyArea() might not be working?
If lang is an empty object, this loop will execute 0 times: for (var key in lang) ...
The for loop iterates on keys of the lang object, but inside the loop you access via languages[key]. That is a little weird.
Their are many more things to check, but this should give you an idea of things to look for. Work backwards and test all your assumptions!
Have you checked the generated HTML or is it impossible to provide such example?
Also I've noticed that you use var way more than you should for your variables. Have a quick read about when to use what here or here.
The function that generates the code createMyArea() uses the keys in the lang variable
for ( var key in lang){
....
textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
....
but in the findPatterns you are checking the id of the document using keys from another variable
for ( var key in patterns){
....
document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;
....
If the patterns variable and lang variable don't have the same key, then you will get an error.
To check that, you can
console.log ("P'+app_page_id+'_VALUE'+key+'")
just before the document.getElementById and see what values is checked there.
How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}
I have a comment box(textarea) in which the user types something and when he hits enter that thing is automatically displayed in 'comment section'. Now when the user hits submit I'm executing the following code,
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
comment.appendTo(commentSection);
By the above code the comment typed by user is dynamically displayed in the commentSection. This works fine but when user types something like,
<input type='text'>
in the comment box then a textbox is created within the comment section. So is there a way through which I could not let this happen?
Thanks in advance.
One way would be to just append the data as .text
Something like this:
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
commentSection.text(comment);
Edit: To append to an existing part of the comment, replace:
commentSection.text(comment);
with:
commentSection.text(commentSection.text() + comment);
You have to convert the string to entities. Define this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
Then run the following code when the user hits enter:
var comment = htmlencode($("#commentBox").val());
var commentSection = $("#commentSection");
comment.appendTo(commentSection);
Try this ,
div.insertAdjacentHTML( 'beforeend', comment);
You can use
var commentText = $("#commentBox").text();
but this do not clean html tags on your string, additionally you can use a function to do this
function RemoveHTMLTags(vals) {
var regX = /(<([^>]+)>)/ig;
var html = vals;
return (html.replace(regX, ""));
}
and then you use:
var finalComment = RemoveHTMLTags(commentText);
I've been tasked with building a very simple app that that has a series of dropdowns in rows of 2, when 2 are selected, a simple functions concatenates the 2 values and gives an output next to them like so:
dropdown1 dropdown2 Output
What I'm trying to get is, once the second dropdown value is chosen the function runs and displays the output where it says output. But currently, what seems to happens is the output is displayed in a new window.
Here's what I have so far (HTML):
<form>
<select id="test">
<option>Arena/Quantum Barcelona LTBC</option>
<option>Arena/Quantum Spain LTES</option>
</select>
<select id="name" onchange="tryThis()">
<option>Name</option>
<option>Name1</option>
</select>
</form>
JavaScript:
function tryThis() {
var string, string1 = '';
var e = document.getElementById("test");
string = e.options[e.selectedIndex].text;
var a = document.getElementById("name");
string1 = a.options[a.selectedIndex].text;
document.write(string+'_'+string1);
}
Am I making this more difficult than it needs to be?!
That's because document.write clears the page before displaying something. You should never need to use that function.
Instead, you could append it to e.g. the body:
document.body.appendChild(
document.createTextNode(string + '_' + string2)
);
Have you noticed that your JS function is called tryThis() and on the event handler you're calling tryThsis()
However in your case I'd refrain from using document.write, good alternatives are appending to the body or having a DIV and changing the innerHTML of that DIV
First put an id on your form so that it is easier to access.
var a = (function () {
var myForm = document.getElementById("myForm"),
magic = function () {
var a = myForm.getElementsByTagName("select"),
b,
c = [];
for (b = a.length - 1; b > -1; b -= 1) {
c.push(a[b].value);
}
alert(c.join(" ") + " output");
};
myForm.onclick = magic;
}());
You were not specific as to what the extra "output" is supposed to be or how you want the data returned, but here you go. Instead of using an alert you could push the result into the value of a different form element. Do not use document.write as this cannot be deferred. If you attempt to defer a document.write operation it will replace the entirety of the body contents of the current page.
I have a read only field on a html field which has a name of _Dataaddr_postcode I now need to capture this data and pass it into a new window which loads another file (proxcomp.asp) and use the data in a field on this page the field has an ID of inpAddr.
I have this code so far
<script type="text/javascript">
var pcodeStart = document.getElementbyId("_Dataaddr_postcode");
var newWindow;
function makeNewWindow( ) {
if (!newWindow || newWindow.closed) {
newWindow = window.open("../hpwprox/proxcomp.asp","sub","status=0,title=0,height=600,width=800");
setTimeout("writeToWindow( )", 50);
} else if (newWindow.focus) {
newWindow.focus( );
}
}
</script>
<input type="button" value="Create New Window" onclick="makeNewWindow();" />
Can someone tell me how to achieve this with some sample code?
Thanks
Justin.
Passing just that one field as a form input to the server-side script:
var genForm = document.createElement("form");
genForm.target = "sub";
genForm.method = "get"; // or "post" if appropriate
genForm.action = "../hpwprox/proxcomp.asp";
var genInput = document.createElement("input");
genInput.type = "hidden";
genInput.name = "inpAddr";
genInput.value = pcodeStart.value;
genForm.appendChild(genInput);
document.body.appendChild(genForm);
if(!newWindow || newWindow.closed) {
window.open("", "sub", "status=0,title=0,height=600,width=800");
} else if(newWindow.focus) {
newWindow.focus();
}
genForm.submit();
If you wish to use client-side code to set a textbox in the pop-up rather than server-side code, you need to do it from the pop-up window to avoid the delay you would add otherwise and the page's load time from "racing" each other. In JavaScript, global variables are properties of the window object they exist inside of, and window.opener gives the window that opened this one. Note that because of the same-origin policy, the two windows need to have the same protocol, hostname, and port number in their URLs.
// Using the variable referring to the text box:
document.getElementById('inpAddr').value = window.opener.pcodeStart.value;
// Or even using getElementById directly:
document.getElementById('inpAddr').value = window.opener.document.getElementById('inpAddr').value
You can omit the window. part of window.opener if you want to, provided that you are using no variable called opener.
Maybe doing this:
newWindow.document.getElementById('inpAddr').value = pcodeStart;
Or from the open window:
document.getElementById('inpAddr').value = opener.document.getElementbyId("_Dataaddr_postcode").value;
Please read this great article!