Is it possible at all to be able to assign the selected value of a select and assign it to the variable of a script and re-run the script?
Here is my current code sample:
<select onchange="reload_script;">
<option value="123">Select 123</option>
<option value="456">Select 456</option>
<select>
<div id="123">
link title
<br/><br/>
Link
</div>
<script language="javascript" type="text/javascript">
var code = '123' // <-- THIS VARIABLE WOULD BE THE VALUE OF THE SELECTED DROPDOWN VALUE
</script>
See: var code = '123' .... That's what's changed when the select box is changed ... then I would need the script to re-run...
Is this possible at all?
If you use jQuery you can always bind change event:
var code = "123";
$("#mySelect").on("change", function() {
code = this.value;
reload_script();
});
Otherwise, in plain JavaScript it may look like this:
var code = "123";
document.getElementById("mySelect").onchange = function() {
code = this.value;
reload_script();
};
Try this
<select onchange="reload_script();">
<option value="123">Select 123</option>
<option value="456">Select 456</option>
<select>
<div id="123">
link title
<br/><br/>
Link
</div>
<script language="javascript" type="text/javascript">
var code = '123' // <-- THIS VARIABLE WOULD BE THE VALUE OF THE SELECTED DROPDOWN VALUE
function script_to_run()
{
//do code here
}
// Call the script one time on page load (only if you need it on page load)
script_to_run();
function reload_script()
{
script_to_run();//run again
}
</script>
Related
I am using Countries.js to populate countries and states to a website. I need to set default a country on load and show respective states in select state input. How can it be done?
I have tried Couple of things from the internet.
1.
<script>populateCountries("us", "state");</script>;
2.
In Core file -->
if (stateElementId) {
countryElement.onchange = function() {
populateStates(countryElementId, stateElementId);
//populateStates( "us", stateElementId );
};
}
But it is not working.
To set a default country onload, first populate the countries select element with countries using the load document event listener, then get the country select element object by id e.g. countryElement. Using that, set the value to a default country e.g. 'USA', and trigger onchange() on the element to populate the states select box. The below example does this, and then triggers a new country selection after 5 seconds to showcase further the state select box changing.. You selected jQuery tag for this question, but I didn't see any jQuery in your example so I kept it to straight vanilla JS for the example.
$(document).ready(function() {
populateCountries("country", "state");
$countryElement = $('#country');
$stateElement = $('#state');
$countryElement.val('USA').trigger('change');
$stateElement.val('Florida');
setTimeout(function() {
$countryElement.val('American Samoa').trigger('change');
$stateElement.val('Eastern');
}, 5000);
});
/*
document.addEventListener("load",
populateCountries("country", "state")
);
var countryElement = document.getElementById('country');
var stateElement = document.getElementById('state');
// Set default country
countryElement.value = 'USA';
// Triggers state select population..
countryElement.onchange();
// Set state for country selected..
stateElement.value = 'Florida';
// 5 seconds later, select a different country..
setTimeout(function() {
countryElement.value = 'American Samoa';
countryElement.onchange();
stateElement.value = 'Eastern';
}, 5000);
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-toggle-group="location">
<div class="form-group">
<label>Country</label>
<select class="form-control" name="country" id="country" data-toggle="country" data-country=""></select>
</div>
<div class="form-group">
<label>State</label>
<select class="form-control" name="state" id="state" data-toggle="state" data-state=""></select>
</div>
</div>
<script type="text/javascript" src="https://www.cssscript.com/demo/generic-country-state-dropdown-list-countries-js/countries.js"></script>
you can use the Jquery document ready function like below. But you have to include the jquery.
<script type="text/javascript">
$(document).ready(function() {
populateCountries("us", "state");
});
</script>
you can see the more detail here at below link.
http://learn.jquery.com/using-jquery-core/document-ready/
You should be able to get it right by setting its value:
$('select').val('stateElementId')
or by the text inside the <option></option>
$('select option:contains("us")').prop('selected',true);
In my application, I want to let user select an option from the drop down menu at anytime. But when the page reloads, it goes back to the default value (the first element in the drop down list).
My HTML looks like this:
<select class="author">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
In my javascript, i use the following for letting the user select an option:
auid = $('#tabs' .author option:selected').prop('value');
I am actually retrieving the value of author that was selected before page reloads from the localstorage by:
auid = localStorage.getItem("latestAuthor");
Can someone tell me how does this all fit together with example code snippet to let me select an option from drop down menu, and the same option stays selected when the page reloads, but the user can select another option from the drop down menu at anytime as well.
On page load, once that select box exists, and once you've retrieved auid from local storage, do this:
if (auid !== null) {
$("#tabs .author").val(auid);
}
The if is there because if you've never set the value in local storage, that's what you'll get back from getItem.
Side note: When getting the value, don't use prop('value'). Use .val:
auid = $("#tabs .author").val();
Complete example on jsFiddle (since Stack Snippets don't allow local storage ☹ ). This assumes it's in a script tag at the end of the HTML, just before the closing </body> tag (which is where you should put them unless you have a good reason not to).
// Scoping function to avoid global vars
(function() {
var auid = localStorage.getItem("latestAuthor");
if (auid !== null) {
$("#tabs .author").val(auid);
}
$("#tabs .author").on("change", function() {
auid = $(this).val();
localStorage.setItem("latestAuthor", auid);
});
})();
If for some reason you can't put the script tag at the very end, you can use jQuery's "DOM ready" callback:
jQuery(function() {
var auid = localStorage.getItem("latestAuthor");
if (auid !== null) {
$("#tabs .author").val(auid);
}
$("#tabs .author").on("change", function() {
auid = $(this).val();
localStorage.setItem("latestAuthor", auid);
});
});
(You can cache the result of $("#tabs .author") in a variable if you want to avoid doing it twice, but doing it twice on page load is nothing.)
Works fine for me.
Possible typo error
auid = $('#tabs' .author option:selected').prop('value');
^
Sample:
$(".btn").on("click", function() {
var auid = $('#tabs .author option:selected').prop('value');
console.log(auid);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tabs">
<select class="author">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
</div>
<button class="btn">Click Me</button>
Also for sample of integrating with LocalStorage, check following code:
Note: Stackoverflow does not allows to access localStorage and you should test it on fiddle.
JSFiddle
var _lsKey = "test";
function registerEvents(){
$(".btn").on("click", function() {
var auid = $('#tabs .author option:selected').prop('value');
saveValueToLS(_lsKey, auid);
});
}
function saveValueToLS(key, value){
localStorage.setItem(key, value);
}
function getValueFromLS(key){
return localStorage.getItem(key);
}
function initializeSelect(){
var lsVal = getValueFromLS(_lsKey);
$(".author").val(lsVal);
}
function initializePage(){
registerEvents();
initializeSelect();
}
initializePage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tabs">
<select class="author">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
</div>
<button class="btn">Click Me</button>
I am trying to pass value stored inside a div tag to a javascript function based on the onchange property of a drop down menu in HTML.
But nothing is being passed. Undefined error is shown.
Here my code:
Suppose $temp_c has a value 30.
<span id="temperature_div"><?php echo $temp_c; ?></span>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(this.value,temperature_div.value,temperature_div.name); ">
<option value="celcius" selected>°C</option>
<option value="farenheit">°F</option>
</select>
And JavaScript
function choose_temperature(conv, value, name) {
alert(conv);
alert(value);
alert(name);
}
Where did I go wrong??
In JavaScript you can't just use temperature_div as a variable and assume it will be the object with id temperature_div. There are functions for fetching elements from the DOM. In plain JavaScript: document.getElementById('temperature_div') will return the element. If you're using JQuery, then $('#temperature_div') will do a similar thing.
Edit:
Try this function:
function choose_temperature(conv) {
alert(conv);
var element = document.getElementById('temperature_div');
alert(element.innerHTML);
alert(element.attributes["name"].value);
}
Called by: choose_temperature(this.value);
Edit: Changed to use innerHTML and attributes["name"].value instead of value and name. I'm assuming that these are what are wanted.
First of all you have used the parameter 'value' which I think is a key word and better not to use.
and I am assuming you are referring to the 'name' html attribute in the 'temperature_div', which you have not defined. I am putting a name attribute just for the sake of understanding.
<html>
<script type="text/javascript">
function choose_temperature(conv, t_value, name)
{
alert(conv);
var div = document.getElementById("temperature_div");
alert(div.innerHTML);
alert(div.getAttribute("name"));
}
</script>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(this.value); ">
<option value="celcius" selected>°C</option>
<option value="farenheit">°F</option>
</select>
Use jquery instead, it is easier.
Get value inside a div as: $('#temperature_div').html() Or $('#temperature_div').text()
You can write onchange for a select box as:
$(document).on('change', '#ddl_temptype', function() {
// Write your function here
var div_value = $('#temperature_div').html();
var select_val = $(this).val();
alert(div_value);
});
Or like this
$('#some_id').on('change', function() {
// Write your function here
var div_value = $('#temperature_div').html();
var select_val = $(this).val();
alert(div_value);
});
Use getElementById() in javascript
<span id="temperature_div"><?php echo $temp_c; ?></span>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(); ">
<option value="celcius" selected> °C</option>
<option value="farenheit"> °F</option>
</select>
function choose_temperature()
{
var value=document.getElementById('temperature_div').innerHTML; //to get html inside span
var conv=document.getElementById('ddl_temptype').value;
alert(conv);
alert(value);
}
<script type="text/javascript">
var productStoreId = $('#productStoreId').val(); //productStoreId on change event
</script>
<select name="productStoreId" id="productStoreId">
<option value='' selected="selected">Select Location</option>
<#list productStoreList as store>
<option value='${store.productStoreId}'>${store.storeName}</option>
</#list>
</select>
<#assign AvblCrseList=prodStoreCoursesMap.get(${productStoreId})>// but productStoreId is undefined here.
I want productStoreId in a variable, because I have a map "prodStoreCoursesMap". I have to access it using the key productStoreId.
I want to access a map using the variable in the script tag as a key in the code in html/ftl.
<script type="text/javascript">
var productStoreId = $('#productStoreId').val(); // productStoreId on change event
</script>
This will only work at launch but won't update as you select from the dropdown.
Try this:
var productId;
$('#productStoreId').on('change', function(){
productId = $(this).val();
});
Currently I have a basic javascript which will alert the value of a selection. I would like to tie this into a javascript function so instead of alerting the value, it replaces the value within the script.
<script type="text/javascript">
function cselect(){
var CID = document.getElementById('country').value;
alert(CID);
}
</script>
<select id="country" onchange="cselect()">
<option value="4242">US</option>
<option value="4243">Canada</option>
</select>
I would like to pass the option value into the script below in place of the static value. Any help greatly appreciated!
<script>// <![CDATA[
cii_EmbedProductLinks('Chairs','{{ prodID }}','4242', CI_LinkID);
// ]]></script>
Maybe something like this:
var sub = $("body").html().replace('4242',CID);
$("body").html(sub);