http://coldfusion.com logo
Join Slack
Powered by
# javascript
  • h

    hemi345

    11/08/2022, 3:04 PM
    Good morning all, I'm currently learning Alpine JS. I have built a select list using Alpine and am now trying and make one of the options 'SELECTED' based on the value of an alpine variable. It almost works. The first x-if works showing the selected option but the second x-if never shows the rest of the options.
    Copy code
    <div class="travFormInput">
              <select x-model="p_person_to" name="p_person_to" required>
                <option value="">Choose one</option>
              <template x-for="u in acctUsers" :key="u['USERID']">
                <template x-if="p_person_to == u['USERID']">
                <option :value="u['USERID']" x-text="u['FULLNAME']" SELECTED></option>
                </template>
                <template x-if="p_person_to != u['USERID']">
                  <option :value="u['USERID']" x-text="u['FULLNAME']"></option>
                </template>
              </template>
              </select>
            </div>
    any ideas or better ways to do this?
    ➕ 1
    m
    • 2
    • 6
  • c

    chris-schmitz

    11/16/2022, 1:55 PM
    I'm trying to create a small PWA with JavaScript (just jQuery) that uses Firebase Cloud Messaging. I Initialize messaging like this:
    Copy code
    <script type="module">
    	import { initializeApp } from "<https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js>";
    	import { getMessaging, getToken, onMessage } from "<https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging.js>";
    
    	// Your web app's Firebase configuration
    	const firebaseConfig = {
    		apiKey: "<Api-Key>",
    		authDomain: "<Domain>",
    		projectId: "<ProjectId>",
    		storageBucket: "<Bucket>",
    		messagingSenderId: "<Sender-Id>",
    		appId: "<App-Id>",
    		name: "<App-Name>"
    	};
    
    	// Initialize Firebase
    	const app = initializeApp(firebaseConfig);
    	const messaging = getMessaging();
    
    	getToken( messaging, { vapidKey: '<Public-Key>' } )
    	.then((currentToken) => {
    		if (currentToken) {
    			window.localStorage.setItem( 'fbToken', currentToken );
    		} else {
    			console.log('No registration token available. Request permission to generate one.');
    		}
    	}).catch((err) => {
    		console.log('An error occurred while retrieving token. ', err);
    	}); 
    
    	onMessage(messaging, payload => {
    		console.log("Message received. ", payload);
    		const { title, ...options } = payload.notification;
    	});
    </script>
    On clicking a button the app reads the token from local storage and sends an ajax request to CF which then uses
    cfhttp()
    to send a message to Firebase with this request body:
    Copy code
    {
        "to" : arguments.data.fbToken
      , "notification" : {
            "message": arguments.data.msg
          , "title": "Greetings"
        }
    }
    The result of the
    cfhttp()
    call shows
    success: 1
    (plus things like
    multicast_id
    and
    message_id
    ), so I assume that I did things right so far. Yet the
    onMessage()
    event handler never fires, and I don't know whether the message never arrives or if there is a different problem. Any ideas or hints?
    s
    • 2
    • 5
  • s

    s1deburn

    11/21/2022, 2:41 PM
    see what's being returned with the browser's devtool?
    c
    m
    a
    • 4
    • 14
  • m

    Mark Takata (Adobe)

    12/21/2022, 7:11 PM
    Does anyone here have experience setting up CORS on Hostek? Trying to get my demo working and their servers seem to be ignoring my config.
    • 1
    • 1
  • j

    Jonas Eriksson

    01/19/2023, 1:30 PM
    Quick question about triggering a javascript chart (amCharts in this case) after manually selecting a tab: I have added some tabs to a "detailed view" on a product listing. On one of the tabs, a chart is generated. As there are about 30 concurrent products listed, 30 charts are being drawn in the background before I know if the visitor actually wants to see the chart, which delays the entire page build too much. Is there a good way using AlpineJS ideally (which I use for the tabs) to trigger the javascript for the charts when the selected tab is active? Many thanks for pointers!
    p
    • 2
    • 2
  • c

    Chris Tierney

    02/20/2023, 11:40 PM
    @Chris Tierney has left the channel
  • p

    phillipsenn

    05/05/2023, 3:14 PM
    I have a web page that works in Chrome but on on an iPad. Q: Is there a way to have JavaScript not fail silently but to display the error on the page? In Chrome I always have the developer console open but on the iPad I don't think I've got that option.
    m
    e
    +2
    • 5
    • 6
  • a

    Alex

    05/22/2023, 8:13 AM
    @Alex has left the channel
  • s

    Simone

    06/18/2023, 12:31 AM
    what is wrong with my sweetalert 1, it is not firing the confirmation
    Copy code
    function showMessage() {
        swal({
            title: "",
            html: 'This will trigger some updates</b>',
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "##EF5350",
            confirmButtonText: "Yes, Proceed",
            cancelButtonText: "Cancel",
            reverseButtons: true
        },function(isConfirmed) {
            alert(isConfirmed)
            if (isConfirmed) {
                alert($(".openStandings").attr('data-href'));
                $.ajax({
                    type: "POST",
                    url: $(".openStandings").attr('data-href'),
                    success: function(data) {
                    alert(data);
                    if (data.toLowerCase().indexOf("error") >= 0) {
                        swal({
                            title: "Oops",
                            text: data,
                            type: "error",
                            showCancelButton: false,
                            confirmButtonColor: "##EF5350",
                            confirmButtonText: "OK",
                            closeOnConfirm: true
                        });
                    } else {
                        swal({
                            title: "Great",
                            text: data,
                            type: "success",
                            showCancelButton: false,
                            confirmButtonColor: "##EF5350",
                            confirmButtonText: "OK",
                            closeOnConfirm: true
                        });
                    }
                }
                })
            }
        })
    }
    m
    m
    • 3
    • 3
  • j

    J

    06/22/2023, 2:56 PM
    Hello, I have a link using <a> tag and when I click on that link, I need to open in incognito window. Is that possible?
    d
    • 2
    • 1
  • s

    Simone

    06/23/2023, 4:00 PM
    is there a javascript function which can escape special characters so it does not break texts written in a different language, i tried elow, but its not working https://jsfiddle.net/p867dnme/
    d
    g
    • 3
    • 2
  • d

    daniel

    07/17/2023, 12:38 PM
    @daniel has left the channel
  • s

    Simone

    08/03/2023, 2:00 AM
    I have a question, playing with javascript, I have two input fields and entering a value in one input also adds the value in the 2nd input field and i want to trigger an event on the 2nd input field, i tried with input, change, but none of them is firing, and what if the 2nd input field is readonly, will it work the same way or it will not fire at all
  • s

    Simone

    08/03/2023, 2:06 AM
    to better explain the scenario here is what i am doing
    Copy code
    document.addEventListener('readystatechange', function(e) {
            switch (e.target.readyState) {
                case "complete":
                    
                    $('.totalsTeal').trigger('input');
                break;
            }
        });
    
    $(document).on('input', '.totalsTeal', function() {
            let self = $(this);
            let day = self.attr('data-name');
            console.log(self.val());
            if (self.val() === "0.00") {
                $('#w1_' + day).parent().find('label').css('display', 'none');
            } else {
                $('#w1_' + day).parent().find('label').css('display', 'block');
            }
        });
    so everytime, the value entered in the input field will have the updated value in the input field having a class of .totalsTeal and it should fire, the class is common to 3 or 4 inputs and every input works like a row
    m
    m
    • 3
    • 9
  • j

    johnbarrett

    08/18/2023, 6:29 PM
    Copy code
    I am trying to make a digital clock, but it always shows PM, and never shows AM, can anybody help me with this code to find out why it is not working correctly?  I think the issue is with " let timeOfDay = hour >= 12 ? "AM" : "PM";"                                                                                                          function update() {
      //Get todays date
      let today = new Date();
    
      //Extract time from date
      let hour = today.getHours();
      let minutes = today.getMinutes();
      let seconds = today.getSeconds();
    
      const weekday = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
      ];
      let day = weekday[today.getDay()];
    
      let date = today.getDate();
    
      const monthArr = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
      ];
      let month = monthArr[today.getMonth()];
    
      // console.log(day,date,month);
    
      //Pad 0 if time is < 10 (single digit)
      hour = hour < 10 ? "0" + hour : hour;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;
    
      //Convert railway clock to AM/PM clock
      hour = hour > 12 ? hour - 12 : hour;
      hour = hour == 0 ? 12 : hour;
    
      //Assign AM or PM according to time
      let timeOfDay = hour >= 12 ? "AM" : "PM";
    
      //Insert time using dom
      document.getElementById("hours").innerHTML = hour + " :&nbsp";
      document.getElementById("minutes").innerHTML = minutes + " :&nbsp";
      document.getElementById("seconds").innerHTML = seconds + "&nbsp";
      document.getElementById("timeOfDay").innerHTML = timeOfDay;
      document.getElementById("day").innerHTML = day + " ,";
      document.getElementById("date").innerHTML = date + "&nbsp&nbsp";
      document.getElementById("month").innerHTML = month;
    }
    
    setInterval(() => {
      update();
    }, 1000);
    m
    • 2
    • 1
  • t

    Tim

    08/18/2023, 6:53 PM
    if hour is 12 or more, then AM, else PM
    is what you have written there. so it doesn't seem like it should always be PM. But it does seem like it's backwards.
    j
    • 2
    • 1
  • t

    Tim

    08/18/2023, 6:54 PM
    hour < 12 ? "AM" : "PM"
    would be right... 0-11 is am, 12-23 is pm. Assuming that the value in hour is a number from 0-24...
  • r

    Ryan Albrecht

    10/04/2023, 5:44 PM
    any quasar dudes in the channel?
  • g

    gsr

    11/02/2023, 6:51 PM
    my JavaScript is firing two times, what ia m doing wrong here https://jsfiddle.net/w0sou8ex/
    r
    r
    m
    • 4
    • 51
  • g

    gsr

    12/10/2023, 3:59 AM
    wrote a code to handlhandle the type of messatge i should get, I am looping over the table's all trs and finding the conditions to match Here are my conditions: 1. if all rows have data-mode="success" and data-pure="yes", it means the code is correct and its a success: 2. if any row has data-mode='success" and data-pure="no", it means, it is a warning, 3. if any row has data-mode="error", it means its an error and the message is danger I have the following code but it is always returning me 1, if there is a third condition,
    Copy code
    function checkTableData() {
                    var allTables = $('#tableBody');
                    var highestValue = -1;
                    for (var i = 0; i < allTables.length; i++) {
                        var table = allTables[i];
                        var trs = $(table).find('tr');
                        for (var j = 0; j < trs.length; j++) {
                            var tr = trs[j];
                            var dataSuccess = $(tr).attr('data-mode');
                            var dataPure = $(tr).attr('data-pure');
                            console.log(highestValue);
                            if (dataSuccess === 'success' && dataPure === 'yes' && highestValue < 0) {
                                highestValue = 0;
                                console.log('0');
                            } else if (dataSuccess === 'success' && dataPure === 'no' && highestValue < 1) {
                                highestValue = 1;
                                console.log('1');
                            } else if (dataSuccess === 'error') {
                                console.log('2');
                                errorCount++;
                                if (errorCount >= 1) {
                                    console.log('more than 2');
                                    return 2;
                                }
                            }
                        }
                    }
                    return highestValue;
                }
    i need some guidance on it, Thanks
    m
    • 2
    • 3
  • g

    gsr

    03/24/2024, 3:29 PM
    anyone knows about the socket.io connection issues https://stackoverflow.com/questions/78214518/connection-not-working-on-using-sockets-library
  • g

    gsr

    04/27/2024, 10:24 PM
    trying to create a dialog box with iframe in it, i am getting an error
    Copy code
    $("#dialogFrame").dialog({
        autoOpen: false, // Dialog is not shown on page load
        modal: true, // Make the dialog modal
        buttons: {
          "Close": function() {
            $(this).dialog("close");
          }
        }
     });
    
    $(document).on('click', ".opendialog1", function(e) {
      e.preventDefault();
      var dialogHref = $(this).data('dialog-href');
      var cssFile = $(this).data('css');
      var dialogTitle = $(this).data('dialog-title') || 'View Details';
      var dialogWidth = $(this).data('dialog-width') || 600;
      var dialogHeight = $(this).data('dialog-height') || 600;
    
      // Set the dialog content
      $("#dialogFrame").html('<iframe id="myIframe" src="' + dialogHref + '" width="100%" height="100%" frameborder="0"></iframe>');
    
      // Update dialog options
      $("#dialogFrame").dialog("option", "width", dialogWidth);
      $("#dialogFrame").dialog("option", "height", dialogHeight);
      $("#dialogFrame").dialog("option", "title", dialogTitle);
    
      // Open the dialog
      $("#dialogFrame").dialog("open");
    
      // Handle the iframe's load event
      $("#myIframe").on("load", function() {
        if (cssFile) {
          var iframeDoc = this.contentDocument || this.contentWindow.document;
          var link = iframeDoc.createElement("link");
          link.rel = "stylesheet";
          link.href = cssFile;
          iframeDoc.head.appendChild(link);
        }
      });
    });
    with this code
    Copy code
    <button name="updateGallery" id="updateGallery" data-load="iframe" data-dialog-href="uploadGallery.cfm?page=about&ID=15" class="main-btn warning-btn btn-hover moss opendialog1" data-dialog-title="Upload Additional Images" data-dialog-width="800" data-dialog-height="800">Upload Gallery</button>
    getting an error Uncaught TypeError: i.getClientRects is not a function which is pointing to this: $("#dialogFrame").dialog("option", "width", dialogWidth);
    q
    • 2
    • 2
  • r

    Ryan Albrecht

    05/16/2024, 5:06 PM
    for the javascript dudes. I have a question to improve my code. I have a vue application that is subscribing to ALOT of data (MQTT) with many topics. I am receiving the message quicker than I can process them so I need to throttle the processing of each message. Any improvements to be had?
  • r

    Ryan Albrecht

    05/16/2024, 5:06 PM
    Copy code
    //object to store throttled function for each topic
    var topic_funcs = {}
    
    //function to create new throttled dispatch function
    var createDispatchFunc = ()=>{
      return _.throttle( (payload)=>{
        store.dispatch('broker/handleMessage', payload)
      }, 3000);
    }
    
    //function to retrieve dispatch function 
    var getFunc = (topic) => {
      if( topic_funcs[topic] == undefined ){
        topic_funcs[topic] = createDispatchFunc();
      }
      return topic_funcs[topic];
    }
    
    // on message recieved from mqtt broker
    client.on('message', (topic,payload) => {
      //get func and execute
      getFunc(topic)(payload);
    } )
    p
    • 2
    • 3
  • e

    elpete

    06/20/2024, 2:13 AM
    We have a coldbox vite plugin that you could use or reference: https://github.com/ColdBox/coldbox-vite-plugin
    👀 1
    b
    • 2
    • 2
  • d

    Dave Merrill

    07/09/2024, 7:14 PM
    Grrr. I'm trying to update a js file, and I have, but I can't get the browser to see the updated version. I actually renamed the file on disk, so it's missing in in source control, but Chrome, Firefox and Edge all still act like it's there, the old version before I modified it. I'm sure I'm on the right server and workspace, since I modified one of the cfm files too, in a very obvious way, and I see that change. Very frustrating. Any suggestions? This is CF 2021 and IE.
    p
    m
    j
    • 4
    • 11
  • d

    Daniel Mejia

    08/17/2024, 1:59 AM
    @Daniel Mejia has left the channel
  • g

    gsr

    09/20/2024, 10:19 PM
    anyone can crack this down https://stackoverflow.com/questions/79008194/jquery-ui-calendar-date-range-showing-too-many-months
  • d

    Dave Merrill

    11/26/2024, 10:16 PM
    I have a page that's intended to be put in full screen mode by the user. As you may know, in Chrome and I think most other browsers, you can't go to full screen automatically on load with js, it has to be in response to a user action. The trick is how to refresh the page without taking it out of full screen. I tried the js below to refresh the content of the page via ajax instead of reloading or submitting it. The code works I think, but the page still gets knocked out of full screen mode. Thoughts?
    Copy code
    function loadPage(url)
    {
      fetch(url)
      .then(response => response.text())
      .then(data => {
        document.documentElement.innerHTML = data;
      })
      .catch(error => {
        console.error('Error:', error);
      });
    }
    loadPage(document.URL);
    • 1
    • 2
  • c

    cfsimplicity

    01/01/2025, 11:52 AM
    @cfsimplicity has left the channel