My apologies if this has been answered before but I did do a search and haven't seen any answers for the questions asked in other posts. The answers I did see didn't relate to my question (mostly to do with dropdowns getting results from mysql).
I have a php dropdown list where you need to select a value (1, 2 or 3). Based on what you select, the list should update a variable and show a hidden div tag. Now from the information I gathered it seems like this cannot be done with php alone but requires a javscript or ajax script.
php:
<form>
<select name="options" onchange="{dosomething}">
<option value="0">[Select value]</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
</form>
This should then update this variable and div in REALTIME:
<div id="test" style="display:none">
$answer= 1 + $value
<?php
echo "1 + $value = $answer";
</div>
javascript/ajax:
<script>
function dosomething {
#update $value based on dropdown and do calculation
#unhide div with id "test"
}
</script>
I need to mention that I have no knowledge of javascript or ajax.
If you only need to view the new result in the same page without requesting something to the server add this script below your last div:
<script>
var element = document.getElementsByName('options');
if( element.length > 0 ){
element[0].addEventListener('change',update_text,false);
//element[0].addEventListener('change',function(){update_text(param)},false);
}
function update_text(evt){
console.log(evt);
var first_element = evt.target;
var selection = first_element.options[first_element.selectedIndex].value;
//do math:
selection = +selection + 1; //this cast selection as number and not as String
console.log(selection);
var test = document.getElementById('test');
test.style.display = 'block';
test.innerHTML = `<p>${selection}</p>`;
};
</script>
Related
I'm trying to create a cookie to store a value from a select form field - I'v been trying different options but unsuccessful everytime 😥 - can someone please help me?
The site is currently on Drupal but I'm wanting to add via Tag Manager, so any help with vanilla JS would be amazing
The Hubspot form in question can be located: https://www.huddle.com/get-started
The select field is : Comapany Size
The value I'm trying to target is the first option: 1-10
This is my code:
<script>
var formField = document.querySelector('form["name="size_of_organisation__c"]').value;
var formValue = "1-10";
var cookieName = sizeOfOrg;
var cookieValue = smb;
if (formField == formValue) {
document.cookie = "cookieName=cookieValue";
}
</script>
Any help would be much appreciated
Humm,
it seems you are using react, so it will be definitely nice to create this process in a react fonction inside your form component, etc.
I'm not really sure of your needs, but this code retrieve the value of the dropdown on change and add it in a cookie :
<html>
<body>
<form>
<select name="size_of_organisation__c">
<option value="" disabled="" selected="">Please Select</option>
<option value="1-10">1-10</option>
<option value="11-50">11-50</option>
<option value="51-200">51-200</option>
<option value="201-500">201-500</option>
<option value="501-1000">501-1000</option>
<option value="1001-5000">1001-5000</option>
<option value="5001-10000">5001-10000</option>
<option value="10001+">10001+</option>
</select>
</form>
</body>
<script src="./temp.js"></script>
</html>
//selector to select dropdown. return an array so take the first one
var select = document.getElementsByName("size_of_organisation__c")[0];
console.log(select);
// add event handler to update the cookie each time you change the select
select.addEventListener("change", function() {
document.cookie = "sizeOfOrg=" + select.value;
console.log(document.cookie);
});
edit: add the html and the console.log() to debug
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 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
});
}
I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>
I am making a simple web app that has drop down list in the first page in a form tags.
Now when I change the value in the dropdown the form is submitted. On the onchange I have made call to create a query string custom JS function of the selected Index.
Now I want the drop down list to maintain its state; keep the last selected value selected after submission.
How can I do this?
You add the selected attribute with any (e.g. blank) value to the you want to keep selected.
The getQueryValue function is a bit unoptimized and would probably be better accomplished with a regular expression match to get the value, but I just typed it out like this so you could see what it was doing.
<html>
<head>
<script type="text/javascript">
function setSelections()
{
document.myForm.mySelect.value = getQueryValue("mySelect");
};
function getQueryValue(key)
{
var queryString = window.location.search.substring(1);
var queryParams = queryString.split("&");
for(var i = 0; i < queryParams.length; i++)
{
if(queryParams[i].indexOf("=") > 0)
{
var keyValue = queryParams[i].split("=");
if(keyValue[0] == key)
{
return keyValue[1];
}
}
}
return null;
}
</script>
</head>
<body onload="setSelections();">
<form name="myForm" action="" method="get">
<select id="mySelect" name="mySelect" onchange="document.myForm.submit();">
<option value="Opt1">Option 1</option>
<option value="Opt2">Option 2</option>
<option value="Opt3">Option 3</option>
<option value="Opt4">Option 4</option>
</select>
</form>
</body>
</html>
Depends on how your page is dealt with after submission, if it goes to a PHP/Perl or whatever language to rebuild the page, then put the drop down options into a script and loop through them.
Something like this is pretty common place
for($i = 0; $i < 10; $i++){
echo "<option value='{$i}' ";
($i == $_POST['dropdownname'])? echo "selected='selected'":"";
echo ">{$i}</option>";
}
You could pass a hidden form variable to the next posted page. Using a simple Javascript function that loops through the options of the selection drop-down list, if any of the options match the hidden value, then set its selected sttribute.