Verifying the presence of a cookie when the page loads

My goal is to have the browser initially check for a cookie named "yes."

If this cookie exists, I would like to show a message.

If not, I want to display the following:

<input type="button" id='approve' value="approve" onclick="a()"/>
<input type="button" id='reject' value="reject" onclick="r()"/>

Is there a way to achieve this on the client side?

Answer №1

If you're looking for a quick solution, one option is to utilize the document.write() method directly within your code. Consider using a preexisting function designed to retrieve cookies, like this one:

// adapted from http://www.elated.com/articles/javascript-and-cookies/
function get_cookie ( cookie_name ){
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

Then, in your HTML file, incorporate something along these lines:

<div id="container">
    <script>
    if (get_cookie("cookiename") == null){
        document.write("[cookie exists message]")
    } else {
        document.write('<input type="button" id='approve' value="approve" onclick="a()"/><input type="button" id='reject' value="reject" onclick="r()"/>')
    }
    </script>
</div>

To delay rendering until after the page has loaded, you can follow this approach:

function showit(){
    var myhtml;
    if (get_cookie("cookiename") == null){
        myhtml = "some message";
    } else {
        myhtml = '<input type="button" id='approve' value="approve" onclick="a()"/><input type="button" id='reject' value="reject" onclick="r()"/>'
    }
    document.getElementById("container").innerHTML = myhtml;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing Ionic function before application shutdown

Does anyone know of a function that can be triggered when the app is about to exit, close, or go into the background? Essentially any event that indicates "the user has stopped using the app"? In my app, I create a 'user log' that keeps track of ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...

Bootstrap modal should be closed by using the back button in bootstrap

Currently, I am in the process of developing an angularjs application that utilizes a bootstrap modal feature. My goal is to have the modal close when the user presses the back button on their phone. I have disabled html5mode, so my URLs include the # sy ...

Modify components in a directive template depending on the information in the scope

In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifica ...

One beneficial aspect of utilizing JavaScript closures for events is when defining a click event

There are two common ways to write code in JavaScript that accomplish the same task: Option A. SomeObject.prototype.hideElement = function(e, element){ e.stopPropagation(); hide(element); } Option B. SomeObject.prototype.hideElement = function( ...

The function toJson() does not exist for the specified stdClass object

After following a tutorial on implementing websockets in Laravel to create a live commenting system, I encountered an error that I cannot figure out. Even though I followed the code exactly as demonstrated in the video, this error persists. Does anyone hav ...

What is the best method for extracting attribute values from multiple child elements using puppeteer?

When using this code, I can retrieve the attribute value of the first element selected. By adding /html/body/section/div[3]/img<2> or img<3> in the xpath, I am able to retrieve data for subsequent img elements. However, the parent element on t ...

A step-by-step guide to adding a checkbox column dynamically within handsontable

I am currently utilizing handsontable within a jsfiddle at http://jsfiddle.net/kc11/cb920ear/1/. My task involves dynamically inserting a checkbox column before the existing data. The structure I am working with appears to be a multidimensional array, as s ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

Turn off choices by utilizing data type attribute values within select2 version 4

I'm attempting to deactivate the options by using the data-type attribute specified for each option in select2. Unfortunately, my attempts have been unsuccessful thus far. In addition, I am encountering this error within the change event handler: ...

Updating controller variables when the route changes in AngularJS

I'm new to the AngularJS scene and I've encountered a challenge. My goal is to have the selected tab change dynamically based on the URL changes. Here's my JavaScript code: app.config(function($routeProvider, $locationProvider){ $rou ...

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container: $('img').each(function(i){ var parent_width = parseInt($(this).parent().width()), image_width = parseInt($(this).width()); ...

What steps are involved in adding an image to an autocomplete script?

I need help adding an image to my autocomplete script. Below is my code that I'm struggling with. My Controller: function getsearch($c_id) { $searchTerm = $_GET['term']; $query = $this->db->query("SELECT state_name FROM state ...

Get a specific attribute of an object instead of directly accessing it

Is there a way to retrieve a specific object property in my checkForUrgentEvents method without referencing it directly? I attempted using Object.hasOwnProperty but it didn't work due to the deep nesting of the object. private checkForUrgentEvents(ur ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Angular JS: Extracting the header from a CSV file

Just getting started with angular JS and I have a question. I need to take a CSV file from the user as input and then send it to the controller when they click submit. <button class="btn btn-primary" type="submit" ng-click="Input(File)">Submit</ ...