I have two selection boxes, the default value is - and i want to pick something else for both, my first problem is both fields have dynamic id like prod-685209-Size so i'm having trouble accessing with id.
I have the following HTML:
<select class="sku-attr" name="Size">
<option value="_def">-</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<select class="sku-attr" name="Color">
<option value="_def">-</option>
<option value="Black">Black</option>
<option value="Blue">Blue</option>
</select>
So i executed the following:
document.getElementsByTagName('select')[0].selectedIndex = 2
document.getElementsByTagName('select')[1].selectedIndex = 2
It worked on the front side, showing my new options but it didn't prompt the backend as it is not actually selecting the options. Backend works fine when i click to these options by hand, basically i need another solution to choose these options.
If I don't misunderstood your requirement then you need something like this. Just add two different ids to your select element and attach a change event listener. For example size and color
var s = document.getElementById("size");
var c = document.getElementById("color");
function getSize() {
sizeSelected = s.value;
console.log('size=' + sizeSelected);
}
function getColor() {
colorSelected = c.value;
console.log('color=' + colorSelected);
}
s.addEventListener('change', getSize);
c.addEventListener('change', getColor);
<select id="size" class="sku-attr" name="Size">
<option value="_def">-</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<select id="color" class="sku-attr" name="Color">
<option value="_def">-</option>
<option value="Black">Black</option>
<option value="Blue">Blue</option>
</select>
You need to add .validate() after your dom commands to actually prompt the page.
Related
What I'm trying is something pretty basic, but I can't do it because the examples I see aren't anything similar to what I'm looking for.
There are 2 select, one of them you choose manually and the other dynamically changes depending on the value of the first one.
If the value of the first select is 1, that in the second one they only appear whose value is 1 as well.
I want to make it 100% JavaScript, I don't want any JQuery.
HTML.php
<select onchange="catch_value_types()" name="types" id="types">
<option value="1">Meat</option>
<option value="2">Fish</option>
<option value="3">Vegetables</option>
</select>
<select name="food" id="food">
<option value="1">Pork</option>
<option value="1">Cow</option>
<option value="1">Chicken</option>
<option value="2">Sardine</option>
<option value="2">Salmon</option>
<option value="2">Mackerel</option>
<option value="3">Spinach</option>
<option value="3">Kale</option>
<option value="3">Green peas</option>
</select>
JavaScript.js
function catch_value_types() {
var types_value_option = document.getElementById("types").value;
// What should I put here?
}
Loop through the options and hide if value doesnot match
function catch_value_types() {
const selectedValue = document.getElementById("types").value;
const select2 = document.getElementById("food");
Array.from(select2.options).forEach((node) => node.style.display = node.value === selectedValue ? "block": "none");
}
<select onchange="catch_value_types()" name="types" id="types">
<option value="1">Meat</option>
<option value="2">Fish</option>
<option value="3">Vegetables</option>
</select>
<select name="food" id="food">
<option>Please Select</option>
<option value="1">Pork</option>
<option value="1">Cow</option>
<option value="1">Chicken</option>
<option value="2">Sardine</option>
<option value="2">Salmon</option>
<option value="2">Mackerel</option>
<option value="3">Spinach</option>
<option value="3">Kale</option>
<option value="3">Green peas</option>
</select>
I have multiple dropdown selections on a single page with exact same options but different IDs. I need dropdown A and B to have the same option selected at all times but only if they both share those options.
I'm a javascript noob so I've tried many variations of code but nothing works, I think it's best if someone could write this simple code from scratch.
Imagine these two selections with cloned options:
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
If you select red in ID california it needs to switch to red in ID texas, and vice versa.
You can add a common class and select on the change event something like following
Jquery
$(document).ready(function(){
$(".select").change(function() {
$(".select").not(this).find("option[value="+ $(this).val() + "]").attr('selected', true)
});
});
Pure JavaScript Solution as already written by #Emeeus
const selectElement = [...document.getElementsByClassName("ClassName")];
selectElement.forEach(a => {
a.addEventListener("change", (e) => {
selectElement.forEach(aa => {
if (aa.querySelectorAll(`option[value=${e.target.value}]`).length)
aa.value = e.target.value;
})
})
})
A simple way to get this done is :
reference the select elements in JavaScript and store the two of them in an array.
when looping through the selects we can store the index of the current select, that has to be used to get the other select (a simple mathematical calculation).
loop through that array (that means looping through the selects) and attach a change event listener to each one of the select elements.
fetch the option that has to be selected, if found, after filtering the options of the other select based on the value of the selected option.
if there's an option that has the same value as the selected option, select that option in the other select.
This may still a bit ambiguous, a demo is worth a hundred docs :
the next demo takes into consideration that an/some option(s) may not appear in both of the select elements, simply nothing will happen and the same functionality stays as is.
/** an array that stores the selects **/
const selects = [document.getElementById('california'), document.getElementById('texas')];
/** ## cycle through these selects
* el: current select in the loop.
* idx: its index in the "selects" array.
**/
selects.forEach((el, idx) => {
/** attach change listener **/
el.addEventListener('change', () => {
/** get the option that should be selected in the other select if found there **/
/** "selects[Math.abs(idx - 1)]" gets the other select (the one that isn't changed) **/
const toBeSelected = [...selects[Math.abs(idx - 1)].options].filter(o => o.value === el.options[el.selectedIndex].value);
/** if we have an option from the other select's options that has the same value as the selected one then return in order to be selected **/
/** if ther's an option that matches the above condition simply select it **/
toBeSelected[0] && (selects[Math.abs(idx - 1)].selectedIndex = toBeSelected[0].index);
});
});
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<!-- new option that doesn't exist in the other select element -->
<option value="green">green</option>
</select>
The ideal solution would be using classes, but with that HTML here a solution:
const selects = [...document.getElementsByTagName("select")];
selects.forEach(s => {
s.addEventListener("change", (e) => {
selects.forEach(sl => {
if (sl.querySelectorAll(`option[value=${e.target.value}]`).length)
sl.value = e.target.value;
})
})
})
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="las_vegas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
this is very simple code :
<select id="california" onclick="applyEvent()">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>
<select id="texas" onclick="apply_Event()">
<option value="red"">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="brown">brown</option>
</select>
<script type="text/javascript">
function applyEvent() {
document.getElementById("texas").value = document.getElementById('california').value;
}
function apply_Event() {
document.getElementById("california").value = document.getElementById('texas').value;
}
</script>
<select id="california">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<select id="texas">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<script>
var californiaSelect = document.getElementById('california');
var texasSelect = document.getElementById('texas');
californiaSelect.addEventListener('change', () => {
texasSelect.value = californiaSelect.value;
})
texasSelect.addEventListener('change', () => {
californiaSelect.value = texasSelect.value;
})
</script>
You can find a working example is this fiddle
getElementById
addEventListener
I'm a rookie when it comes to Javascript.
First thanks for all of your answers.
Please follow under codes.
I made like this.
This is crawler htmls one section.
<select data-js="career-select" data-group-id="stats">
<option value="0x02E00000FFFFFFFF" option-id="ALL HEROES">ALL HEROES</option>
<option value="0x02E0000000000002" option-id="Reaper">Reaper</option>
<option value="0x02E0000000000003" option-id="Tracer">Tracer</option>
<option value="0x02E0000000000004" option-id="Mercy">Mercy</option>
<option value="0x02E0000000000005" option-id="Hanzo">Hanzo</option>
<option value="0x02E0000000000006" option-id="Torbjörn">Torbjörn</option>
<option value="0x02E0000000000007" option-id="Reinhardt">Reinhardt</option>
<option value="0x02E0000000000008" option-id="Pharah">Pharah</option>
<option value="0x02E0000000000009" option-id="Winston">Winston</option>
<option value="0x02E000000000000A" option-id="Widowmaker">Widowmaker</option>
<option value="0x02E0000000000015" option-id="Bastion">Bastion</option>
<option value="0x02E0000000000016" option-id="Symmetra">Symmetra</option>
<option value="0x02E0000000000020" option-id="Zenyatta">Zenyatta</option>
<option value="0x02E0000000000029" option-id="Genji">Genji</option>
<option value="0x02E0000000000040" option-id="Roadhog">Roadhog</option>
<option value="0x02E0000000000042" option-id="McCree">McCree</option>
<option value="0x02E0000000000065" option-id="Junkrat">Junkrat</option>
<option value="0x02E0000000000068" option-id="Zarya">Zarya</option>
<option value="0x02E000000000006E" option-id="Soldier: 76">Soldier: 76</option>
<option value="0x02E0000000000079" option-id="Lúcio">Lúcio</option>
<option value="0x02E000000000007A" option-id="D.Va">D.Va</option>
<option value="0x02E00000000000DD" option-id="Mei">Mei</option>
<option value="0x02E000000000012E" option-id="Sombra">Sombra</option>
<option value="0x02E000000000013B" option-id="Ana">Ana</option>
</select>
This is server side jQuery part.
var quick_data = $(`#quickplay select[data-group-id="stats"]`);
quick_data.each(function() {
var test= $(this).find("option").attr('value');
console.log('test : ' + test);
})
I tried and got values(like '0x230000000fffffffffff') but if I use server side jQuery send like this
test : 0x02E00000FFFFFFFF
Just 1.. just one!!
Why this just works one?
Thank you for read my foolish code and English
Thank you and Regards
Why this just works one?
Because there's only one select, so your each callback is called only once, and it grabs the value of the first option within it (because that's how attr, val, prop, and such work when you use them as getters*).
If you want each value, you can loop through the options:
$(`#quickplay select[data-group-id="stats"] option`).each(function(){
console.log('test : ' + this.value);
});
Example:
$(`#quickplay select[data-group-id="stats"] option`).each(function() {
console.log('test : ' + this.value);
});
<div id="quickplay"><select data-js="career-select" data-group-id="stats">
<option value="0x02E00000FFFFFFFF" option-id="ALL HEROES">ALL HEROES</option>
<option value="0x02E0000000000002" option-id="Reaper">Reaper</option>
<option value="0x02E0000000000003" option-id="Tracer">Tracer</option>
<option value="0x02E0000000000004" option-id="Mercy">Mercy</option>
<option value="0x02E0000000000005" option-id="Hanzo">Hanzo</option>
<option value="0x02E0000000000006" option-id="Torbjörn">Torbjörn</option>
<option value="0x02E0000000000007" option-id="Reinhardt">Reinhardt</option>
<option value="0x02E0000000000008" option-id="Pharah">Pharah</option>
<option value="0x02E0000000000009" option-id="Winston">Winston</option>
<option value="0x02E000000000000A" option-id="Widowmaker">Widowmaker</option>
<option value="0x02E0000000000015" option-id="Bastion">Bastion</option>
<option value="0x02E0000000000016" option-id="Symmetra">Symmetra</option>
<option value="0x02E0000000000020" option-id="Zenyatta">Zenyatta</option>
<option value="0x02E0000000000029" option-id="Genji">Genji</option>
<option value="0x02E0000000000040" option-id="Roadhog">Roadhog</option>
<option value="0x02E0000000000042" option-id="McCree">McCree</option>
<option value="0x02E0000000000065" option-id="Junkrat">Junkrat</option>
<option value="0x02E0000000000068" option-id="Zarya">Zarya</option>
<option value="0x02E000000000006E" option-id="Soldier: 76">Soldier: 76</option>
<option value="0x02E0000000000079" option-id="Lúcio">Lúcio</option>
<option value="0x02E000000000007A" option-id="D.Va">D.Va</option>
<option value="0x02E00000000000DD" option-id="Mei">Mei</option>
<option value="0x02E000000000012E" option-id="Sombra">Sombra</option>
<option value="0x02E000000000013B" option-id="Ana">Ana</option>
</select></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
* jQuery is set-based. In your original code, $(this).find("option") returned a set of option elements (all of them), but when you use a getter on the set, it only gets from the first element in the set. (In contrast, jQuery's setters update all elements in the set; the API is assymmetrical.) There's one exception to this: text, when used as a getter, gets the text of all of the elements in the set. (I have no idea why it's different from all the others.)
it looks like your jQuery foreach has the wrong selector. You're doing foreach on the select, not the options with in the select. Try this
var quick_data = $(`#quickplay select[data-group-id="stats"] > option`);
$(`#quickplay select[data-group-id='stats'] option`)
This will grab all options under id quickplay where select has the attribute data-group-id stats.
vs.
$(`#quickplay select[data-group-id='stats']`)
This will grab all selects under #quickplay (with the data-group-id being stats).
Then you add:
.each(function() {
console.log($(this).find("option").attr("value"));
});
And, now, we're iterating through all of our selects and printing the first
option. When you use functions like .attr() on multiple elements,
it will take the value from only the first one. It does not return an array.
$(`#quickplay select[data-group-id='stats'] option`).each(function(){
var test= $(this).attr('value');
console.log('test : ' + test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quickplay">
<select data-js="career-select" data-group-id="stats">
<option value="0x02E00000FFFFFFFF" option-id="ALL HEROES">ALL HEROES</option>
<option value="0x02E0000000000002" option-id="Reaper">Reaper</option>
<option value="0x02E0000000000003" option-id="Tracer">Tracer</option>
<option value="0x02E0000000000004" option-id="Mercy">Mercy</option>
<option value="0x02E0000000000005" option-id="Hanzo">Hanzo</option>
<option value="0x02E0000000000006" option-id="Torbjörn">Torbjörn</option>
<option value="0x02E0000000000007" option-id="Reinhardt">Reinhardt</option>
<option value="0x02E0000000000008" option-id="Pharah">Pharah</option>
<option value="0x02E0000000000009" option-id="Winston">Winston</option>
<option value="0x02E000000000000A" option-id="Widowmaker">Widowmaker</option>
<option value="0x02E0000000000015" option-id="Bastion">Bastion</option>
<option value="0x02E0000000000016" option-id="Symmetra">Symmetra</option>
<option value="0x02E0000000000020" option-id="Zenyatta">Zenyatta</option>
<option value="0x02E0000000000029" option-id="Genji">Genji</option>
<option value="0x02E0000000000040" option-id="Roadhog">Roadhog</option>
<option value="0x02E0000000000042" option-id="McCree">McCree</option>
<option value="0x02E0000000000065" option-id="Junkrat">Junkrat</option>
<option value="0x02E0000000000068" option-id="Zarya">Zarya</option>
<option value="0x02E000000000006E" option-id="Soldier: 76">Soldier: 76</option>
<option value="0x02E0000000000079" option-id="Lúcio">Lúcio</option>
<option value="0x02E000000000007A" option-id="D.Va">D.Va</option>
<option value="0x02E00000000000DD" option-id="Mei">Mei</option>
<option value="0x02E000000000012E" option-id="Sombra">Sombra</option>
<option value="0x02E000000000013B" option-id="Ana">Ana</option>
</select>
</div>
So I am a newbie on Wordpress working with a theme to make a car platform. Unfortunately, on the theme, the car-selling functionalities differ from what we need. One of those things is: show or hide options based on previous selection with dropdown lists.
Quick example: If 'BMW' is chosen on 'Make', then only show '1 series' '3 series' '5 series' on 'Model', if '3 series is chosen, then only show 318i 320i 330i on 'Engine', aso. From a logical point of view, it is so easy, but I have no clue how to translate this into code. Luckily, I've found pretty good code here already, but this works only for the next dropdown list. My question is, how does the javascript/jquery code have to look like so you can make more than 2 conditional dropdown lists? You could take Engine as an example. Thank you
HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="req_make">Make</label>
<select id="req_make" name="make">
<option disabled="disabled" selected="selected" value="">Choose Make</option>
<option class="BMW" value="BMW">BMW</option>
<option class="Audi" value="Audi">Audi</option>
<option class="VW" value="VW">VW</option>
</select>
<label for="req_model">Model</label>
<select id="req_model" name="model">
<option disabled="disabled" selected="selected" value="">Choose model</option>
<option class="BMW" value="1er">1er</option>
<option class="BMW" value="3er">3er</option>
<option class="BMW" value="5er">5er</option>
<option class="BMW" value="7er">7er</option>
<option class="Audi" value="A4">A4</option>
<option class="Audi" value="A8">A8</option>
<option class="Audi" value="Q7">Q7</option>
<option class="VW" value="Golf">Golf</option>
<option class="VW" value="Touran">Touran</option>
</select>
<label for="req_engine">Engine</label>
<select id="req_engine" name="engine">
<option disabled="disabled" selected="selected" value="">Choose engine</option>
<option class="BMW" value="7er">7er - 730i</option>
<option class="BMW" value="7er">7er - 730Li</option>
<option class="BMW" value="7er">7er - 735i</option>
</select>
Javascript code:
$(function(){
$("#req_make").on("change",function(){
var levelClass = $('#req_make').find('option:selected').attr('class');
console.log(levelClass);
$('#req_model option').each(function () {
var self = $(this);
if (self.hasClass(levelClass) || typeof(levelClass) == "undefined") {
self.show();
} else {
self.hide();
}
});
});
});
You can specify any number of selectors to combine into a single result. So change $('#req_model option').each(function () { ... to $('#req_model option, #req_engine option').each(function () { ... to solve this.
I just did it on my own. It is working, but of course I don't know if it's the right way to do it. I am taking the value of the former list and assigning it to the class of the next, while changing attr('class') to attr('value'). https://jsfiddle.net/agdkw1xm/
I am designing a webform that may capture anywhere from 1 to 150 rows of data giving definitions to what type of data is provided in a given row of a csv. These rows of data are all exactly same but I do not know how many of them will be used at the outset. I would like to start with one row and let the end user click an add button to add a new row. On the W-3 schools website there was a small tutorial on how to do this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_create
but there are some problems I am seeing. first, it is buggy. If you go to the link and click the 'try it' button it will create a simple select dropdown. Wonderful! However, If you click it again it then creates a blank one, with every subsequent click creating the same. The other problem is that the select element I would need to use is huge (160 possible options) and uses optgroups to keep it separated and intuitive here is a sample:
<select name="data_value" id="data_value_selector">
<optgroup label="Entity Provider">
<option style="margin-left:12px;" value="name">Name</option>
<option style="margin-left:12px;" value="dba">DBA</option>
<option style="margin-left:12px;" value="facility_type">Facility Type</option>
</optgroup>
<optgroup label="Individual Provider"></optgroup>
<optgroup style="margin-left:12px;" label="Name">
<option value="full_name">Full Name</option>
<option value="name_prefix">Prefix</option>
<option value="first_name">First Name</option>
<option value="middle_name">Middle Name</option>
<option value="last_name">Last Name</option>
<option value="name_suffix">Suffix</option>
<option value="pro_suffix">Professional Suffix</option>
</optgroup>
<optgroup style="margin-left:12px;" label="Birth Date">
<option value="full_birth_date">Full Birth Date</option>
<option value="day_of_birth">Day Of Birth</option>
<option value="month_of_birth">Month Of Birth</option>
<option value="year_of_birth">Year Of Birth</option>
</optgroup>
<optgroup style="margin-left:12px;" label="Education">
<option value="education_institution">Education Institution</option>
<option value="education_city">Education City</option>
<option value="education_county">Education County</option>
<option value="education_state">Education State</option>
<option value="education_country">Education Country</option>
<option value="education_start_date">Education Start Date</option>
<option value="education_end_date">Education End Date</option>
<option value="graduation_date">Graduation Date</option>
<option value="degree" >Degree</option>
</optgroup>
<optgroup label="Provider Information"></optgroup>
<optgroup style="margin-left:12px;" label="Address">
<option value="full_address">Full Address</option>
<option value="address_1">Address 1</option>
<option value="address_2">Address 2</option>
<option value="address_city">City</option>
<option value="address_county">County</option>
<option value="address_state">State</option>
<option value="address_zip_code">Zipcode</option>
<option value="address_country">Country</option>
<option value="address_csz">City/State/Zip</option>
</optgroup>
<optgroup style="margin-left:12px;" label="Phone">
<option value="phone_number">Number</option>
<option value="phone_extension">Extension</option>
</optgroup>
<optgroup style="margin-left:12px;" label="Singular Values">
<option value="url">URL</option>
<option value="tin">TIN Number</option>
<option value="email">Email</option>
<option value="dea_registration_number">DEA Regisration Number</option>
<option value="npi_number">NPI Number</option>
<option value="upin_number">UPIN Number</option>
</optgroup>
<optgroup style="margin-left:12px;" label="Provider Values">
<option value="provider_value">Provider Value</option>
</optgroup>
</select>
...And this is not even the entire select object. In the W-3 tutorial it builds each element independently as variables and adds them to each other individually. As you can see this might take some time to write and just seems very bulky. I would like to define the select object once and have it replicated that way (if possible) with every click. I imagine each newly created select object would need a unique name, but I am not 100% sure on that. If that is the case, is there a way to just append a 1 to the name of the first one and so on?
If you want something in jQuery you can use clone() function. See:
$("#data_value_selector").clone().appendTo("#select-box");
Demo.
I changed the name attribute to send a collection of the selected values. You can change this behaviour to a custom name in the click event, if you want:
var newSelect = $("#data_value_selector").clone();
newSelect.attr("name", "newName");
newSelect.appendTo("#select-box");
I hope this helps you.
You could use the cloneNode() method. Here is an example:
http://jsfiddle.net/JKNT4/7/
HTML
<button onclick="addRow()">Add Row</button>
<div id="parent_selector" class="data-row">
<select name="data_value[]">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div id="child_selectors"></div>
Javascript
function addRow() {
var itm = document.getElementById("parent_selector");
var cln = itm.cloneNode(true);
cln.removeAttribute("id");
document.getElementById("child_selectors").appendChild(cln);
}