Durchsuche Foren

(Erweiterte Suche)

Foren-Statistiken
» Mitglieder: 43.388
» Neuestes Mitglied: PrimoCenturio
» Foren-Themen: 504
» Foren-Beiträge: 2.090

Komplettstatistiken

Benutzer Online
Momentan sind 51 Benutzer online
» 0 Mitglieder
» 49 Gäste
Bing, Google

Aktive Themen
Probleme Firebase Databas...
Forum: Javascript
Letzter Beitrag: Sempervivum
Vor 8 Stunden
» Antworten: 3
» Ansichten: 38
Verbindung von Entscheidu...
Forum: Javascript
Letzter Beitrag: Ashriel
16.04.2024, 11:02
» Antworten: 3
» Ansichten: 78
Neu laden ohne Scrolling
Forum: Javascript
Letzter Beitrag: Tom
16.04.2024, 08:48
» Antworten: 0
» Ansichten: 17
Formularfelder addieren u...
Forum: Javascript
Letzter Beitrag: heena123
16.04.2024, 08:03
» Antworten: 17
» Ansichten: 339
FMOVIES
Forum: Javascript
Letzter Beitrag: xomanig690
16.04.2024, 07:07
» Antworten: 0
» Ansichten: 22
Spam gelöscht
Forum: Ankündigungen,Neuigkeiten
Letzter Beitrag: rzscout
10.04.2024, 23:37
» Antworten: 0
» Ansichten: 146
Reihenfolge der Karten
Forum: Brauche Javascript / Userscript
Letzter Beitrag: hardee
10.04.2024, 17:54
» Antworten: 4
» Ansichten: 88
Variable aus Funktion zur...
Forum: Javascript
Letzter Beitrag: Kai_Behncke
27.03.2024, 14:58
» Antworten: 2
» Ansichten: 119
Probleme mit Canvas
Forum: Javascript
Letzter Beitrag: Sempervivum
27.03.2024, 09:28
» Antworten: 5
» Ansichten: 240
Bildauswahl Reset
Forum: Javascript
Letzter Beitrag: Sempervivum
25.03.2024, 05:38
» Antworten: 6
» Ansichten: 240

  Probleme Firebase Database
Geschrieben von: PrimoCenturio - Vor 11 Stunden - Forum: Javascript - Antworten (3)

Hallo zusammen,

ich bin neu in der JS Programmierung und ich hoffe hier noch einiges zu lernen.

Hier habe ich mein erstes Problem wo ich eure Hilfe bräuchte. Hier der Code

Code:
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-app.js";
  import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-auth.js";
  import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-database.js";

  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries
  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "XXXXXXXXXXXXXXXXXXXX,
    authDomain: "XXXXXXXXXXXXXXXXXXXX",
    projectId: "XXXXXXXXXXXXXXXXXXXX",
    storageBucket: "XXXXXXXXXXXXXXXXXXXX",
    messagingSenderId: "XXXXXXXXXXXXXXXXXXXX",
    appId: "XXXXXXXXXXXXXXXXXXXX"
  };
  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  //submit button
  const registration = document.getElementById('registration');
  registration.addEventListener("click", function (event) {
    event.preventDefault();

  //inputs
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;
  const name = document.getElementById('name');
  const prename = document.getElementById('prename');
  function AddData(){
    const db =getDatabase();
    set(ref(db, 'user/' + name), {
        name: name.value,
        prename: prename.value,
    })
    .then(()=>{
      alert("Daten wurden erfolgreich übermittelt");
    })
    .catch((error)=>{
      alert("Unsuccssful")
    })
  }
  const auth = getAuth();
 
  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed up
      const user = userCredential.user;
      alert("Benutzer wurde erstellt")
      // ...
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      alert(errorMessage)
      // ..
    });
  })

Die Authentifizierung funktioniert, jedoch nicht das eintragen der Daten auf Firebase Database. Sieht jemand evtl was ich falsch mache?

Danke euch vorab.

Viele Grüsse

Primo

Drucke diesen Beitrag

  Neu laden ohne Scrolling
Geschrieben von: Tom - 16.04.2024, 08:48 - Forum: Javascript - Keine Antworten

Ich verwende diese HTML-Seite um Messwerte und Google-Chart anzuzeigen und alle 3 Sekunden zu aktualisieren. Leider Scrollt die Seite nach jedem neu Laden an den Seitenanfang.
Kann man das irgendwie ausschalten, so das die Seite auf der aktuellen Scroll Position stehen bleibt und nur die neuen Werte anzeigt?
Das neu Laden mit dieser Seite funktioniert perfekt, ohne flackern des Bildschirms, aber eben das Scrolling sollte nicht sein.

<html>
<head>
  <script src="http://code.jquery.com/jquery-2.1.3.js" type="text/javascript"></script>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">google.charts.load('current',{packages:['corechart']});</script>
  <script type="text/javascript">
    $(document).ready(function() {
    $("#refresh").load("messwerte.php");
    var refreshId = setInterval(function() {
    $("#refresh").load('messwerte.php?');}, 3000);});
  </script>
<head>
<body>
  <div id="refresh"></div>
</body>
</html>



Angehängte Dateien
.html   index1.html (Größe: 589 Bytes / Downloads: 2)
Drucke diesen Beitrag

  FMOVIES
Geschrieben von: xomanig690 - 16.04.2024, 07:07 - Forum: Javascript - Keine Antworten

Since the inception of cinema, movies have captivated audiences around the world with their ability to entertain, inspire, and provoke thought. From the early days of silent films to the modern era of digital blockbusters, the magic of movies continues to transcend time and space, uniting people of all ages, cultures, and backgrounds. In this article, we delve into the enduring allure of movies, exploring their impact on society, culture, and the human psyche.
The Universal Language of Cinema: FMOVIES  
One of the most remarkable aspects of movies is their ability to communicate across linguistic and cultural barriers. Through the universal language of visuals and emotions, films have the power to evoke laughter, tears, and everything in between, forging connections among people from diverse walks of life.
Whether it's a Hollywood blockbuster, a Bollywood musical, or a foreign arthouse film, movies have the capacity to transport audiences to different worlds, inviting them to experience new perspectives and gain insights into the human condition. In an increasingly interconnected world, cinema serves as a bridge between cultures, fostering empathy, understanding, and a sense of shared humanity.
The Art of Storytelling:
At its core, cinema is the art of storytelling, and storytellers have been using the medium to weave tales of love, courage, triumph, and tragedy for over a century. From the epic narratives of ancient mythology to the intimate character studies of contemporary drama, films have the power to illuminate the human experience in all its complexity.
Through compelling characters, gripping plotlines, and stunning visuals, filmmakers transport viewers to distant lands, immersing them in worlds of imagination and wonder. Whether it's the heart-pounding excitement of an action-packed thriller or the quiet poignancy of a tender romance, movies have the ability to stir the emotions and leave a lasting impression on audiences long after the credits roll.
The Evolution of Cinema:
Since the Lumière brothers first dazzled audiences with their moving pictures in the late 19th century, cinema has undergone a remarkable evolution, embracing new technologies, genres, and storytelling techniques along the way. From the silent era to the golden age of Hollywood to the digital revolution of the 21st century, movies have continually pushed the boundaries of what is possible, both artistically and technologically.
Advancements in filmmaking technology, such as sound, color, computer-generated imagery (CGI), and virtual reality, have expanded the creative possibilities of cinema, enabling filmmakers to bring their wildest visions to life on the silver screen. Meanwhile, the rise of streaming platforms and digital distribution has democratized the filmmaking process, giving independent filmmakers greater access to audiences than ever before.
The Influence of Movies on Society:
Beyond their entertainment value, movies have a profound impact on society, shaping attitudes, beliefs, and cultural norms in subtle yet significant ways. From the propaganda films of wartime propaganda to the groundbreaking social commentary of the civil rights era, films have the power to challenge assumptions, provoke debate, and inspire social change.
Films have the ability to shine a spotlight on pressing issues such as racism, sexism, poverty, and environmental degradation, sparking conversations and mobilizing audiences to take action. Whether it's the powerful message of racial equality in "To Kill a Mockingbird" or the environmental allegory of "Avatar," movies have the capacity to influence hearts and minds, galvanizing individuals to work towards a better world.
The Enduring Appeal of Moviegoing:
Despite the proliferation of streaming services and digital media, the experience of going to the movies remains a cherished pastime for millions of people around the world. From the thrill of watching a highly anticipated blockbuster on opening night to the cozy comfort of a classic film marathon on a rainy day, going to the movies offers a unique blend of escapism, community, and shared experience.
For many moviegoers, the cinema is a sacred space where they can leave their cares behind and lose themselves in the magic of storytelling. Whether it's the immersive sound, the larger-than-life visuals, or the collective energy of a captivated audience, there's something undeniably special about the experience of watching a movie in a darkened theater.
Conclusion:
In an age of constant change and uncertainty, films remain a constant source of inspiration, enlightenment, and joy. From the humble beginnings of silent films to the cutting-edge technology of today's blockbusters, cinema has endured as a testament to the enduring power of human creativity and imagination.
As we continue to navigate the complexities of the modern world, films serve as a beacon of hope, reminding us of the boundless possibilities of the human spirit. Whether it's the timeless wisdom ofa classic film or the groundbreaking innovation of a contemporary masterpiece, mo



Angehängte Dateien Thumbnail(s)
   
Drucke diesen Beitrag

  Verbindung von Entscheidungen D3
Geschrieben von: Ashriel - 11.04.2024, 11:50 - Forum: Javascript - Antworten (3)

Guten Tag,
Ich bin relativ neu im programmieren und habe vor ein größeres Projekt zu starten.
Als Grundlage dazu benutze ich das decision tool von d3.

Code:
function init() {

      // Since 2.2 you can also author concise templates with method chaining instead of GraphObject.make
      // For details, see https://gojs.net/latest/intro/buildingObjects.html
      const $ = go.GraphObject.make;  // for conciseness in defining templates

      myDiagram = new go.Diagram("myDiagramDiv",  // must name or refer to the DIV HTML element
        {
          initialContentAlignment: go.Spot.Left,
          allowSelect: false,  // the user cannot select any part
          // create a TreeLayout for the decision tree
          layout: $(go.TreeLayout, { arrangement: go.TreeLayout.ArrangementFixedRoots })
        });

      // custom behavior for expanding/collapsing half of the subtree from a node
      function buttonExpandCollapse(e, port) {
        var node = port.part;
        node.diagram.startTransaction("expand/collapse");
        var portid = port.portId;
        node.findLinksOutOf(portid).each(l => {
          if (l.visible) {
            // collapse whole subtree recursively
            collapseTree(node, portid);
          } else {
            // only expands immediate children and their links
            l.visible = true;
            var n = l.getOtherNode(node);
            if (n !== null) {
              n.location = node.getDocumentPoint(go.Spot.TopRight);
              n.visible = true;
            }
          }
        });
        myDiagram.toolManager.hideToolTip();
        node.diagram.commitTransaction("expand/collapse");
      }

      // recursive function for collapsing complete subtree
      function collapseTree(node, portid) {
        node.findLinksOutOf(portid).each(l => {
          l.visible = false;
          var n = l.getOtherNode(node);
          if (n !== null) {
            n.visible = false;
            collapseTree(n, null);  // null means all links, not just for a particular portId
          }
        });
      }

      // get the text for the tooltip from the data on the object being hovered over
      function tooltipTextConverter(data) {
        var str = "";
        var e = myDiagram.lastInput;
        var currobj = e.targetObject;
        if (currobj !== null && (currobj.name === "ButtonA" ||
          (currobj.panel !== null && currobj.panel.name === "ButtonA"))) {
          str = data.aToolTip;
        } else {
          str = data.bToolTip;
        }
        return str;
      }

      // define tooltips for buttons
      var tooltipTemplate =
        $("ToolTip",
          { "Border.fill": "whitesmoke", "Border.stroke": "lightgray" },
          $(go.TextBlock,
            {
              font: "8pt sans-serif",
              wrap: go.TextBlock.WrapFit,
              desiredSize: new go.Size(200, NaN),
              alignment: go.Spot.Center,
              margin: 6
            },
            new go.Binding("text", "", tooltipTextConverter))
        );

      // define the Node template for non-leaf nodes
      myDiagram.nodeTemplateMap.add("decision",
        $(go.Node, "Auto",
          new go.Binding("text", "key"),
          // define the node's outer shape, which will surround the Horizontal Panel
          $(go.Shape, "Rectangle",
            { fill: "whitesmoke", stroke: "lightgray" }),
          // define a horizontal Panel to place the node's text alongside the buttons
          $(go.Panel, "Horizontal",
            $(go.TextBlock,
              { font: "30px Roboto, sans-serif", margin: 5 },
              new go.Binding("text", "key")),
            // define a vertical panel to place the node's two buttons one above the other
            $(go.Panel, "Vertical",
              { defaultStretch: go.GraphObject.Fill, margin: 3 },
              $("Button",  // button A
                {
                  name: "ButtonA",
                  click: buttonExpandCollapse,
                  toolTip: tooltipTemplate
                },
                new go.Binding("portId", "a"),
                $(go.TextBlock,
                  { font: '500 16px Roboto, sans-serif' },
                  new go.Binding("text", "aText"))
              ),  // end button A
              $("Button",  // button B
                {
                  name: "ButtonB",
                  click: buttonExpandCollapse,
                  toolTip: tooltipTemplate
                },
                new go.Binding("portId", "b"),
                $(go.TextBlock,
                  { font: '500 16px Roboto, sans-serif' },
                  new go.Binding("text", "bText"))
              )  // end button B
            )  // end Vertical Panel
          )  // end Horizontal Panel
        ));  // end Node and call to add

      // define the Node template for leaf nodes
      myDiagram.nodeTemplateMap.add("personality",
        $(go.Node, "Auto",
          new go.Binding("text", "key"),
          $(go.Shape, "Rectangle",
            { fill: "whitesmoke", stroke: "lightgray" }),
          $(go.TextBlock,
            {
              font: '13px Roboto, sans-serif',
              wrap: go.TextBlock.WrapFit, desiredSize: new go.Size(200, NaN), margin: 5
            },
            new go.Binding("text", "text"))
        ));

      // define the only Link template
      myDiagram.linkTemplate =
        $(go.Link, go.Link.Orthogonal,  // the whole link panel
          { fromPortId: "" },
          new go.Binding("fromPortId", "fromport"),
          $(go.Shape,  // the link shape
            { stroke: "lightblue", strokeWidth: 2 })
        );

      // create the model for the decision tree
      var model =
        new go.GraphLinksModel(
          { linkFromPortIdProperty: "fromport" });
      // set up the model with the node and link data
      makeNodes(model);
      makeLinks(model);
      myDiagram.model = model;

      // make all but the start node invisible
      myDiagram.nodes.each(n => {
        if (n.text !== "Start") n.visible = false;
      });
      myDiagram.links.each(l => {
        l.visible = false;
      });
    }

    function makeNodes(model) {
      var nodeDataArray = [
        { key: "Start" },  // the root node

        // intermediate nodes: decisions on personality characteristics
        { key: "I" },
        { key: "E" },

        { key: "IN" },
        { key: "IS" },
        { key: "EN" },
        { key: "ES" },

        { key: "INT" },
        { key: "INF" },
        { key: "IST" },
        { key: "ISF" },
        { key: "ENT" },
        { key: "ENF" },
        { key: "EST" },
        { key: "ESF" },

        // terminal nodes: the personality descriptions
        {
          key: "INTJ",
          text: "INTJ: Scientist\nThe most self-confident of all types.  They focus on possibilities and use empirical logic to think about the future.  They prefer that events and people serve some positive use.  1% of population."
        },
        {
          key: "INTP",
          text: "INTP: Architect\nAn architect of ideas, number systems, computer languages, and many other concepts.  They exhibit great precision in thought and language.  1% of the population."
        },
        {
          key: "INFJ",
          text: "INFJ: Author\nFocus on possibilities.  Place emphasis on values and come to decisions easily.  They have a strong drive to contribute to the welfare of others.  1% of population."
        },
        {
          key: "INFP",
          text: "INFP: Questor\nPresent a calm and pleasant face to the world.  Although they seem reserved, they are actually very idealistic and care passionately about a few special people or a cause.  1% of the population."
        },
        {
          key: "ISTJ",
          text: "ISTJ: Trustee\nISTJs like organized lives. They are dependable and trustworthy, as they dislike chaos and work on a task until completion. They prefer to deal with facts rather than emotions. 6% of the population."
        },
        {
          key: "ISTP",
          text: "ISTP: Artisan\nISTPs are quiet people who are very capable at analyzing how things work. Though quiet, they can be influential, with their seclusion making them all the more skilled. 17% of the population."
        },
        {
          key: "ISFJ",
          text: "ISFJ: Conservator\nISFJs are not particularly social and tend to be most concerned with maintaining order in their lives. They are dutiful, respectful towards, and interested in others, though they are often shy. They are, therefore, trustworthy, but not bossy. 6% of the population."
        },
        {
          key: "ISFP",
          text: "ISFP: Author\nFocus on possibilities.  Place emphasis on values and come to decisions easily.  They have a strong drive to contribute to the welfare of others.  1% of population."
        },
        {
          key: "ENTJ",
          text: "ENTJ: Fieldmarshal\nThe driving force of this personality is to lead.  They like to impose structure and harness people to work towards distant goals.  They reject inefficiency.  5% of the population."
        },
        {
          key: "ENTP",
          text: "ENTP: Inventor\nExercise their ingenuity by dealing with social, physical, and mechanical relationships.  They are always sensitive to future possibilities.  5% of the population."
        },
        {
          key: "ENFJ",
          text: "ENFJ: Pedagogue\nExcellent leaders; they are charismatic and never doubt that others will follow them and do as they ask.   They place a high value on cooperation.  5% of the population."
        },
        {
          key: "ENFP",
          text: "ENFP: Journalist\nPlace significance in everyday occurrences.  They have great ability to understand the motives of others.  They see life as a great drama.  They have a great impact on others.  5% of the population."
        },
        {
          key: "ESTJ",
          text: "ESTJ: Administrator\nESTJs are pragmatic, and thus well-suited for business or administrative roles. They are traditionalists and conservatives, believing in the status quo. 13% of the population."
        },
        {
          key: "ESTP",
          text: "ESTP: Promoter\nESTPs tend to manipulate others in order to attain access to the finer aspects of life. However, they enjoy heading to such places with others. They are social and outgoing and are well-connected. 13% of the population."
        },
        {
          key: "ESFJ",
          text: "ESFJ: Seller\nESFJs tend to be social and concerned for others. They follow tradition and enjoy a structured community environment. Always magnanimous towards others, they expect the same respect and appreciation themselves. 13% of the population."
        },
        {
          key: "ESFP",
          text: "ESFP: Entertainer\nThe mantra of the ESFP would be \"Carpe Diem.\" They enjoy life to the fullest. They do not, thus, like routines and long-term goals. In general, they are very concerned with others and tend to always try to help others, often perceiving well their needs. 13% of the population."
        }
      ];

      // Provide the same choice information for all of the nodes on each level.
      // The level is implicit in the number of characters in the Key, except for the root node.
      // In a different application, there might be different choices for each node, so the initialization would be above, where the Info's are created.
      // But for this application, it makes sense to share the initialization code based on tree level.
      for (var i = 0; i < nodeDataArray.length; i++) {
        var d = nodeDataArray[i];
        if (d.key === "Start") {
          d.category = "decision";
          d.a = "I";
          d.aText = "Introversion";
          d.aToolTip = "The Introvert is “territorial” and desires space and solitude to recover energy.  Introverts enjoy solitary activities such as reading and meditating.  25% of the population.";
          d.b = "E";
          d.bText = "Extraversion";
          d.bToolTip = "The Extravert is “sociable” and is energized by the presence of other people.  Extraverts experience loneliness when not in contact with others.  75% of the population.";
        } else {
          switch (d.key.length) {
            case 1:
              d.category = "decision";
              d.a = "N";
              d.aText = "Intuition";
              d.aToolTip = "The “intuitive” person bases their lives on predictions and ingenuity.  They consider the future and enjoy planning ahead.  25% of the population.";
              d.b = "S";
              d.bText = "Sensing";
              d.bToolTip = "The “sensing” person bases their life on facts, thinking primarily of their present situation.  They are realistic and practical.  75% of the population.";
              break;
            case 2:
              d.category = "decision";
              d.a = "T";
              d.aText = "Thinking";
              d.aToolTip = "The “thinking” person bases their decisions on facts and without personal bias.  They are more comfortable with making impersonal judgments.  50% of the population.";
              d.b = "F";
              d.bText = "Feeling";
              d.bToolTip = "The “feeling” person bases their decisions on personal experience and emotion.  They make their emotions very visible.  50% of the population.";
              break;
            case 3:
              d.category = "decision";
              d.a = "J";
              d.aText = "Judgment";
              d.aToolTip = "The “judging” person enjoys closure.  They establish deadlines and take them seriously.  They despise being late.  50% of the population.";
              d.b = "P";
              d.bText = "Perception";
              d.bToolTip = "The “perceiving” person likes to keep options open and fluid.  They have little regard for deadlines.  Dislikes making decisions unless they are completely sure they are right.  50% of the population.";
              break;
            default:
              d.category = "personality";
              break;
          }
        }
      }
      model.nodeDataArray = nodeDataArray;
    }

    // The key strings implicitly hold the relationship information, based on their spellings.
    // Other than the root node ("Start"), each node's key string minus its last letter is the
    // key to the "parent" node.
    function makeLinks(model) {
      var linkDataArray = [];
      var nda = model.nodeDataArray;
      for (var i = 0; i < nda.length; i++) {
        var key = nda[i].key;
        if (key === "Start" || key.length === 0) continue;
        // e.g., if key=="INTJ", we want: prefix="INT" and letter="J"
        var prefix = key.slice(0, key.length - 1);
        var letter = key.charAt(key.length - 1);
        if (prefix.length === 0) prefix = "Start";
        var obj = { from: prefix, fromport: letter, to: key };
        linkDataArray.push(obj);
      }
      model.linkDataArray = linkDataArray;
    }
    window.addEventListener('DOMContentLoaded', init);
 

Dies ist der Orginal Code, dass man da nicht suchen muss. Die Funktion ist ja, dass die einzelnen 'Decisions' über deren Namen verknüpft werden und jeweils überall die Gleiche 'Decision' ist.
Meine Idee war jetzt, die Verknüpfung statt über den Namen über einen Unsichtbaren Parameter zu führen, dass ich die Entscheidungen durchnummeriere, sprich AAAA, AAAB etc, da das ganze von der Optik vernünftig sein soll und ich jeweils gerne Erläuterungen als Text stehen haben möchte. 
Der zweite Punkt ist, dass die Fragen nicht auf jeder Ebene gleich sein sollen, ich sie also individuell in der IF Schleife definieren möchte.
Wichtig: Ich verlange hier nicht, dass mir das ganze wer programmiert, allerdings habe ich wenig Ideen, wo ich anfangen kann und wie man sowas umsetzen kann.
Ich hoffe mir kann da wer helfen.

Mit freundlichen Grüßen,
Ashriel

Drucke diesen Beitrag

  Spam gelöscht
Geschrieben von: rzscout - 10.04.2024, 23:37 - Forum: Ankündigungen,Neuigkeiten - Keine Antworten

Hi liebe Community,
es wurden zahlreiche Spam-Inhalte im Forum gelöscht. Zusätzlich versuchen wir so oft wie möglich Spam-Inhalte zu löschen.

Leider sind diese nicht immer gleich erkennbar, daher würden wir uns freuen, wenn ihr als Forum-Community Spam-Nachrichten meldet. Dafür erstellen wir euch ein eigenen Bereich, wo ihr eure Meldungen zu Spam reinschreiben dürft. Dort könnt ihr gerne die URL zu dem Thema oder Beitrag senden.

Viele Grüße

rzscout

Drucke diesen Beitrag

  Reihenfolge der Karten
Geschrieben von: hardee - 10.04.2024, 07:33 - Forum: Brauche Javascript / Userscript - Antworten (4)

hallo,
ich brauche ein js, das notiert, in welcher reihenfolge eine bestimmte anzahl von karten, die in einem karten-container liegen, angeklickt worden sind und es später in die zwischenablage transportiert
beide scipte funktionieren nicht. was ist daran falsch?

script #1

document.addEventListener('DOMContentLoaded', function() {
    let kartenReihenfolge = [];

    document.querySelectorAll('.card').forEach((card, index) => {
        card.addEventListener('click', function() {
            if (!this.classList.contains('selected')) {
                this.classList.add('selected'); 
                const kartenName = this.querySelector('.card-front').getAttribute('alt');
                const aufDemKopf = this.querySelector('.card-front').style.transform === 'rotate(180deg)';
                kartenReihenfolge.push(`${kartenName} ${aufDemKopf ? '(auf dem Kopf)' : ''}`);
            }
        });
    });
    window.kopiereInZwischenablage = function() {
        const ergebnisText = kartenReihenfolge.join('\n');
        navigator.clipboard.writeText(ergebnisText).then(() => {
            alert("Ergebnisse wurden in die Zwischenablage kopiert.");
        }, (err) => {
            console.error('Fehler beim Kopieren: ', err);
        });
    };
});

script #2

"use strict";

document.addEventListener('DOMContentLoaded', function() {
    let gezogeneKarten = [];

    document.querySelectorAll('.card').forEach(card => {
        card.addEventListener('click', function() {
            if (!this.classList.contains('selected')) {
                this.classList.add('selected');
               
                const kartenName = this.querySelector('.card-front').getAttribute('alt');
                const aufDemKopf = this.querySelector('.card-front').style.display === 'none' ? 'Nein' : 'Ja';
                gezogeneKarten.push({ kartenName, aufDemKopf });

                if (gezogeneKarten.length <= 6) {
                    console.log(`Karte gezogen: ${kartenName}, Auf dem Kopf: ${aufDemKopf}`);
                } else {
                    alert('Du kannst keine weiteren Karten auswählen.');
                }
            }
        });
    });

    function kopiereErgebnisseInZwischenablage() {
        let ergebnisText = 'Deine Auswahl:\n';
        gezogeneKarten.forEach((karte, index) => {
            ergebnisText += `${index + 1}. Karte: ${karte.kartenName}, Auf dem Kopf: ${karte.aufDemKopf}\n`;
        });

        navigator.clipboard.writeText(ergebnisText).then(() => {
            alert("Ergebnisse wurden in die Zwischenablage kopiert.");
        }, (err) => {
            console.error('Fehler beim Kopieren: ', err);
        });
    }

    document.getElementById("ergebnisse-anzeigen").addEventListener("click", kopiereErgebnisseInZwischenablage);
});

Drucke diesen Beitrag

  Formularfelder addieren und Zwischensumme ausgeben
Geschrieben von: joerg.plage@web.de - 01.04.2024, 13:39 - Forum: Javascript - Antworten (17)

Hallo Zusammen,

für einige ist mein Problem bestimmt eine Übung zum warm werden, dennoch für mich ein riesen Berg Big Grin 

Meine Familie und ich golfen für unser Leben gern an der Wii. Nach dem unsere Wii-U den Geist aufgegeben hat (CD-ROM im A*****) sind wir umgestiegen auf die Wii-Switch. Auf der 'U' gab es eine grafische Darstellung für den Fortschritt oder auch Rückschritt.auf der Switsh nicht. so habe
diese Funktion im Browser nachgebaut. (Super, funktioniert prima). die erste und zweite Hälfte  kann eingegben werden und wird dann in einer
MarieDB Tabelle gespeichert.


Nun möchte die einzelnen Ergebnis pro Loch speichern und da fängt mein Problem an. Ich habe ein Formular mit 18 Eingabefeldern (jeweil 9 pro Hälfte)
Ich möchte eine zwischenbilanz für die aktuelle Hälfte die nur angezeigt werden soll. das wollte ich mit JS machen, da es nicht gespeichert werden soll.

ein 'nice to have' : negative Ergenisse wollte ich in blau anzeigen z.B. -1 ein Paar in schwarz (0) und über Paar, also z.B eine 1, in rot.

vielen Dank für die Hilfe und Gruß Jörg

PS: ich habe den geposteten Text auch als Datei angehängt

Code:
<?php
    include("config.inc.php");
?>
<html>
    <head>
        <title>Eingabeformular</title>
        <style>
            .demo {
                border:1px solide #C0C0C0;
                border-collapse:Zusammenbruch;
                padding:5px;
            }
            .demo th {
                border:1px solide #C0C0C0;
                padding:5px;
                background:#F0F0F0;
            }
            .demo td {
                border:1px solide #C0C0C0;
                padding:5px;
            }
            input.g1 {
                color:#000000;
                background : #FFFFFF;
                border : 1px solid #FFFFFF
            }
            input#g1:focus {
                color:grey;
                background : #0000000;
            }
        </style>
        <script type="text/javascript">
            function hintergrund() {
                if (document.getElementById('g1').value == "") {
                    document.getElementById('g1').style.backgroundColor="#FFFFFF";
                } else (document.getElementkById('g1').value == '-1') {
                    document.getElementById('g1').style.backgroundColor="blue";
                }
            }
            function ersteHaelfte(player) {
                let player0 = 0;
                for (let i = 1; i < 10; i++) {
                    let player+i = document.getElementById(player+i).value;
                }
                let player+z1 = player9;
            }
            document.getElementById('volume').addEventListener('gz1', ersteHaelfte);
        </script>
    </head>
    <body>
    <form method="POST" action="">
        <input name="datum" type="hidden" style="width: 120px" value="<?php echo date('Y-m-d');?>" />
            <table class="demo">
                <caption>Ergebnis 18ner Hole <?php echo date('d.m.Y');?></caption>
                <thead>
                    <tr>
                        <th><br></th>
                        <th>1</th>    
                        <th>2</th>
                        <th>3</th>
                        <th>4</th>
                        <th>5</th>
                        <th>6</th>
                        <th>7</th>
                        <th>8</th>
                        <th>9</th>
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Gabi <br></td>
                        <td><input autofocus name="g1" type="text" style="width: 40px" tabindex="1" id="g1" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g2" type="text" style="width: 40px" tabindex="4" id="g2" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g3" type="text" style="width: 40px" tabindex="7" id="g3" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g4" type="text" style="width: 40px" tabindex="10" id="g4" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g5" type="text" style="width: 40px" tabindex="13" id="g5" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g6" type="text" style="width: 40px" tabindex="16" id="g6" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g7" type="text" style="width: 40px" tabindex="19" id="g7" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g8" type="text" style="width: 40px" tabindex="22" id="g8" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input name="g9" type="text" style="width: 40px" tabindex="25" id="g9" onChange="hintergrund();ersteHaelfte('g');" value="-1" /></td>
                        <td><input disabled name="gz1" type="text" style="width: 40px" id="gz1" /></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>Kai</td>
                        <td><input name="k1" type="text" style="width: 40px" tabindex="2" id="k1" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k2" type="text" style="width: 40px" tabindex="5" id="k2" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k3" type="text" style="width: 40px" tabindex="8" id="k3" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k4" type="text" style="width: 40px" tabindex="11" id="k4" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k5" type="text" style="width: 40px" tabindex="14" id="k5" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k6" type="text" style="width: 40px" tabindex="17" id="k6" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k7" type="text" style="width: 40px" tabindex="20" id="k7" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k8" type="text" style="width: 40px" tabindex="23" id="k8" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input name="k9" type="text" style="width: 40px" tabindex="26" id="k9" onChange="hintergrund();ersteHaelfte('k');" value="-1" /></td>
                        <td><input disabled name="kz1" type="text" style="width: 40px" id="kz1" /></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>Jörg</td>
                        <td><input name="j1" type="text" style="width: 40px" tabindex="3" id="j1" onChange="hintergrund();ersteHaelfte('j');" value="-1" /></td>
                        <td><input name="j2" type="text" style="width: 40px" tabindex="6" id="j2" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j3" type="text" style="width: 40px" tabindex="9" id="j3" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j4" type="text" style="width: 40px" tabindex="12" id="j4" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j5" type="text" style="width: 40px" tabindex="15" id="j5" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j6" type="text" style="width: 40px" tabindex="18" id="j6" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j7" type="text" style="width: 40px" tabindex="21" id="j7" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j8" type="text" style="width: 40px" tabindex="24" id="j8" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input name="j9" type="text" style="width: 40px" tabindex="27" id="j9" onChange="hintergrund();ersteHaelfte('j')" value="-1" /></td>
                        <td><input disabled name="jz1" type="text" style="width: 40px" id="jz1" /></td>
                        <td></td>
                    </tr>
                    <tr>
                        <th><br></th>
                        <th>10</th>
                        <th>11</th>
                        <th>12</th>
                        <th>13</th>
                        <th>14</th>
                        <th>15</th>
                        <th>16</th>
                        <th>17</th>
                        <th>18</th>
                        <th></th>
                        <th></th>
                    </tr>
                    <tr>
                        <td>Gabi <br></td>
                        <td><input name="g10" type="text" style="width: 40px" tabindex="28" id="g10" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g11" type="text" style="width: 40px" tabindex="31" id="g11" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g12" type="text" style="width: 40px" tabindex="34" id="g12" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g13" type="text" style="width: 40px" tabindex="37" id="g13" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g14" type="text" style="width: 40px" tabindex="40" id="g14" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g15" type="text" style="width: 40px" tabindex="43" id="g15" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g16" type="text" style="width: 40px" tabindex="46" id="g16" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g17" type="text" style="width: 40px" tabindex="49" id="g17" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="g18" type="text" style="width: 40px" tabindex="52" id="g18" onChange="hintergrund();" value="-1" /></td>
                        <td><input disabled name="gz2" type="text" style="width: 40px" id="gz2" /></td>
                        <td><input disabled name="gg" type="text" style="width: 40px" id="gg"  /></td>
                    </tr>
                    <tr>
                        <td>Kai</td>
                        <td><input name="k10" type="text" style="width: 40px" tabindex="29" id="k10" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k11" type="text" style="width: 40px" tabindex="32" id="k11" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k12" type="text" style="width: 40px" tabindex="35" id="k12" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k13" type="text" style="width: 40px" tabindex="38" id="k13" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k14" type="text" style="width: 40px" tabindex="41" id="k14" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k15" type="text" style="width: 40px" tabindex="44" id="k15" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k16" type="text" style="width: 40px" tabindex="47" id="k16" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k17" type="text" style="width: 40px" tabindex="50" id="k17" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="k18" type="text" style="width: 40px" tabindex="53" id="k18" onChange="hintergrund();" value="-1" /></td>
                        <td><input disabled name="kz2" type="text" style="width: 40px" id="gz2" /></td>
                        <td><input disabled name="kg" type="text" style="width: 40px" id="gg"  /></td>
                    </tr>
                    <tr>
                        <td>Jörg</td>
                        <td><input name="j10" type="text" style="width: 40px" tabindex="30" id="j10" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j11" type="text" style="width: 40px" tabindex="33" id="j12" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j12" type="text" style="width: 40px" tabindex="36" id="j12" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j13" type="text" style="width: 40px" tabindex="39" id="j13" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j14" type="text" style="width: 40px" tabindex="42" id="j14" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j15" type="text" style="width: 40px" tabindex="45" id="j15" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j16" type="text" style="width: 40px" tabindex="48" id="j16" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j17" type="text" style="width: 40px" tabindex="51" id="j17" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="j18" type="text" style="width: 40px" tabindex="54" id="j18" onChange="hintergrund();" value="-1" /></td>
                        <td><input disabled name="jz2" type="text" style="width: 40px" id="jz2" /></td>
                        <td><input disabled name="jg" type="text" style="width: 40px" id="jg"  /></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td colspan="18"><input name="speichern_18" type="submit" value="speichern"  tabindex="55"/> </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                <tbody>
            </table>
            <table class="demo">
                <caption>Ergebnis 3er Spezial <?php echo date('d.m.Y');?></caption>
                <thead>
                    <tr>
                        <th><br></th>
                        <th>1</th>    
                        <th>2</th>
                        <th>3</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Gabi <br></td>
                        <td><input name="gs1" type="text" style="width: 40px" tabindex="56" id="g1" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="gs2" type="text" style="width: 40px" tabindex="59" id="g1" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="gs3" type="text" style="width: 40px" tabindex="62" id="g1" onChange="hintergrund();" value="-1" /></td>
                    </tr>
                    <tr>
                        <td>Kai</td>
                        <td><input name="ks1" type="text" style="width: 40px" tabindex="57" id="g1" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="ks2" type="text" style="width: 40px" tabindex="60" id="g1" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="ks3" type="text" style="width: 40px" tabindex="63" id="g1" onChange="hintergrund();" value="-1" /></td>
                    </tr>
                    <tr>
                        <td>Jörg</td>
                        <td><input name="js1" type="text" style="width: 40px" tabindex="58" id="g1" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="js2" type="text" style="width: 40px" tabindex="61" id="g1" onChange="hintergrund();" value="-1" /></td>
                        <td><input name="js3" type="text" style="width: 40px" tabindex="64" id="g1" onChange="hintergrund();" value="-1" /></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td colspan="4"><input name="speichern_sp" type="submit" value="speichern"  tabindex="65"/> </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                <tbody>
            </table>
        </form>
    </body>
</html>
<?php
    if ( isset ($_POST["speichern_sp"]) ) {
        $into = "";
        $value = "";
        for ($i = 1; $i <= 3; $i++) {
            if ( $into == "" ) {
                $into = "g".$i.",k".$i.",j".$i;
            } else {
                $into .= ",g".$i.",k".$i.",j".$i;
            }
            if ($value == "") {
                $value = $_POST["gs".$i].",".$_POST["ks".$i].",".$_POST["js".$i];
            } else {
                $value .= ",".$_POST["gs".$i].",".$_POST["ks".$i].",".$_POST["js".$i];
            }
        }
        $sql = 'INSERT INTO tbl_spezial
                            (datum, '.$into.')
                     VALUES
                            ("'.$_POST["datum"].'", '.$value.');';
        // echo $sql;
        $db_stat = $db->prepare( $sql );
        $db_stat->execute();
    }
// ***************************
    if ( isset ($_POST["speichern_18"]) ) {
        $into = "";
        $value = "";
        for ($i = 1; $i <= 18; $i++) {
            if ( $into == "" ) {
                $into = "g".$i.",k".$i.",j".$i;
            } else {
                $into .= ",g".$i.",k".$i.",j".$i;
            }
            if ($value == "") {
                $value = $_POST["g".$i].",".$_POST["k".$i].",".$_POST["j".$i];
            } else {
                $value .= ",".$_POST["g".$i].",".$_POST["k".$i].",".$_POST["j".$i];
            }
        }
        $sql = 'INSERT INTO tbl_18_loch
                            (datum, '.$into.')
                     VALUES
                            ("'.$_POST["datum"].'", '.$value.');';
        // echo $sql;
        $db_stat = $db->prepare( $sql );
        $db_stat->execute();
        $gc1 = 0;
        $gc2 = 0;
        $kc1 = 0;
        $kc2 = 0;
        $jc1 = 0;
        $jc2 = 0;
        for ($i = 1; $i <= 9; $i++) {
            $gc1 = $gc1 + $_POST["g".$i];
            $kc1 = $kc1 + $_POST["k".$i];
            $jc1 = $jc1 + $_POST["j".$i];
        }
        for ($i = 10; $i <= 18; $i++) {
            $gc2 = $gc2 + $_POST["g".$i];
            $kc2 = $kc2 + $_POST["k".$i];
            $jc2 = $jc2 + $_POST["j".$i];
        }
        $sql = 'INSERT INTO tbl_ergebnis
                            (datum, gc1, gc2, kc1, kc2, jc1, jc2, cort, konsole)
                     VALUES
                            ("'.$_POST["datum"].'", "'.$gc1.'", "'.$gc2.'","'.$kc1.'", "'.$kc2.'", "'.$jc1.'",
                             "'.$jc2.'", "4", "s");';
        // echo $sql;
        $db_stat = $db->prepare( $sql );
        $db_stat->execute();
    }
?>



Angehängte Dateien
.php   neu_test.php (Größe: 14,53 KB / Downloads: 1)
Drucke diesen Beitrag

  Variable aus Funktion zurückerhalten
Geschrieben von: Kai_Behncke - 27.03.2024, 11:12 - Forum: Javascript - Antworten (2)

Hallo liebe Leute,

für einige ist diese Aufgabe vielleicht ganz einfach (für mich leider nicht).

Ich nutze eine API, um verschiedene Koordinatensystemsyteme umzuwandeln.

Code:
    require([
          "esri/geometry/projection"
], function(projection) { ....

Zwingend muss die Funktion über ein load().then... aufgerufen werden:
Code:
projection.load().then(function() {
var punkt2=projection.project(punkt1, cs2);
alert ("In Function: "+punkt2.x);
});

alert ("Ausserhalb Function: "+punkt2.x);

Innerhalb dieser Funktion erhalte ich auch die völlig korrekten Koordinaten (hier: punkt2.x). Jedoch: Wie kann ich auf die Variable "punkt2" ausserhalb dieser Funktion zugreifen?
alert ("Ausserhalb Function: "+punkt2.x);  sagt mir, dass die Variable nicht existiert.

Irgendwie stehe ich da völlig auf dem Schlauch. Kann mir da jemand einen Tipp geben?
Danke im voraus :-)

Drucke diesen Beitrag

  Probleme mit Canvas
Geschrieben von: Derbestetv - 25.03.2024, 13:54 - Forum: Javascript - Antworten (5)

Hallo ich habe ein Problem mit canvas 
hier ist der code da hab ich kommentiert welche zeilen der fehler macht
(ich weiß ich bin kein profi und das mit dem einrücken muss ich noch machen das ist je erstmal nur ein test)

Code:
function layout(ctx,x,y,typ,name,richtung,color_top,color_bottom,color_weiche){
console.log(x+" "+y+" "+color_top)
//ctx.fillStyle = '#8b8c7a'; // Roter Hintergrund
//    ctx.fillRect(x+ 1, y+ 1, 139, 71);
if (typ == "Signal"){
    if (richtung == "0"){

console.log("test")
}else{
    ctx.fillStyle = color_top;
            ctx.beginPath();
            ctx.fillRect(x + 1, y + 1, 139, 30);


            ctx.fillStyle = color_bottom;
            ctx.beginPath();
            ctx.fillRect(x + 1, y + 30, 139, 41);

            var xh = x + 120;
            var yh = y + 56;
            ctx.fillStyle = "#000000";
                    ctx.beginPath();
                    ctx.fillRect(xh - 85, yh - 11, 42, 22);

                    ctx.fillStyle = "#FFFFFF";
                    ctx.beginPath();
                    ctx.fillRect(xh - 84, yh - 10, 40, 20);


                    ctx.fillStyle = "#000000";
                    ctx.font = "bold 12px Arial";
                    var width = ctx.measureText(name).width;
                    ////("_______________________");
                    ////(width);
                    ////("_______________________");
                    ctx.fillText(name, xh - 57 - width, yh + 4);
                    var xd = xh + 1;

                    ctx.fillStyle = "#000000";
                    ctx.beginPath();
                    ctx.arc(xd - 30, yh - 40, 7, 300, Math.PI * 2 / 4, false);
                    ctx.fill();
                    ctx.beginPath();
                    ctx.fillRect(xd - 100, yh - 47, 70, 14);
                    ctx.fill();
                    ctx.beginPath();
                    ctx.arc(xd - 100, yh - 40, 7, 900, Math.PI * 2 / 1.3, false);
                    ctx.fill();
                    ctx.beginPath();
                    ctx.fillRect(xd - 25, yh - 42, 10, 4);
                    ctx.fill();
                    ctx.beginPath();
                    ctx.fillRect(xd - 15, yh - 47, 5, 14);
                    var xs = xd - 30;
                    var ys = yh + 4;
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(xh, yh, 5, 1, Math.PI * 2 / 0.1, false);
ctx.arc(xd, yh - 40, 5, 1, Math.PI * 2 / 0.1, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(xd - 120, yh - 25, 139, 10);
ctx.fill();







    ctx.beginPath();
    //ctx.arc(xd, yh, 3.5, 1, Math.PI * 2 / 0.1, false);
    ctx.arc(xd - 78, yh - 40, 5, 1, Math.PI * 2 / 0.1, false);
    ctx.arc(xd - 98, yh - 40, 5, 1, Math.PI * 2 / 0.1, false);

    //ctx.arc(xh, yh, 3.5, 1, Math.PI * 2 / 0.1, false);

    //ctx.arc(xd, yh - 40, 3.5, 1, Math.PI * 2 / 0.1, false);
//ctx.moveTo(xs, ys - 40);
//ctx.lineTo(xs - 8, ys - 48);
//ctx.lineWidth = 3;


ctx.arc(xd, yh, 3.5, 1, Math.PI * 2 / 0.1, false);//diese Zeile und die darunter siend die die das problem verursachen
ctx.arc(xd, yh - 40, 3.5, 1, Math.PI * 2 / 0.1, false);

ctx.moveTo(xd - 30, yh + 4);
                    ctx.lineTo(xd - 40, yh - 0);
                    ctx.lineTo(xd - 30, yh - 4);

ctx.rect(xd - 70, yh - 22, 40, 4);

ctx.arc(xd - 70, yh - 20, 2, 900, Math.PI * 2 / 1.3, false);
ctx.arc(xd - 30, yh - 20, 2, 300, Math.PI * 2 / 4, false);

    ctx.closePath();
    ctx.clip();
}
}
}
Hier ist das Bild von dem Fehler

Drucke diesen Beitrag

  HTML Tabelle filtern + Navigation mit Pfeiltasten
Geschrieben von: anfaenger - 23.03.2024, 17:20 - Forum: Javascript - Antworten (1)

Hallo zusammen,

ich würde mir gerne eine "Link-Liste" in HTML erstellen. In dieser möchte ich alle für mich wichtigen Links eintragen. 
Wenn ich die HTML Seite aufrufe, möchte ich ein Textfeld haben, in dem ich die Tabelle nach dem Suchtext filtern kann.

Soweit habe ich das - als blutiger Anfänger - auch schon zusammen-ge-googelt...  Shy

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Linkliste</title>
<style>
    <!-- color every other table cell background-->
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 10px;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 
}

th {text-align:center}

tr:nth-child(even) {background-color: #adadad;}
tr:nth-child(odd) {background-color: #dad8d8;}
</style>


</head>
<body>

    <script>
        function searchTable() {
            var input, filter, found, table, tr, td, i, j;
            input = document.getElementById("FilterText");
            filter = input.value.toUpperCase();
            table = document.getElementById("URLTable");
            tr = table.getElementsByTagName("tr");
            for (i = 1; i < tr.length; i++) {
                td = tr[i].getElementsByTagName("td");
                for (j = 0; j < td.length; j++) {
                    if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                        found = true;
                    }
                }
                if (found) {
                    tr[i].style.display = "";
                    found = false;
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
        </script>


    <center>
<h1>LINK LISTE</h1>
<p><i>lorem ipsum</i></p>
</center>

<p><br></p>
<p><strong> Filter:</strong>    <input id='FilterText' onkeyup='searchTable()' type='text'autofocus> <button onclick=location.reload()>Clear input field</button> </p>
<p>  </p>
<p><br></p>
<table id='URLTable'>
   
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D</th>
            <th>COMMENTS / NOTES</th>
        </tr>
   
    <tbody>
        <tr style=" cursor: pointer;" onclick="window.open('https://www.google.de')">
            <td>Germany</td>
            <td>Earth</td>
            <td>search01.google.com</td>
            <td>physical x86 Server</td>
            <td>Testing</td>
        <tr/>                                             
        <tr style=" cursor: pointer;" onclick="window.open('https://www.google.de')">
            <td>Germany</td>
            <td>Earth</td>
            <td>search02.google.com</td>
            <td>physical x86 Server</td>
            <td>Testing</td>
        <tr/>          
        <tr style=" cursor: pointer;" onclick="window.open('https://www.google.de')">
            <td>Germany</td>
            <td>Earth</td>
            <td>search03.google.com</td>
            <td>Virtual Machine</td>
            <td>Testing</td>
        <tr/>                                                                                
        </tbody>   
</table>

</body>
</html>

Der nächste Schritt wäre, dass ich - nachdem ich gefiltert habe - mit den Pfeiltasten den richtigen Eintrag auswählen kann, und den Link dann mit ENTER aufrufen kann.

Das will aber nicht so recht funktionieren. Da ich nicht wirklich programmieren kann, sondern eher "Fundstücke" irgendwie zuammen würfele, sieht der aktuelle Code ("verschönert" durch den Bing CoPilot) im Moment so aus:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Link Liste</title>
<style>
    <!-- color every other table cell background-->
table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  text-align: left;
  padding: 10px;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 
}

th {text-align:center}

tr:nth-child(even) {background-color: #adadad;}
tr:nth-child(odd) {background-color: #dad8d8;}
</style>


</head>
<body>

    <script>
        var selectedRow = null;

        function searchTable() {
            var input, filter, found, table, tr, td, i, j;
            input = document.getElementById("FilterText");
            filter = input.value.toUpperCase();
            table = document.getElementById("URLTable");
            tr = table.getElementsByTagName("tr");
            for (i = 1; i < tr.length; i++) {
                td = tr[i].getElementsByTagName("td");
                for (j = 0; j < td.length; j++) {
                    if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                        found = true;
                    }
                }
                if (found) {
                    tr[i].style.display = "";
                    found = false;
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

        function selectRow(row) {
            if (selectedRow) {
                selectedRow.style.backgroundColor = "";
            }
            selectedRow = row;
            selectedRow.style.backgroundColor = "yellow";


        document.getElementById("FilterText").addEventListener("keydown", function(event) {
            if (["ArrowDown", "ArrowUp", "Enter"].includes(event.key)) {
                navigateTable(event);
            }
        });
        function attachKeydownToRows() {
        var table = document.getElementById("URLTable");
        var cells = Array.from(table.getElementsByTagName("td"));
        cells.forEach(cell => {
            cell.addEventListener("keydown", function(event) {
                if (["ArrowDown", "ArrowUp", "Enter"].includes(event.key)) {
                    navigateTable(event);
                }
            });
        });
    }

        function navigateTable(event) {
            var table = document.getElementById("URLTable");
            var rows = Array.from(table.getElementsByTagName("tr")).filter(row => row.style.display !== "none");
            var currentIndex = rows.indexOf(selectedRow);
            if (event.key === "ArrowDown") {
                if (currentIndex < rows.length - 1) {
                    selectRow(rows[currentIndex + 1]);
                }
            } else if (event.key === "ArrowUp") {
                if (currentIndex > 0) {
                    selectRow(rows[currentIndex - 1]);
                }
            } else if (event.key === "Enter" && selectedRow) {
                selectedRow.click();
            }
        }
    }


    </script>

    <center>
<h1>LINK LISTE</h1>
<p><i>lorem ipsum</i></p>
</center>

<p><br></p>
<p><strong> Filter:</strong>    <input id='FilterText' onkeyup='searchTable()' type='text'autofocus> <button onclick=location.reload()>Clear input field</button> </p>
<p>  </p>
<p><br></p>
<table id='URLTable'>
   
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D</th>
            <th>COMMENTS / NOTES</th>
        </tr>
   
    <tbody>
        <tr tabindex="0" style=" cursor: pointer;" onclick="window.open('https://www.google.de')">
            <td>Germany</td>
            <td>Earth</td>
            <td>search01.google.com</td>
            <td>physical x86 Server</td>
            <td>Testing</td>
        <tr/>                                             
        <tr tabindex="0" style=" cursor: pointer;" onclick="window.open('https://www.google.de')">
            <td>Germany</td>
            <td>Earth</td>
            <td>search02.google.com</td>
            <td>physical x86 Server</td>
            <td>Testing</td>
        <tr/>          
        <tr tabindex="0" style=" cursor: pointer;" onclick="window.open('https://www.google.de')">
            <td>Germany</td>
            <td>Earth</td>
            <td>search03.google.com</td>
            <td>Virtual Machine</td>
            <td>Testing</td>
        <tr/>                                                                                
        </tbody>   
</table>

</body>
</html>

Als Fortschritt sehe ich schon einmal an, dass ich jetzt aus dem Input-Field mit TABULAR in die Liste springen kann, und mit weiterem TABULAR durch die angezeigten Zeilen.
Aber optimal wäre es für mich (der mit DOS aufgewachsen ist  Angel) wenn das mit den Pfeiltasten möglich wäre und ich mit ENTER den Link aufrufen könnte.

Ich vermute, dass ich irgendwie aus der `searchTable()` Funktion wieder raus muss, wenn KEY_DOWN erkannt wurde.

Leider komme ich damit nicht weiter und bin am Verzweifeln.

Vielleicht hat einer der Profis einen Tip für mich? 

Vielen Dank im Voraus,

liebe Grüße!

Drucke diesen Beitrag