js change select name based on option selection - javascript

I have a dynamic drop down menu where options are loaded from database, Now i need to change the attribute every time different option is selected from the drop down menu.
To achieve this I am trying to use js in my opinion suitable to do the job but unfortunately I find it difficult and cannot come up with a correct solution, actually i dont know how to start it.
Here is my PHP code that dynamicly generates drop down menu:
$opt = '<select id="Forex" name="" style="display: none">';
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = '';
while($result = mysqli_fetch_assoc($query)){
if($timestamp < $result['endingDate']){
$opt2 .= '<option id="'.$result['id'].'" value="'.$result['startingDate'].'">'.$result['course'].'</option>';
}
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Could some one suggest a solution a at least give me a link to a article that covers this problem

You can add "onchange" event and change the name whatever you like:
$('#Forex').change(function(){
var val = $(this).val(); // you can get the value of selected option
//you can process your conditions here
$(this).attr('name', 'your_choice_name'); // this will change the name attribute
});
or you can do this from javascript
<select id="Forex" name="abc" onchange="changeAttr(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script type="text/javascript">
function changeAttr(ele)
{
var val = ele.value;
var n = "";
if(val == 1){
n = 'xyz';
} else if(val == 2){
n = 'abc';
}
ele.setAttribute('name', n);
}
</script>
Hope this will help you what you want...

Use jquery, with a "onChange" event that will change the attribute you want with the selected item in the list.
jQuery get value of select onChange

Hei!
Not sure if I understood you, but you can use jQuery to manipulate attributes on change event.
For event http://api.jquery.com/change/
To change atribute http://api.jquery.com/attr/

Related

When registering both onchange and onclick on a select, the click event is triggered twice

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...

How can I hide some elements from a select list?

I am new to programming and I would like to know how to hide some options from a select control I have...
I am going to explain the thing: So, i have two select controls.. according to the option from the select number 1, I want to hide some items from the second select, but I don't know how to do it, I was trying with some jQuery .hide but it is not working... Hope you can help me...
Thank you
Hope this gives you an idea, since you didn't post any code.
HTML
<select id="selectA">
<option value="">Select Fruit or Veg</option>
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
</select>
<select id="selectB">
<option value="">All</option>
<option value="apple" data-type="fruit">apple</option>
<option value="orange" data-type="fruit">orange</option>
<option value="carrot" data-type="vegetable">carrot</option>
<option value="tomato" data-type="vegetable">tomato</option>
</select>
JS
var selectA = document.querySelector('#selectA')
var selectB = document.querySelector('#selectB')
selectA.addEventListener('change', event => {
var type = event.target.value;
[].slice.call(selectB.querySelectorAll('option'))
.forEach(el => {
el.style.display = (el.dataset.type === type ? 'block' : 'none')
})
})
JSFiddle Demo: https://jsfiddle.net/hw76aLqv/1/
Try this.
if($("#APU").val("1")) {
$("#celda option[value = 'raven']").wrap('<span>')
}
To show again, just find that option(not span) and
$("#celda option[value = 'raven']").unwrap()
I hope this helps . Although the jQuery function is pretty lengthy but This way you will be able to get what is actually happening . After selecting an option from first select element , do a check whether id is 'selectA' or not .
Take the selected option as an object in the variable OPTIONS.
and then go to the next select Element using .next() function .
There use a loop which will go through all the child elements of select element .
after that I am doing a check . If the data-type of the child element is not equal to options.val() hide the child element using .hide()
Here is the code
$(document).ready(function(){
$('select').on('change',function(){
if($(this).attr('id')=='selectFirst'){
var options = $(this).find('option:selected');
var nextSelect = $('select').next();
nextSelect.children().each(function(){
child = $(this);
if(child.attr('data-type') != options.val()){
child.hide();
}
});
}
});

Run Function on default HTML Select with PHP And Javascript

I try to Run Default Function on HTML Select, but Default Function doesn't works for Default Selected Value, But it Works On User Select
<?php
$status_selected = 'A002';
?>
<!-- HTML Select 1 -->
<select id="state" class="l" name="state" onchange="Func()">
<option value="A001" <?php if($status_selected == "A001") echo "selected"; ?> data_item=" , StateA003 One, A003 State Two, A003 State Three">A001</option>
<option value="A002" <?php if($status_selected == "A002") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A002</option>
<option value="A003" <?php if($status_selected == "A003") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A003</option>
</select>
<!-- HTML Select 2 -->
<label for="city">Item : </label><select id="city" name="item" class="l" onchange="onSelected()">
<script>
function Func() {
var city = document.getElementById('item');
var state = document.getElementById('state');
var val=state.options[state.selectedIndex].getAttribute('data_item');
var arr=val.split(',');
item.options.length = 0;
for(i = 0; i < arr.length; i++) {
if(arr[i] != "") {
item.options[item.options.length] = new Option(arr[i],arr[i]);
}
}
}
function onSelected() {
var item = document.getElementById('item').value;
var state = document.getElementById('state').value;
console.log('Parent : ' + state+ ', Item : ' + item);
}
</script>
it load HTML Select One And then Select Item in HTML Select Two, But HTML Select Two Works Only By Manual User Select And Not Works For Default Programatically Value
Whole Of Codes Above Are On PHP File.
How i can fix it ?
Not sure if it is relevant, but maybe you want a chained select box? If not, please clarify your question, it's very hard to follow.
EDIT: So the real issue is selecting the right option by code. In that case, this is a duplicate of How do I programmatically set the value of a select box element using javascript?.
In your onload script(or just after the functions if the script is at the bottom of the page), also run Func(), then set the value for #city:
Func();
var state = document.getElementById('state'),
city = document.getElementById('city'),
selectedCity = state.getAttribute('data-selected-city');
if(selectedCity) {
city.value = selectedCity;
}
You need to store the selected city somewhere, my suggestion is to add it to the select:
<select id="state" data-selected-city="new-york">
<!--and so on--->
</select>
NOTE: setting a data attribute in HTML5 should begin with data-, not an underscore. So it's data-item="", not data_item="". That will give you a warning when running HTML validator.
Put Out Of PHP Tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
On Script Tag Put :
$(function() {
$("#state").on("change", Func());
});
After :
item.options[item.options.length] = new Option(arr[i],arr[i]);
put the code :
$(item).prop("selectedIndex",i);

Get the values of all select options on change event javascript

I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?
<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}
You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!

How to maintain a persistent state of the drop down?

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.

Categories

Resources