Javascript - Get text value from select list - javascript

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;

Related

Clone selected dropdown value after page redirect

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');

set default value to more than 1 product ID using javascript

I have set default value to an input box and set it to readonly.
I also disable some select options.
It is working but when I add another ID for another product, only 1 ID works.
Please note that I don't have access to the actual html pages. I can only access the js file.
What I need is:
if I go to product 1 OR product 2, I will see the text box is set to 28 in readonly and the Weeks/Months disabled.
Below is my sample HTMLs.
The HTMLs below are two different HTML pages.
HTML for product 1
<p>Deliver products every <input type="text" id="thisInput_prod1"></p>
<select id="thisSelect_prod1">
<option value="Days" selected>Days</option>
<option value="Weeks">Weeks</option>
<option value="Month">Month</option>
</select>
HTML for product 2
<p>Deliver products every <input type="text" id="thisInput_prod2"></p>
<select id="thisSelect_prod2">
<option value="Days" selected>Days</option>
<option value="Weeks">Weeks</option>
<option value="Month">Month</option>
</select>
This is the .js file
window.onload = SetDefaultValue;
function SetDefaultValue() {
document.getElementById('thisInput_prod1').setAttribute('value','28');
document.getElementById('thisInput_prod1').readOnly = true;
var x = document.getElementById('thisSelect_prod1');
x.options[1].disabled=true;
x.options[2].disabled=true;
//below is to set the other product - I disable because its not working
//document.getElementById('thisInput_prod2').setAttribute('value','28');
//document.getElementById('thisInput_prod2').readOnly = true;
//var y = document.getElementById('thisSelect_prod2');
//y.options[1].disabled=true;
//y.options[2].disabled=true;
}
When there's no thisInput_prod2 element, document.getElementById('thisInput_prod2') will evaluate to null, and then the code will abort trying to call .setAttribute on that null. You should assign it to a variable and test it to see if it's === null before dereferencing it.
Here is your working example : Fiddle
document.getElementById('thisInput_prod1').value = '28';
document.getElementById('thisInput_prod1').readOnly = true;
var x = document.getElementById('thisSelect_prod1');
x.options[1].disabled = true;
x.options[2].disabled = true;
document.getElementById('thisInput_prod2').readOnly = true;
var y = document.getElementById('thisSelect_prod2');
y.options[1].disabled=true;
y.options[2].disabled=true;

Php and Jquery, How do i post a option selected value into a span

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.

Get value of span that is dynamically changed by a select box

I have an ecommerce website with a <span> that contains the SKU of each product on the product detail page as follows:
<span class="VariationProductSKU">052077</span>
When the customer selects a size in the following <select> menu...
<div class="productOptionViewSelect">
<select id="4ab0094cccc675de3daaa83d6b1819e2" class="validation" name="attribute[110]">
<option selected="selected" value=""> -- Please Choose an Option -- </option>
<option value="69">S</option>
<option value="70">M</option>
<option value="71">L</option>
<option value="72">XL</option>
<option value="73">XXL</option>
</select>
</div>
the SKU displayed in the <span> tag is dynamically updated as follows (in this example, they selected size "L"):
<span class="VariationProductSKU">052077.L</span>
I need to get the value of the <span> tag containing the new dynamically updated SKU using jQuery. I've tried the following jQuery code, but it seems to always be passing me back the previous value of the <span> tag and not the new value.
if ($('div.productAttributeList').html() !== ''){
$("div.productOptionViewSelect select").on( 'change', function () {
var val = "";
val = $('span.VariationProductSKU').text().trim();
alert(val);
});
}
Any insight into how I can get the correct value from the <span> tag would be greatly appreciated!
Try waiting a bit for the remote script to finish:
if ($('div.productAttributeList').html() !== '') {
$("div.productOptionViewSelect select").on('change', function () {
var val = "";
setTimeout(function() {
val = $('span.VariationProductSKU').text().trim();
alert(val);
}, 50); // adjust this value until it's working reliably
});
}

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Categories

Resources