How to perform an operation with an undefined amount of <select>? - javascript

I have the following code in html:
<select onchenge="action('account1')">
<option value="1">op 1</option>
</select>
I need the function to also receive the selected value without using an id. (because I have an unlimited amount from the tag)
How can this be done?
This is my javascript code:
function action(account) {
const email = account
const select = // value*
}

Your onChange listener to be a function, instead you put a string. It should be something like the below code. Hope this will help you.
export default function App() {
....
function action(e, account) {
....
const select = e.target.value;
}
return(
....
<select onChange={(e) => action(e, "account1")}>
<option value="1">op 1</option>
</select>
....
)
}

Related

Retrieving the data* value from my HTML and printing it into the console using Javascript

I don't know what I've done wrong with this code, I've looked online and all I've seen to do is put the window.onload = function() at the start of the code. However, the value is always printed as null and I can't my head around why it's doing it.
Here is the code:
window.onload = function () {
// Get the select element by its id
const select = document.getElementById("select-filter");
// Get the selected option element
const selectedOption = select.options[select.selectedIndex];
// Get the data-select value
const dataSelect = selectedOption.getAttribute("data-sel");
// Print the data-select value to the console
console.log(dataSelect);
}
<div class="filter-select-container">
<!-- filter selector -->
<div class="filter-selection-container">
<select name="select-filter" id="select-filter">
<option value="filter-all">All</option>
<option value="filter-commercials" data-sel="1">Commercials</option>
<option value="filter-fiction" data-sel="2">Fiction</option>
<option value="filter-music-videos" data-sel="3">Music Videos</option>
</select>
</div>
</div>
Thanks for any help :)
You probably mean for the select to have a change listener on it, and then check the data attribute is defined before trying to log it.
const select = document.getElementById("select-filter");
select.addEventListener('change', handleChange);
function handleChange() {
const selectedOption = select.options[select.selectedIndex];
const dataSelect = selectedOption.getAttribute("data-sel");
if (dataSelect) console.log(dataSelect);
}
<div class="filter-select-container">
<!-- filter selector -->
<div class="filter-selection-container">
<select name="select-filter" id="select-filter">
<option value="filter-all">All</option>
<option value="filter-commercials" data-sel="1">Commercials</option>
<option value="filter-fiction" data-sel="2">Fiction</option>
<option value="filter-music-videos" data-sel="3">Music Videos</option>
</select>
</div>
</div>

Uncaught Reference Error xyz is not defined when trying to pass parameters

I am currently trying to pass parameters to set the state of the current size selected depending on which option the user is currently on, so i setup a function as well as a parameter that whenever onSelect is triggered it passes the variable of the size but for some reason im getting that my function is not defined, im guessing its my syntax but i cant seem to figure it out, here is my current code:
const updateSize = userSize = () => {
setSize(userSize);
console.log(userSize);
}
<select className="buttons form-control mb-2">
<option onSelect={updateSize("Small")}>Small</option>
<option onSelect={updateSize("Medium")}>Medium</option>
<option onSelect={updateSize("Large")}>Large</option>
</select>
Instead of const updateSize = userSize = () => { make it const updateSize = (userSize) => {
Instead of setting event listeners on individual options, set it on the <select> tag itself. Then get the text of the option selected and use it in tour code.
HTML
<select onchange="updateSize()" className="buttons form-control mb-2" id="select">
<option>Small</option>
<option>Medium</option>
<option>Large</option>
</select>
JS
<script>
function updateSize() {
let select = document.getElementById('select');
let text = select.options[select.selectedIndex].text;
console.log(text)
}
</script>
Text value can be Small, Medium or Large depending on what option was selected.
Issue was because my function was inside another function without me noticing thus outside the scope.
If you want to give parameter to a const function use below method.
<select className="buttons form-control mb-2">
<option onSelect={()=>updateSize("Small")}>Small</option>
<option onSelect={()=>updateSize("Medium")}>Medium</option>
<option onSelect={()=>updateSize("Large")}>Large</option>
</select>
Also for your updateSize function. keep the parameters inside the ().
const updateSize = (userSize) => {
setSize(userSize);
console.log(userSize);
}

Onclick button href based on drop-down

Premise:
In this particular example, I am trying to make a selection in a drop-down menu and change the keyword 'something' in the onclick() handler mentioned below with whatever value is associated with the selection made in #panel_link_library. Hope this makes sense?
Code so far:
var aaa = document.getElementById('panel_link_library')
aaa.onchange = function() {
document.getElementById("abc").href = this.value
}
<div class="dropdown-plans">
<select id="panel_link_library" name="p_links">
<option value="/pages/home_up/">Location 1</option>
<option value="www.google.com">Location 2</option>
<option value="https://321.com">Location 3</option>
</select>
</div>
<div id="abc" class="panel_link" onclick="location.href='something'">Jump to location</div>
Solution:
Your onclick simply needs to read the value of the selection!
const navToSelection = _ => {
const el = document.getElementById("panel_link_library")
const val = el.options[el.selectedIndex].value
window.location.href = val // That's it!
}
<div id="abc" class="panel_link" onclick="navToSelection()">Jump to location</div>
Explanation:
We first fetch the dropdown element by it's id = panel_link_library
Then we get that elements selected element, and from that read its value property
Use this to then set as the new location for your browser to navigate to
Change the location at the onclick function, then you can go and get the dropbox value and redirect the user.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
var aaa = document.getElementById('panel_link_library');
function goToSomewhere() {
window.location.href= aaa.value;
}
<div class="dropdown-plans">
<select id="panel_link_library" name="p_links">
<option value="/pages/home_up/">Location 1</option>
<option value="https://www.google.com">Location 2</option>
<option value="https://321.com">Location 3</option>
</select>
</div>
<div id="abc" class="panel_link" onclick="goToSomewhere()">Jump to location</div>
You're trying to assign an href to a div. assign it to the onclick handler.
var aaa = document.getElementById('panel_link_library');
aaa.onchange = function (e) {
console.log(e);
var abc = document.getElementById("abc");
abc.addEventListener('click', () => {window.location = e.target.value});
}

React JS: Pass event inside onChange drop down (Ant Design)

I have a drop down in my form (https://ant.design/components/select). In this select drop down I have the onChange to call a function. Inside 'onChange' I want to pass the event as a parameter to my function. The problem is: when the onChange occurs, only the selected value is passed, but I want the entire event.
Here is the code:
export default class MyForm extends Component {
constructor() {
super();
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
console.log(event); // here I'm receiving only the value selected (1 or 2)
}
render() {
render(
<Form>
<Select onChange={this.handleOnChange}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
}
In the console.log() I'm receiving only the selected value. Is there a way to pass the entire event object to the function handleOnChange()?
I found a solution. Just use: onSelect(), passing the value and the event.
handleOnChange = (value, event) => {
...code here
}
render() {
render(
<Form>
<Select onSelect={(value, event) => this.handleOnChange(value, event)}>
<Option value="1">text 1</Option>
<Option value="2">text 2</Option>
</Select>
</Form>
)
}
The Select component that you use is the one that handle the onChange and call your "outer" function.
What you can try is use the synthetic event variable inside your function, it might work:
handleOnChange = (selectedValue) => {
console.log(selectedValue); // The value from the inner component
console.log(event); // usually you have access to this variable
}
Try this, if you dont want to bind in callback in Select onSelect/onChange:
toggleActive = name => event => {
console.log("name: ",name) // prints "name: Active!"
console.log("event: ",event) // event is some data
}
<Select
mode="multiple"
style={{ width: '91%' }}
placeholder="Stuff"
value={this.props.value}
onChange={this.toggleActive("Active!")}
>

Change value of materialize select box by jquery

I want to change materialize select box value by jquery.
I am using $('#myselect').val('1'); on onchange event of other select box but it not works.
$("#select1").change(function() {
$('#myselect').val('1');
});
It appears to work fine for me, changing the first drop down, resets the value of the second drop down to 1.
I have done a rough implementation on jsFiddle: http://jsfiddle.net/55r8fgxy/1/
<select id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select id="myselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
JS:
$(function() {
$("#select1").on('change', function() {
$('#myselect').val("1");
// re-initialize material-select
$('#myselect').material_select();
});
});
$('#myselect').formSelect() ;
The new method is formSelect(), use this after you have updated the select.
As suggested by #logikal, you have got to re-Initialize
$("#myselect").material_select()
In 2018 (Materialize v1.0.0-rc.2), first you have to set your option programmatically:
$('#SELECT-ID').find('option[value="SELECT-VALUE"]').prop('selected', true);
And then re-initialise the select input with:
$("#SELECT-ID").formSelect();
Hope it helps!
Rather than using .val(), it's cleaner to set value as usual with jQuery :
$('#my-select').find('option[value="my-value"]').prop('selected', true);
$("#my-select").material_select();
For a new materialize 1.0.0 use .select() instead of .material_select()
Solution without re-initialization.
function msValue (selector, value) {
selector.val(value).closest('.select-wrapper').find('li').removeClass("active").closest('.select-wrapper').find('.select-dropdown').val(value).find('span:contains(' + value + ')').parent().addClass('selected active');
}
Then just use
msValue($("#select_id"), "value_here")
This answer might be late but it might help someone else.
On Ready add the line below
$(document).ready(function () {
$('select').formSelect();
});
Each time you change an option within your Select add the line below
$("#select1").change(function() {
$('#myselect').val('1');
$('select').formSelect();
});
This is what worked for me, hope it helps.
Using delegated event fixes the problem for me.
HTML
<div class="input-field col s10" id="pickerContainer">
<select>
<option value="" disabled selected>Choose your option</option>
</select>
</div>
JS
$('#pickerContainer').on('change', 'select', function(){
console.log("got you");
});
Since JQuery is no longer a hard dependency of the Materialize library, one can easily update the select via the init static method with any of the lookup methods:
const reinitialize = (selector, value) => {
const element = document.querySelector(selector);
element.value = value;
const {
options
} = M.FormSelect.getInstance(element); //pass through initialization options;
return M.FormSelect.init(element, options);
};
A quick runnable demonstration:
(() => {
const reinitialize = (selector, value) => {
const element = document.querySelector(selector);
element.value = value;
const {
options
} = M.FormSelect.getInstance(element); //pass through initialization options;
return M.FormSelect.init(element, options);
};
const interval = (callback, delay = 250) => {
callback();
setTimeout(interval, delay, callback, delay);
};
M.AutoInit(); //initializes everything
interval(() => {
const id = "test";
const randVal = Math.floor(Math.random() * 3) + 1;
reinitialize("#" + id, randVal);
});
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="input-field col s12">
<select id="test">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<label>Materialize Select</label>
</div>
Here is a version of the above for JQuery (to be fair to other answerers - this is a generalized version of this):
const updateSelect = (selector, value) => $(selector).val(value).formSelect();
Please, note that the actual core of every solution is (see docs):
you need to reinitialize the select component every time a value is updated non-natively
The rest depends on the version of Materialize used and whether one uses JQuery or not. It is also important to keep in mind that:
material_select() solutions are outdated! Use formSelect() as of Materialize 1.0.0
This is similar to what logikal answered but I think is cleaner:
$(".your-component-class").change(function(){
//your code..
//re-initialize component
$(this).material_select();
});
This was my solution in case it helps someone. I used a lot of what #Raold said.
the issue I had was the select was getting stuck when it's updated without the code below.
function updateSelect(value) {
var select = $('#myselectId');
$(select).val(value);
var text = $(select).find(':selected').text();
$(select).closest('.select-wrapper')
.find('li').removeClass("active")
.closest('.select-wrapper')
.find('.select-dropdown').val(text)
.find('span:contains(' + value + ')')
.parent()
.addClass('selected active');
}
Solution, I used in my project:
document.getElementById("mySelect").addEventListener("change", function()
{
console.log("Hello, World!")
});
I don't know if the event trigger gives you selected item or selected item's value - you can check it yourself!
const selectObj = document.querySelector('#select');
selectObj.value = "new value";
const {
options
} = M.FormSelect.getInstance(selectObj);
M.FormSelect.init(selectObj, options);

Categories