I'm making a website that needs to have an interface where I can select an option and push that option, which updates text on that same website running in a different browser. So far I have the code that allows me to update the text on the first browser, but not the other one.
HTML
<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;
}
I only need to update one line of text on each browser, so please keep this as simple as possible as I'm still learning HTML and am new to web development.
Thanks in advance :)
took me a bit.. made an example with repl.it.. don't mind the C file, I just like the C for the free environment.. focus on the backend.js and frontend.html
The concept is that each tab/client gets a new key, the client sends its key, looking for data in return in a loop, when there is data, it puts the element document.getElementById("selectedEvent") .innerHTML with the response text. In the button however, it sends a post that will put text into server object's key of the tab that shares the inputted key. That combination of scouting data and placing data makes it work like a charm
backend.js
var http=require('http')
var fs=require('fs')
function randomChar(){
var m=Math.random; var f=Math.floor
var arr=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
0,1,2,3,4,5,6,7,8,9,"!","#","$","&","*","(","-","_","=","+","[","]","'","~"]
var newChar=""
for(var i=0; i<f(m()*100+20); i++){newChar+=arr[f(m()*arr.length)]}
return newChar
}
var obj={}
function frontEnd(){
var specialChar=randomChar(); obj[specialChar]=""
return `<script>window.key="${specialChar}"</script>`+
fs.readFileSync(__dirname + '/frontend.html')
.toString().split('')
.map(a=>{if(a=="\\"){return(specialChar)}return(a)})
.join('')
}
//server stuff below
var server=http.createServer((req,res)=>{
if(req.method=="GET"){res.write(frontEnd())}
else if(req.method=="POST"){
if(req.headers.pw&&req.headers.inp){
if(obj[req.headers.pw]!=undefined){obj[req.headers.pw]=req.headers.inp}
}
else if(req.headers.receive&&req.headers.key){
res.write(obj[req.headers.key]||"")
}
else if(req.headers.end=="yes"&&req.headers.key){
delete(obj[req.headers.key])
console.log(`a key ${req.headers.key} was deleted`)
}
}
res.end()
})
server.listen(8080)
frontend.html
<html>
<h3>for this tab manipulation, so that you cannot edit all tabs connected to this site, you need to know the <bold>KEY</bold> of someone else's tab</h3>
<p>your key is <bold>\</bold></p>
<input placeholder="enter other tab's key here" id="inp" />
<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>
<h4 id="selectedEvent"></h4>
<script>
//loop checking for incoming changes (empty input("") means it would me treated as no input)
var select=document.getElementById("selectedEvent");
(async()=>{
var options={
method:'POST',
headers:{'receive':'true','key':key}
}
while(true){
let x=await fetch(location.href,options)
let text=await x.text()
if(text){select.innerHTML=text}
}
})()
//now for the button
function GetSelectedText() {
var e = document.getElementById("currentEvent");
var result = e.options[e.selectedIndex].text;
select.innerHTML = result;
//sends an outgoing request that will edit the other tab
var xhr=new XMLHttpRequest()
xhr.open('POST',location.href,true)
var inp=document.getElementById('inp')
xhr.setRequestHeader('pw',inp.value)
xhr.setRequestHeader('inp',result)
xhr.send()
}
//now for a listener that will attempt to delete the key from the server as it closes
window.onbeforeunload = async function(){
await fetch(location.href,{method:'POST',headers:{'end':'yes'}})
//put return in front of the 'await' word in line above
//and a confirm would appear when you try to close
}
</script>
</html>
Related
So i want to make a table that i can fill up with info.
I've managed to fill one cell with a value of a text box. But i can't do the same with drop-down lists.
I've created the list:
<select name="status">
<option value="10 perces">10 perces</option>
<option value="ebéd">ebéd</option>
<option value="egyéb">egyéb</option>
</select>
And tried to get the value or text:
var tstatus = document.getElementById("status");
var result = tstatus.options[tstatus.selectedIndex].text;
document.getElementById("result").innerHTML = result;
I dont know where is the issue, the value extracting code is wrong, or the array filler.
Full code down below
Full code
Picture
Your using a wrong selector, you should be using:
// use querySelector as theres is no element with the id of "status" in your html
var tstatus = document.querySelector("[name='status']");
var result = tstatus.options[tstatus.selectedIndex].text;
// you also need an element to set the inner HTML to
document.getElementById("result").innerHTML = result;
<!-- Updated HTML -->
<select name="status">
<option value="10 perces">10 perces</option>
<option value="ebéd">ebéd</option>
<option value="egyéb">egyéb</option>
</select>
<span id="result"></span>
// Updated Javascript
var tstatus = document.querySelector("[name='status']");
var result = tstatus.options[tstatus.selectedIndex].text;
document.getElementById("result").innerHTML = result;
I'm learning jquery... This is my problem, I need to clone the value selected from web page 1 and redirect webpage1 to webpage2...
I found some codes here and tried to combine them...but the code below only redirects and does not clone dropdown value to webpage2 based on the selected value from webpage1....
function moveTo(optionValue) {
if(optionValue=="") return false;
window.location='.htm'+optionValue;
}
var $orginalDiv = $('#container');
var $clonedDiv = $orginalDiv.clone();
//get original selects into a jq object
var $originalSelects = $orginalDiv.find('select');
$clonedDiv.find('select').each(function(index, item) {
//set new select to value of old select
$(item).val( $originalSelects.eq(index).val() );
});
$clonedDiv.appendTo('clonedItem')
WebPage1 Dropdown List
<div id="container">
<p>Priority</p>
<select name="priority" id="drop1" size="1" onchange="moveTo(this.options[this.selectedIndex].value);">
<option value="form2.html">Low</option>
<option value="form2.html">Normal</option>
<option value="form2.html">High</option>
<option value="form2.html">Emergency</option>
</select>
</div>
WebPage2 Dropdown List
<div id='clonedItem'>
<p>Priority</p>
<select name="priority" id="drop2" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</div>
Please advise on how to fix this or if there is another way aside from using jquery...Thanks.
Since the page refreshes, you can not store variable is js directly. There are different ways to achieve what you want. If i understand correctly, the two selects are the same, so they have the same options. for this, i would say the "GET" parameter is the most usefull. in your redirect function just add the index of selected option as a GET to the redirect URL:
function moveTo(optionValue) {
if(optionValue=="") return false;
window.location='http://newURL.com'+"?index="+optionValue;
}
Then you just need a js function on the new page which can filter the GET parameter out of the location:
function parse(val) {
var result = "Not found",
tmp = [];
location.search.substr(1).split("&").forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
});
return result;
}
(see this aswer for src)
Then finally call the parse function on pageload on the new page and make the option active:
var index = parse(window.location);
$('#drop2 option').eq(index[0]).addClass('selected');
I want to post a value of a selected option into a span/label without submit button?, how do I do that?
I've already did it with a input text box but with a selection option I just can't...
Here's my actual code:
<script type="text/javascript">
function calculateTotal() {
var totalAmt = document.addem.total.value;
totalR = eval(document.addem.tb1.value * 0.8);
document.getElementById('update').innerHTML = totalR;
}
</script>
<div id="swag">
<form name="addem" id="addem">
<select name="simulate_option" id="simulate_opt">
<option value="EUR" selected="selected">EUR</option>
<option value="USD">USD</option>
<option value="CHF">CHF</option>
<option value="GBP">GBP</option>
<option value="RON">RON</option>
<option value="CZK">CZK</option>
<option value="NOK">NOK</option>
<option value="DKK">DKK</option>
<option value="LVL">LVL</option>
<option value="TRY">TRY</option>
<option value="HRK">HRK</option>
<option value="SEK">SEK</option>
<option value="PLN">PLN</option>
<option value="HUF">HUF</option>
<option value="MXN">MXN</option>
<option value="CAD">CAD</option>
</select>
<input type="text" name="tb1" onkeyup="calculateTotal()"/>
<span class="swag" id="update">0</span>
<input type="hidden" name="total" value="0"/>
</form>
this piece of javascript code should help.
//runs when a value is changed in the combobox.
var dropdown = document.getElementById("simulate_opt");
dropdown.onchange = function(event){
//loads data from combobox.
var val = dropdownoptions[simulate_opt.slectedIndex].value;
//CHANGE THESE 2 strings.
Ajax("id of div to be changed", "url to the php file", array(val));
}
//A basic dynamic javascript function for AJAX
//div is div to be changed, url = url to php file.
//vars = array with items to be send via Post
function Ajax(div, url, vars){
var xml = new XMLHttpRequest(); //wont work in ie7 or lower
xml.onreadystatechange=function(){
if(xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;
}
};
xml.open("POST",URL,true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
sendXML(xml, vars);
}
function sendXML(xml, vars){
var send = "";
var i = 1;
for(var x in vars){
y = vars[x];
send = send+"&var"+i+"="+y;
i++;
}
xml.send(send);
}
Then have a php file like this.
<?php
$var = $_POST['var1'] //loads the selected value
echo $var; //shows selected value.
?>
The Ajax function can be used to realtime update the page without need for refreshing.
it calls to a php script which then can modify a div with echo. give the Ajax function the ID of a div that will be changed by php, the url to php and put any variables php needs from the client in an array as the third variable.
//for instance
Ajax("header", "loadHeader.php", Array("hello"."world");
//In php the array items are obtainable as follows.
$_POST['var1']; // this is "hello"
$_POST['var2']; // this is "world"
//if any more array items were added they would've been.
$_POST['var3']; //etc for as much as were set.
I have some code which is working perfectly after the second page refresh. Basically I have a drop down selection, the selection appends a sort order to the end of the URL,upon the selection of this sort order the page is refreshed.
Here is where my problem is on this post back the cookie does not seem to keep the users selection, however subsequent page refreshes or even through the paging of the catalouge the cookie keep the users selection which is perfect, it's just that first page load after the selection.
Here is the code I have
<!-- List header -->
<select id="Selection" class="sorter" onchange="document.cookie= 'myDDIdx = ' + this.selectedIndex + '; path=/;';location=this.options[[this.selectedIndex]].value" style="float:right;margin-right:8px;">
<option value="">Sort by</option>
<option value="?orderby=0">Code</option>
<option value="?orderby=1">Title A-Z</option>
<option value="?orderby=2">Title Z-A</option>
<option value="?orderby=3">Brand</option>
<option value="?orderby=4">Lowest price</option>
<option value="?orderby=5">Highest price</option>
<option value="?orderby=6">Lowest Quantity</option>
<option value="?orderby=7">Highest Quantity</option>
</select>
<div style="clear:both;"></div>
<script>
var sidx = document.cookie.indexOf("myDDIdx");
if(sidx != -1)
window.onload = function () { document.getElementById("Selection").selectedIndex = document.cookie.substr(sidx + 8,1); }
</script>
Is anyone able to suggest how I can fix this behavior? Code snip-its are appreciated.
I believe the way you were obtaining the cookie wasn't working correctly. I've changed the code slightly to work properly. Also note when changing the page use window.location not just location.
window.onload = function () {
var cookies = document.cookie,
sidx = !!cookies ? cookies.match(/myDDIdx=([0-9]+?);?/) : false;
if (!!sidx && sidx.length >= 2) {
document.getElementById("Selection").selectedIndex = sidx[1];
}
};
document.getElementById("Selection").onchange = function () {
document.cookie = 'myDDIdx=' + this.selectedIndex + '; path=/;';
window.location = this.options[[this.selectedIndex]].value;
};
DEMO
I have a form on a page with two inputs. On submission, I would like the page redirected to a link that contains the values of the two inputs, plus a preceding string. The html is the following:
<form name="searchForm">
<label for="property_type">Property Type</label>
<select name="property_type" id="property_type_number">
<option value>- All Property Types -</option>
<option value="1432">Commercial</option>
<option value="1433">Land</option>
<option value="1434">MultiFamily</option>
<option value="1435">Rental</option>
<option value="1436">Residential</option>
<option value="1988">Residential / Condo</option>
<option value="1987">Residential / Single Family</option>
</select>
<label for="city">City</label>
<select name="city" id="city_number">
<option value>- All Property Types -</option>
<option value>--</option>
<option value="cambridge">Cambridge</option>
<option value="zanesville">Zanesville</option>
</select>
<input type="submit" value="Search for Properties" onclick="searchform()">
</form>
And the Javascript is the following:
function searchform()
{
var propertyType = document.getElementById("property_type_number").value;
var city = document.getElementById("city_number").value;
target = "/idx/?" + city + propertyType + "hi";
document.searchForm.action = target;
}
When I submit the form, it seems to only use the first string of the target variable ("/idx/?") but ignore the rest. It then inserts the values from the form automatically. I would like it to go to a custom target such as the one above.
If you want to see it on the web, the address is: http://lainegabriel.net/ (it is the last widget on the left).
Well, I can't explain why the form behaves as such, or why it doesn't work, since it would appear that every bit of information online says to do exactly what you're doing.. I can however, provide a work-around:
Firstly, change your html to this, deleting the 'onclick' from the submit button, and replacing the form tag:
<form name="searchForm" onsubmit="return searchform();">
Secondly, in your searchform() function:
function searchform() {
var propertyType = document.getElementById("property_type_number").value;
var city = document.getElementById("city_number").value;
target = "/idx/?" + city + propertyType + "hi";
document.searchForm.action = target; // I just left this in here just in case you wanted it.
window.location.href = target; // redirect the window to the new url/action
return false; // prevent the default submit action from occurring
}
Demo
change this:
var propertyType = document.getElementById("property_type_number").value;
var city = document.getElementById("city_number").value;
with this:
var select = document.getElementById("property_type_number");
var propertyType = select.options[ select.selectedIndex ].value;
select = document.getElementById("city_number");
var city= select.options[ select.selectedIndex ].value;
Any difference?
i know its bigger in code but i never had problems with that (before i switched to jquery and forget all these kind of problems..)