I need help solving a simple requirement.
<select id="my-select1">
<option value="1">This is option 1 ({myop1}|OP)</option>
<option value="2" selected>This is option 2 ({myop1}|OQ)</option>
<option value="3">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="1">This is option 1 ({myop2}|PP)</option>
<option value="2">This is option 2 ({myop2}|PQ)</option>
<option value="3" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="1">This is option 1 ({myop3}|QP)</option>
<option value="2">This is option 2 ({myop3}|QQ)</option>
<option value="3" selected>This is option 3 ({myop3}|QR)</option>
</select>
See the HTML above, I want to recreate my array:
combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
INTO
combo = ["abc-OQ-PR", "def-PR"];
based on the selected options.
Another thing to note is that I cannot simply change the value of the options of the select box, meaning to say the HTML is somewhat as it is, if it would help, the only part i can restructure on that HTML is the text content between <option></option>
I'm not sure, but I'm already spending a couple of hrs just to solve this problem. Maybe due to my limited jQuery knowledge.
Please help. thanks
Get the selected values into an associative array:
var pattern = {};
var s = $('select option:selected').each(function(){
var m = /\((.*?)\|(.*)\)/.exec($(this).text());
pattern[m[1]] = m[2];
});
Then you can replace each place holder in each string in the array with the corresponding value:
combo = $.map(combo, function(e){
return e.replace(/\{.*?\}/g, function(m){
return pattern[m];
});
});
Demo: jsfiddle.net/C97ma/
Based on the information you provided I'm don't get it 100% I guess. But whatever you're trying to do, I guess jQuerys .map() and $.map() would help you here.
Like
var arr = $('select').find('option:selected').map(function(index, elem) {
return elem.textContent || elem.text;
}).get();
Demo: http://www.jsfiddle.net/4yUqL/78/
Within the callback you can modify/match the text in any way you want/need. In your case I could imagine you want to use a regular expression to match the selected strings and recreate those somehow.
I figure you're using javascript for combining those (it can be done with PHP also)..
You need references to your selects, e.g. :
<script type="text/javascript">
a=document.getElementById("myselect").options[1];
</script>
This will assign the 2nd option value from the 'myselect' select element to the variable 'a'
To begin with I would change the values in the select box like this:
<select id="my-select1">
<option value="OP">This is option 1 ({myop1}|OP)</option>
<option value="OQ" selected>This is option 2 ({myop1}|OQ)</option>
<option value="OR">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="PP">This is option 1 ({myop2}|PP)</option>
<option value="PQ">This is option 2 ({myop2}|PQ)</option>
<option value="PR" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="QP">This is option 1 ({myop3}|QP)</option>
<option value="QQ">This is option 2 ({myop3}|QQ)</option>
<option value="QR" selected>This is option 3 ({myop3}|QR)</option>
</select>
Now to update your array:
var comboDef = ["abc-{myop1}-{myop2}", "def-{myop2}"];
var combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
function updateArray() {
combo = comboDef;
for (i in combo)
{
combo[i] = combo[i].replace("{myop1}",document.getElementById("my-select1").value);
combo[i] = combo[i].replace("{myop2}",document.getElementById("my-select2").value);
combo[i] = combo[i].replace("{myop3}",document.getElementById("my-select3").value);
}
}
Of course, this could be done better with proper arrays (if you gave your select boxes the same name you could iterate through them using document.getElementsByName()). The basic idea is the replace though which I trust is what you're looking for.
Related
I'm trying to make a chained dropdown that contain continent, region,country, province,city,district, and village, but i'm stuck at country.
my dropdown require me to use the id from database to chain all the dropdown, so to get the text name i usually using this method :
Country :
<select name="loc_country" class="loc_country loc5" id="loc_country" onchange="javacript: var valor2 = this.options[selectedIndex].text; document.getElementById('loc_country_real').value = valor2;">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
However this method doesn't work this time so i try another approach with :
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
and js :
$("#continent").change(function () {
$("#loc_country_real").val($('#loc_country').text());
});
and hoping when my select box with id="continent" changing, the value will update.
And that method also failed because the value given in "loc_country_real" doesn't match with selectbox "loc_country" (e.g.:when i selected europe on the continent selectbox, the loc_country select box will give me a list of european countries but the value in "loc_country_real" will be asian from country)
i need to make the text in "loc_country" and "loc_country_real" match but i have no idea how to do it, please help.
Try this:
Change your select's to have a VALUE matching the text you want E.G:
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">--Select--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
You can then use document.getElementById('loc_country').value to get the selected option value
// Change `loc_country_real`'s value to match `loc_country` selected option
document.getElementById('loc_country_real').value = document.getElementById('loc_country').value;
Or the jQuery way:
$('#loc_country').change(function(){
$('#loc_country_real').val($('#loc_country').val());
});
Edit since you mentioned you cannot use value:
$('#loc_country').change(function(){
var textOfSelectedOption = $("#loc_country option:selected").text();
$('#loc_country_real').val(textOfSelectedOption);
});
So I am making two dropdowns. One is dependent on the other one, as in when you choose an option in the first dropdown, the values in the other should change. I am rendering my form with Symfony3.4, so I do not have much control over it. (I do not think I can add dynamic class names/value names to it). If it is relevant, I am using Bulma css framework.
Here is what my selectboxes look like:
states:
<select name="state" id="stateSelect">
<option value="1">Lagos</option>
<option value="2">Abuja</option>
<option value="3">Rivers</option>
<option value="4">Ogun</option>
<option value="5">Oyo</option>
<option value="6">Anambra</option>
<option value="7">Enugu</option>
<option value="8">Akwa Ibom</option>
<option value="9">Adamawa</option>
...
<option value="37">Zamfara</option>
</select>
LGA (local government areas):
<select id="lgaSelect" name="areas_registration[lga]">
<optgroup label="Lagos">
<option value="1">Abule Egba</option>
<option value="2">Agege</option>
<option value="3">Ajah</option>
<option value="4">Alimosho</option>
<option value="5">Amuwo Odofin</option>
...
</optgroup>
<optgroup label="Abuja">
<option value="38">Apo</option>
<option value="39">Asokoro</option>
<option value="40">Central Area</option>
<option value="41">Chika</option>
<option value="42">Dakibiyu</option>
...
</optgroup>
....35 more optgroups
</select>
My goal is when a user chooses an option from States dropdown, the LGA dropdown should only have options relevant to the selected state. I am using optgroup label for this. What I tried in my javascript is that when the page loads, I clone the LGA dropdown, hide it, call it lgaSelectSeed and use it for seeding the original LGA dropdown: (#hiddenLgas is just an empty div)
$(function () {
var stateSelect = $("#stateSelect") || null;
var lgaSelect = $("#lgaSelect") || null;
var hiddenLga = $("#hiddenLgas") || null;
$(hiddenLga).html(lgaSelect.clone().prop('id', 'lgaSelectSeed'));
stateSelect.change(function () {
var select_class = $(this).find('option:selected').text();
var options = $(lgaSelectSeed).find('optgroup[label="' + select_class + '"]');
$(lgaSelect).html(options.children());
}
This works but there is a bug in it. If you select random options in the state dropdown, and then go up and select Lagos or Abuja, the LGA dropdown becomes blank. I have been trying to figure out for a few days why this is happening, but still cant. Is there any jquery plugin to handle this instead?
DEMO: https://jsfiddle.net/gafyvbL9/
How to replicate the bug: In the states dropdown (left), choose Lagos. Then choose Anambra. Then choose Lagos again, then choose Anambra. You can see that the LGA dropdown (right) becomes empty. Why is this happening? Thanks in advance
Make a clone of the stored options so you don't remove the originals from $(hiddenLga)
Change:
$(lgaSelect).html(options.children());
To
$(lgaSelect).html(options.children().clone());
Playing with your fiddle, I think the issue is when you perform $(lgaSelect).html(), you're deleting all of the information stored there. Try storing that outside of your handler.
let $options = $('#lgaSelect').clone();
$("#stateSelect").on('change',function() {
let state = $(this).find('option:selected').text();
$("#lgaSelect").html($options.find(`optgroup[label="${state}"]`).html());
});
EDIT:
Notice the double quote in optgroup[label="${state}"]. This prevents issue with states that contain a space, like Akwa Ibom.
I want to achieve:
If I select "16" in first select box and bigger value in second, for example "17", then in second select automatically changing to "16".
Just if value in first select box is lower than second, always change to same values, for example 16 to 16, 18 to 18.
<select id="from_age_js" name="from_age" class="select-advertise-style">
<option value="f13">13</option>
<option value="f14">14</option>
<option value="f15">15</option>
<option value="f16">16</option>
<option value="f17">17</option>
<option value="f18" selected>18</option>
<option value="f19">19</option>
<option value="f20">20</option>
</select>
—
<select id="to_age_js" name="to_age" class="select-advertise-style">
<option value="t13">13</option>
<option value="t14">14</option>
<option value="t15">15</option>
<option value="t16">16</option>
<option value="t17">17</option>
<option value="t18">18</option>
<option value="t20" selected>20+</option>
</select>
That's an easy one, in your case, with pure javascript, I would do something like this:
function checkit()
{
//Store the two dropdowns for easy reference
var fromAge = document.getElementById('from_age_js');
var toAge = document.getElementById('to_age_js');
//Verify if the toAge value is minor, to see if the conditional code will be executed
if( fromAge.options[fromAge.selectedIndex].value >
toAge.options[toAge.selectedIndex].value)
{
//In that case, match the values to be the same...
document.getElementById('to_age_js').value =
fromAge.options[fromAge.selectedIndex].value;
}
}
And you just have to add that function to where you want it to be called. I would choose to add the onchange event from Javascript within the select dropdowns. Like this:
<select id="from_age_js" name="from_age" class="select-advertise-style" onchange="checkit();">
You can see a working example here:
https://jsfiddle.net/8cmad3tz/19/
I found a nice demo on an old JSFIddle for Moving items from one multi-select box to another with JavaScript
You can see the demo here: http://jsfiddle.net/jasondavis/e6Y7J/25/
The problem is, the visual part works correctly but when I put this on a server with PHP, it only POST the last item added to the new select box. So instead of POSTING an array of items, it will only POST 1 item regardless of how many items exist in the selection box.
Can anyone help me?
The JavaScript/jQuery
$(document).ready(function() {
$('select').change(function() {
var $this = $(this);
$this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
});
});
I believe I've hit this issue before. For the PHP $_POST array to populate this correctly you need to add a name field with [] at the end of the name. PHP will then interpret the result as an array of all the values and not just the last selected one.
Example:
<select name="demo_multi[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
When you recall the item in the $_POST array leave off the square brackets.
$values = $_POST['demo_multi'];
Change the multiselect name to an array
<select name="post_status[]" multiple id="select2" class="whatever" style="height: 500px; width: 222px;"></select>
I think you also have to select all items in the
This is pre jquery but it works.
`<form onsubmit="selectAll();"> ....</form>
function selectAll()
{
for(j=0; j<document.formdata.elements.length; j++)
{
// if a multiple select box then select all items in the box so they are sent with the form
var currObj = document.formdata.elements[j];
if (currObj.tagName == 'SELECT' && currObj.multiple == true)
for (i=0; i<currObj.length; i++)
currObj.options[i].selected = true;
}
}`
This will then be loaded into the array named in the
I'm trying to select a certain option in a select box, but it's not working:
var category = $(row + 'td:nth-child(4)').text();
$('#category_id', theCloned).load('/webadmin/video/get_categories',function(){
$('#category_id', theCloned).val(category);
});
There's no error thrown, but it doesn't change the select box. What am I doing wrong here?
Here is an example of the options loaded by the load() call:
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
The value of the category variable is "Fun" or "Capabilities", etc.
var $selectbox = $('#category_id', theCloned), // cache the element to avoid lookup overheads
category = $(row + 'td:nth-child(4)').text();
$selectbox.load('/webadmin/video/get_categories', function(){
$selectbox
.find('option')
.filter(function(){
return $(this).text() === category;
})
.prop('selected', true);
});
Update 1
Updated the code to adjust to the code you presented in your update. This will work. However if an option will contain a part of the string and not the full string it will still be part of the selected elements. E.g.
If the options will be
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
<option value="6">Fun Time</option>
<option value="6">Funhouse</option>
And the category variable will have the value Fun, all three last options will be part of the selector.
Update 2
Changed the code to filter the options whose text fully matches the value of the category variable. Thus, you won't have to worry about the Update 1 above.
$('#id_of_select_box').val('your_value');
this will do
Try this
$('#category_id', theCloned).val($.trim(category));
At last i found a new solution Fiddle
<select>
<option value='1'>one</option>
<option value='2' >two</option>
<option value='3' >three</option>
</select>
Script
$("select").on("change",function(){
alert($("select option:selected").text());
});