Function to hide form fields from external script - javascript

I'm using a web page which contains a form loaded with an external script using the command 'script src'.
I created a function to populate some fields from url parameters and also hide some of them.
Here is the code.
<script type="text/javascript">
<!-- Hide Form Field -->
function hideFormField(name) {
var list = document.getElementsByName(name);
for (i = 0; i < list.length; i++) {
list[i].style.display = 'none';
list[i].style.visible = 'false';
list[i].type = 'hidden';
}
}
<!-- Customize form -->
function CustomizeForm()
{
// Set Field Value
hideFormField('custom_11');
hideFormField('custom_12');
hideFormField('custom_13');
hideFormField('custom_14');
hideFormField('custom_15');
}
// call it
CustomizeForm();
</script>
The fields are populated but not hidden.
When I debug, the form fields appear to disappear briefly but then they reappear.
It looks like the form is being refreshed afterwards.
To hide fields, which specific command is best and should I use out of those three? I'm tried them separately but it didn't seem to solve my problem.
field.style.display = 'none';
field.style.visible = 'false';
field.type = 'hidden';
Where should I put the call to the function to hide fields?
Assuming I don't control where the code is being added exactly in my designer (only in which section: header, body or footer), is there another alternative that would work every time? For example, can I attach to an event (which one) that might get called after all the loading and refresh is done.
Can I somehow debug or trace what is happening and why the fields do reappear?
Thank you in advance!

it's visibility not visible, try:
list[i].style.visibility = "hidden";

Related

How to hide elements of an external widget on my website

I am trying to instal a chat widget in my website and I would like to hide certain elements of the chat widget.
The chat is provided by Tidio but I guess this apply to any widget.
I am specifically trying to hide a button that minimise the chat button as highlighted in the image below.
I have inspected the button and found out that button has a class exit-chat, so I run this script where I try to get the button with document.getElementsByClassName("exit-chat") however the document is somehow null. I have also tried to add a delay before getting the button but it does not work.
Here is the code I have written and here is the link to a codepen
<script src="//code.tidio.co/fouwfr0cnygz4sj8kttyv0cz1rpaayva.js" async="async"></script>
<!-- Swap your javascript code above -->
<script>
(function() {
function onTidioChatApiReady() {
(function() {
//code run after the widget is loaded
window.tidioChatApi.open();
const loading = document.getElementsByClassName("loading");
loading[0].style.display = "none";
const tidioo = document.getElementById("tidio-chat");
tidioo.style.display = "display";
var timeoutInSeconds = 2;
setTimeout(function() {
console.log("timeout");
const minimizee = document.getElementsByClassName("exit-chat");
console.log(minimizee==null);
minimizee[0].style.display = "none";
minimizee[1].style.display = "none";
}, timeoutInSeconds * 1000)
})();
}
if (window.tidioChatApi) {
window.tidioChatApi.on("ready", onTidioChatApiReady);
} else {
document.addEventListener("tidioChat-ready", onTidioChatApiReady);
}
})();
</script>
<div class="loading">
<p>Loading...</p>
</div>
Can you please help to understand where I get this wrong and explain how to hide that button?
Thanks!!
If you embedded an iframe that is hosted in another website, you will not be able to edit the style of the elements inside the iframe by adding CSS to your website.

window.onload function is called on page load and also every time I close an overlay

I have some JS code that I am trying to debug, and the problem is that the window.onload function is being called way more often than I expect it to. Here is my JS code:
var trueCountApp = (function(){
window.onload = function(){openRulesOverlay()};
document.getElementById("open-rules-overlay-button").onclick = function(){openRulesOverlay()};
document.getElementById("select-rules-button").onclick = function(){saveRuleSelections()};
function openRulesOverlay(){
let blackjackRules;
if(sessionStorage.blackjackRules){
blackjackRules = JSON.parse(sessionStorage.blackjackRules);
for(let i=0; i<blackjackRules.length;i++){
document.getElementsByClassName("rule")[i].value = blackjackRules[i];
}
}
document.getElementById("rules_overlay").style.display = "block";
}
function saveRuleSelections(){
let blackjackRules = [];
let rules = document.getElementsByClassName("rule");
for(let i=0; i<rules.length;i++){
blackjackRules.push(rules[i].value);
}
let jsonBlackjackRules = JSON.stringify(blackjackRules);
sessionStorage.setItem("blackjackRules", jsonBlackjackRules);
document.getElementById("rules_overlay").style.display = "none";
}
})();
There are 2 buttons on my page: one opens an overlay, and the other closes an overlay. I also wanted to run some code a single time when the page is first loaded, and I just used the openRulesOverlay() function that I had already written as a placeholder for the code I want to run. What I expected to happen was for the page to load, openRulesOverlay() would run once, then the buttons would work as normal from there. However, it seems that the window.onload function is running anytime the overlay gets closed. Why is this happening?
Note: I did not include the html code because I didn't think it was relevant to this problem. Let me know if I need to include it.
Simple fix in my particular case: the default button type is "submit", so the page would load, the form would open, and then when I pressed a button to close the form, it was essentially reloading the page and opening the form again. Just needed to change button type to "button".

How can I show content on a page based on query string?

I'm working with a team that is using a vendor's web based application. When people log out, they are redirected to the login page, where we would like to add a message. We don't have access to change the code (it's cloud hosted) but we can pass a query string parameter in the URL.
We can do something like:
http://our.site.com?logout=true
From there, I'd like to display a message in an h2 or something.
We can customize the HTML, CSS and JS of the page, but we don't have access to the source of the application (otherwise I would do this in PHP).
I presume I can use JS to change some CSS, but in all my trials I cannot get the CSS to actually change.
Check this answer: Get url parameter jquery Or How to Get Query String Values In js
var logout = getUrlParameter('logout');
if(typeof logout !== "undefined")
{
// show some div with display: none
// or put some content to the existing div
}
From your question above, I am just understanding that you need a piece of code to show some message on your login page on the basis of the query string received.Following is the piece of code you can add in the footer of your login page html(as you have the access to html).
<script type="text/javascript">
function getParamValue(querystring) {
var qstring = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < qstring.length; i++) {
var urlparam = qstring[i].split('=');
if (urlparam[0] == querystring) {
return urlparam[1];
}
}
}
if(getParamValue('logout')=='true'){
var messageDiv = document.createElement("div"); // Creating a div to display your message
var message = document.createTextNode("You have successfully logged out."); // Preparing the message to show
messageDiv.appendChild(message); // Appended the message in newly created div
var addIn = document.getElementById("login"); //just presuming there is a div having id="login" in which you want to prepend the message
addIn.insertBefore(messageDiv, addIn.childNodes[0]); //just appended the message on top of login div
//setting style in your message div
messageDiv.style.backgroundColor ="#FF0000";
messageDiv.style.width ="100%";
}
</script>
Then change the link of login page like this:
http://our.site.com/login.php?logout=true
Note :Read the code comments carefully to edit the code as per your html structure.
Try !important to change CSS? Just a temporary solution until you can edit the actual code.

How to clear form behind modal window with javascript?

Just like the question says, I'm trying to clear a form from a modal window while the modal stays up. I've tried:
if (myDocument.title == "Modal Window") {
parent.document.getElementById("textbox")
}
(I need it to do more than 1 tb, but used that just to try to get there. No luck.
It is contained within an iFrame, so I tried:
if (myDocument.title == "Modal Window") {
var ifr = document.getElementById("iFrame")
var form = ifr.document.getElementById("form")
ClearForm(form)
}
The ClearForm(form) function I stole from another Stack Overflow answer:
function ClearForm(form) {
$(':input', form).each(function () {
var type = this.type;
var id = this.id;
if (type == 'text' && id != 'text2')
this.value = "";
});
}
That 'text2' is one specific tb that we need to remain populated.
Any idea what I'm missing? I've been plagued with this bug for weeks.
I expect your issue is that the form is within an iFrame - most browsers won't allow you to modify elements within an iFrame, from the parent page, if they aren't from the same origin (or if the server is set up to deny it, or if you're looking at the page locally... see here for more details)
To double-check, try moving the form markup into the same page as the modal is in and run your function ClearFormfrom there. I expect that you'll then find it works.
Your only way around this would be to include the ClearForm function within the iFrame'd page, and then trigger it from the parent.

Adding and removing elements on a web page dynamically using javascript

So I'm using Twitter Bootstrap to create a web page, and I'd like to use their "Alerts" class to dynamically create and dismiss alerts at the bottom of my page. Basically my web page is used to monitor a wireless data acquisition system, so I'd like to be able to dynamically display messages related to that system, i.e. "Warning, Sensor 1 is not responding", and then be able to dismiss it dynamically when the event has passed, or have the user dismiss it.
I'm more of an embedded systems guy, and haven't done much web development, so I'm really not sure where to start. My first inclination would be to do something like this:
<div id="Alert1"></div>
<div id="Alert2"></div>
...
And create enough divs at the bottom of my page to display a reasonable number of messages, then dynamically change them in code with something like:
var Alert1 = document.getElementById("Alert1");
Alert1.className = "alert alert-warning";
$('#Alert1').html("Error: Unable to write to logfile");
I can't imagine that this is a very good way to do it, though, and I'd have to have some way to manage what divs were in use, etc. What is a better way to dynamically create and remove these elements?
Using jQuery you can use append to dynamically add an element to the page.
<div class="alerts"></div>
In JavaScript:
$(".alerts").append("<div id='alert1'>Warning</div>");
Similarly you can remove the element using the remove() function.
You don't need to create a <div> for any and all error messages you have. Just create one <div> and dynamically fill in the appropriate text (or HTML) of the currently active message.
Sample code:
// define this function globally
(function (exports) {
var messages = {};
function addMessage(type, msg) {
if (typeof messages[type] === "undefined") {
messages[type] = [];
}
messages[type].push(msg);
render();
}
function render() {
var html = "";
for (type in messages) {
if (messages.hasOwnProperty(type)) {
for (var i=0, len=messages[type].length; i<len; i++) {
html += type + ": " + messages[type][i];
}
}
}
$("#Alert").html(html);
}
exports.addMessage = addMessage;
})(window);
// somewhere in your code
addMessage("Error", "Unable to write to logfile");
It would be even better to declare "Error" as a constant/variable somewhere:
var ERR_ERROR = "Error";
var ERR_WARNING = "Warning";
You can define a template for your alerts, holding the message and the type of the message.
Then according to the type of the message you would append the message into the page.
Consider the following function
function addAlert(type, message) {
_.templateSettings.variable = "element";
var tpl = _.template($("#alertTemplate").html());
var tplData = {
message: message,
type: type
};
$("#mainContainer").append(tpl(tplData));//the div or container where you want your messages to appear
}
And the template would be
<script type="text/html" id="alertTemplate">
<div class = "alert alert-<%= element.type %>" > <%= element.message %> </div>
</script>
and of course the container of your alerts
<div id="mainContainer">
</div>
Then in your alert handler you would call addAlert with the appropriate parameters.
and to remove all the alerts
$("#mainContainer").find('.alert').remove();
You can find working example at http://jsfiddle.net/hatemalimam/EpM7W/6/

Categories

Resources