简体   繁体   中英

How do I show a selected option on two different identical webpages?

I'm pretty new to webpage and HTML, and I'm not sure what the easiest way to solve this program is. I have a basic webpage that I get data from a tag, and then I have a button to push it to a part on the webpage.

HTML

<div id="footer">
   <p id="selectedEvent">Event</p>
</div>

<select id="currentEvent">
   <option value="" disabled selected>Current Event</option>
   <option value="1">Option 1</option>
   <option value="2">Option 2</option>
   <option value="3">Option 3</option>
</select>
<button type="button" onclick="GetSelectedText()">Push Changes</button>

JS

function GetSelectedText() {
   var e = document.getElementById("currentEvent");
   var result = e.options[e.selectedIndex].text;
   document.getElementById("selectedEvent").innerHTML = result;
}

What I want this to do is update text on another instance of this code running in another tab, so that both webpages display the selected option after it is pushed on one of them. What's the easiest way to do this?

EDIT I'm gonna briefly explain my use case just to get more useful responses. I'm using this as an overlay and interface for OBS as a browser source, so the solution needs to basically be able to sync across different browsers (ex Chrome and Firefox)

Thanks in advance!

Is this what you want?

var e = document.getElementById("currentEvent");

function GetSelectedText() {
    var selected = e.options[e.selectedIndex];
    document.getElementById("selectedEvent").innerHTML = selected.text;

    if (typeof(Storage) !== "undefined") { 
        localStorage.setItem("s_option", selected.text);
        localStorage.setItem("s_option_value", selected.value);
    }
}

function show_result() {
    document.getElementById("selectedEvent").innerHTML = localStorage.getItem("s_option");
    document.getElementById("currentEvent").value = localStorage.getItem("s_option_value");
}

window.addEventListener("storage", show_result);
e.addEventListener("change", GetSelectedText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM