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
});
}
Related
I'm working on an html page that will allow users to get pre-populated text filled into the text input field, based on the option they select. I'm trying to do this via javascript but I can't get the function to "fire" when I do an onchange within the select input field.
Trying to figure out what I'm doing wrong, either with the function, the innerHTML, or both.
Example code I'm working on below:
HTML
<label for='accountg'>Goal</label>
<select id="accountg" name="accountg" style="border-radius:1px;border:1px solid #003399;font-size:14px;width:50px;" onchange="accountSelect()">
<option value=''></option>
<option value='1'></option>
<option value='2'></option>
<option value='3'></option>
<option value='4'></option>
<option value='5'></option>
</select>
<input type="text" id="account1" name="account1" style="width:900px;" title="140 character maximum" />
JAVASCRIPT
function accountSelect() {
var aSelect = document.getElementById('accountg').value;
var account1 = '';
if(aSelect == '') {
} else if(aSelect == 1){
if(account1 == '')
{
var act1 = 'Outlines written policies and procedures to ensure consistent adherence by staff.';
document.getElementById('account1').innerHTML = act1;
} else {}
}
}
<input> doesn't have an inner content, it has a value though:
document.getElementById('account1').value = act1;
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;
Goal: Have a select whose option have nested structure when user clicks on the select, but when user selects an option the option should be displayed "normally" (ie with no leading spaces).
Attempted solution using JS and Jquery: My JS is far from sophisticated so I apologize in advance :)
I attempted to use .on("change") and .on("click") to change the selected option value (by calling .trim() since I achieve the "nested" structure with ). I'm also storing the original value of the selected option because I want to revert the select menu to its original structure in case the user selects another option.
The problem: The function registered for .on("click") is called twice, thus the select value immediately resets itself to its original value.
I suspect there is a much, much easier solution using CSS. I will be happy to accept an answer that will suggest such solution.
JSFiddle: https://jsfiddle.net/dv6kky43/9/
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
<textarea id="output"/>
var orig;
var output = $("#output");
output.val("");
function onDeviceSelection(event){
output.val(output.val() + "\nonDeviceSelection");
var select = event.target;
orig = select.selectedOptions[0].text;
select.selectedOptions[0].text = select.selectedOptions[0].text.trim()
}
function resetDeviceSelectionText(event) {
output.val(output.val() + "\nresetDeviceSelectionText");
var select = event.target;
if (orig !== undefined){
select.selectedOptions[0].text = orig;
}
}
$("#select").on("change", onDeviceSelection);
$("#select").on("click", resetDeviceSelectionText);
If you are already using jQuery, why not utilize data function to store the original value. This way you will also be able to specify different nest levels.
(function($){
$(document).on('change', 'select', function(event) {
$(this).find('option').each(function(index, element){
var $option = $(element);
// Storing original value in html5 friendly custom attribute.
if(!$option.data('originalValue')) {
$option.data('originalValue', $option.text());
}
if($option.is(':selected')) {
$option.html($option.data('originalValue').trim());
} else {
$option.html($option.data('originalValue'));
}
})
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
Once caveat I see is, the selected option will appear trimmed on the list as well, if dropdown is opened after a previous selection has been made:
Will it still work for you?
Instead of keeping the state of the selected element i would simply go over all options and add the space if that option is not selected:
function onDeviceSelection(event){
// Update textarea
output.val(output.val() + "\nonDeviceSelection");
// Higlight the selected
const {options, selectedIndex} = event.target;
for(let i = 0; i < options.length; i++)
options[i].innerHTML = (i === selectedIndex ? "":" ") + options[i].text.trim();
}
$("#select").on("change", onDeviceSelection);
Note that you need to use innerHTML to set the whitespace...
I need to change the 'selected' attribute of a html option element within a select object using javascript.
I already tried this: Solution
This is what I have:
.cshtml
<div class="form-group form-group-default" id="divStateEUA">
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA" data-init-plugin="select2" style="width: 100%">
#foreach (var state in ViewBag.EUAStates)
{
<option>#state</option>
}
</select>
</div>
javascript
<script>
$(document)
.ready(function () {
CheckState();
});
function CheckState() {
if (selectedText == 'Estados Unidos') {
var element = document.getElementById('listStateEUA');
element.value = 'Chicago';
}
}
</script>
rendered html:
And still not working. Any ideas?
You are missing value attribute in the option tag of select.
Modify your razor code to have value attribute in option tag, so that you can change the combo-box selection on basis of value :
#foreach (var state in ViewBag.EUAStates)
{
<option value="#state">#state</option>
}
and now in your jquery code, you should be able to do :
function CheckState() {
if (selectedText == 'Estados Unidos') {
$("#listStateEUA").val("Chicago");
}
}
You must provide a value for the options. Your JS is trying to set the select to the "Chicago" value, but none exists. <option>Chicago</option> vs <option value="Chicago">Chicago</option>
function CheckState() {
var element = document.getElementById('listStateEUA');
element.value = 'chicago';
}
CheckState();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA">
<option value="nevada">nevada</option>
<option value="chicago">chicago</option>
<option value="arizona">arizona</option>
</select>
As Mike McCaughan suggested (thank you very much), since I'm using select2 plugin, it have a different way to get and set values.
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
Answer found here: select2 plugin get and set values
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');