handleselectenquiryId(e) {
let attribute = document.getElementById(e.target.value);
let sectorattrribute = attribute.getAttribute("data-items");
this.setState({ enquiryId: e.target.value }, ()=>{
let data = {
id : sectorattrribute
}
UserAction._getSingleEnquiry(data);
});
}
handleselectBookingId(e) {
let attribute = document.getElementById(e.target.value);
let sectorattrribute = attribute.getAttribute("data-item");
console.log(sectorattrribute);
this.setState({ bookingId: e.target.value }, ()=>{
let data = {
id : sectorattrribute
}
UserAction._getSingleBooking(data);
});
}
<div className="col-sm-4 col-6">
<h2 className="card-inside-title">Enquiry Id</h2>
<select className="c-select form-control box_ip" onChange={this.handleselectenquiryId.bind(this)} value={this.state.enquiryId}>
<option value='-1' disabled>Select Enquiry</option>
{this.state.enquirieslist.enquiries.map((el) => <option id={el.enquiryId} data-items={el.id} value={el.enquiryId}>{el.enquiryId}</option>)}
</select>
</div>
<div className="col-sm-4 col-6">
<h2 className="card-inside-title">Booking Id</h2>
<select className="c-select form-control box_ip" onChange={this.handleselectBookingId.bind(this)} value={this.state.bookingId}>
<option value='-1' disabled>Select Booking</option>
{this.state.bookinglist.bookings.map((el) => <option id={el.bookingId} data-item={el.id} value={el.bookingId}>{el.bookingId}</option>)}
</select>
</div>
I am having two dropdowns which has values 1 and 2 in both select tags.
data-items and data-item attribute i am maintaining in both respectively as both el.id is unique when onChange of handleselectBookingId it is taking the id of handleselectenquiryId onchange,
May I know what was the error i was doing.
As i was handling document.getElementById is this the proper way to work or any way to resolve this.
It's not good to use document.getElementById(e.target.value) in react as it has ref for acessing DOM nodes.
you can use ref in your case like this:
first, assign a ref to your options:
<select className="c-select form-control box_ip" onChange=
{this.handleselectenquiryId.bind(this)} value={this.state.enquiryId}>
<option value='-1' disabled>Select Enquiry</option>
{this.state.enquirieslist.enquiries.map((el) => <option ref={val => this[el.enquiryId] = val} data-items={el.id} value={el.enquiryId}>{el.enquiryId}</option>)}
</select>
then access to their data-items attribute value like this in your onChange handler:
this[e.target.value].attributes['data-items'].value)
Related
I am working on Reactjs/Nextjs and right now I am trying to change the dropdown value (working on the update module).
I tried the following code but it's not working.
const Post = function(props) {
const [content2, setContent2] = useState('');
}
useEffect(()=>{
setContent2(post?.cat_name);
},[])
<select value={post?.cat_name} className="form-control" name="cat_name" id="cat_name" onChange={(con2) =>
{
setContent2(con2);
}}>
<option value="">Select Category</option>
<option value="pined" >Pined</option>
</select>
Any help would be great.
use content2 as value
value={content2}
you can initialize content2 in declaration
const [content2, setContent2] = useState(post? post.cat_name : "");
then the value attribute in select should be content2 also in onChange try to use event
<select
value={content2}
className="form-control"
name="cat_name"
id="cat_name"
onChange={(event) => {
setContent2(event.target.value);
}}
>
<option value="">Select Category</option>
<option value="pined">Pined</option>
</select>
I'm trying to loop through elements and check their length, then add a class if parents have more than 2 elements.
Now the class is been added to all parent elements.
My code is like this:
let CheckOptions = [...document.querySelectorAll(".value select option")]
let checkSelects = [...document.querySelectorAll(".value select")]
checkSelects.forEach(checkSelect => {
if(CheckOptions.length >= 2){
CheckOptions.forEach(checkSelects => checkSelect.classList.add("active"));
}
})
.active {
background-color: red;
<div class="value">
<select class="select">
<option class="option">1</option>
<option class="option">2</option>
<option class="option">3</option>
<option class="option">4</option>
</select>
</div>
<div class="value">
<select class="select">
<option class="option">1</option>
<option class="option">2</option>
</select>
</div>
<div class="value">
<select class="select">
<option class="option">1</option>
<option class="option">2</option>
<option class="option">3</option>
<option class="option">4</option>
</select>
</div>
What I'm doing wrong here?
We can access a select's options by the options select property so we check the length of that property's value is greater than 2, if so, we add the class active to the current select.
Try the following .js code:
let checkSelects = [...document.querySelectorAll(".value select")]
checkSelects.forEach(checkSelect => {
const options = checkSelect.options
if (options.length > 2) {
checkSelect.classList.add("active")
}
})
Also, in order to get the length, instead of getting the options property of the checkSelect, you can just get the length by checkSelect.length property.
So it would be:
let checkSelects = [...document.querySelectorAll(".value select")]
checkSelects.forEach(checkSelect => {
if (checkSelect.length > 2) {
checkSelect.classList.add("active")
}
})
I have a drop-down list where depending on the selected value, the next drop-down list shows specific values. when changing the value of the first list and then going back to the old value, the second list does not update. keeps the same value selected before. How can I make the second list update to the value I marked as selected by default whenever I change the value of the first list?
I hope you guys were able to understand me, and I thank you for your time.
Here's the code:
<select onchange="showprd('hidevalue', this), showprd2('hidevalue2', this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="hidevalue">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="hidevalue2">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</body>
<script>
function showprd(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 0 ? 'block' : 'none';
}
function showprd2(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none';
}
</script>
TL;DR. Control the input value changes in one place.
Please see the updated snippet below. html structure hasn't been changed, but I've removed the inline js call and updated the id names. JavaScript blocks are commented in details.
In a nut-shell, this code listens for any change to the parent select dropdown. Whenever a change occurs, its child dropdowns will reset their values and toggle their visibility accordingly.
// Assign each dom element to a variable
const primarySelect = document.querySelector('#primary');
const childSelect1 = document.querySelector('#child1');
const childSelect2 = document.querySelector('#child2');
const defaultValues = document.querySelectorAll('.default');
function resetInputs() {
// Reset the child select options to default
defaultValues.forEach(option => option.selected = true);
}
function handlePrimary(e) {
// Reset the child select values whenever the parent value changes
resetInputs();
// `input` value is always a string. Here we're converting it to a number
const val = parseFloat(e.target.value);
// Toggle visibility of child select dropdowns
[childSelect1, childSelect2].
forEach((select, i) => select.style.display = val === i ? 'block' : 'none');
}
primarySelect.addEventListener('change', handlePrimary);
<select id="primary">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="child1">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="child2">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
If I understood correctly, the expected behavior is when the second or third <select> is hidden, the <select> should go back to default (the first <option>?). If so, then remove disabled and hidden from the first <option> of the second and third <select> then add the following:
selectObj.hidden = true;
selectObj.selectedIndex = 0;
The example below has a <form> wrapped around everything (always use a form if you have more than one form control. By using HTMLFormElement interface I rewrote the code and can reference all form controls with very little code. Inline event handlers are garbage so don't do this:
<select id='sel' onchange="lame(this)">
Instead do this:
selObj.onchange = good;
OR
selObj.addEventListener('change', better)
Read about events and event delegation
const UI = document.forms.UI;
UI.onchange = showSelect;
function showSelect(e) {
const sel = e.target;
const IO = this.elements;
if (sel.id === "A") {
if (sel.value === '0') {
IO.B.hidden = false;
IO.C.hidden = true;
IO.C.selectedIndex = 0;
} else {
IO.B.hidden = true;
IO.B.selectedIndex = 0;
IO.C.hidden = false;
}
}
}
<form id='UI'>
<select id='A'>
<option disabled selected hidden>Pick</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<br>
<br>
<select id="B" hidden>
<option selected>Pick B</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<select id="C" hidden>
<option selected>Pick C</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
</form>
I give you an example for your reference:
let secondList = [
[{
value: "pleno",
text: "Pleno"
},
{
value: "integrado",
text: "Integrado"
}
],
[
{
value: "junior",
text: "Junior"
},
{
value: "senior",
text: "Senior"
}
]
]
function update(v){
let secondSelectBox=document.getElementById("second");
secondSelectBox.style.display="none";
let optionList=secondList[v.value];
if (optionList){
let defaultOption=new Option("Selecione o produto","");
secondSelectBox.innerHTML="";
secondSelectBox.options.add(defaultOption);
optionList.forEach(o=>{
let vv=new Option(o.text,o.value);
secondSelectBox.options.add(vv);
})
secondSelectBox.style.display="block";
}
}
<select onchange="update(this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<select hidden id="second">
</select>
Im trying to get the item properties that is being clicked in the option button
This is my code
<select #click="populate" class="form-control" tabindex="12">
<option disabled value="" selected="selected">Select one</option>
<option v-for="(payment, index) in paymentsSelect" #click="pop(payment)"
:key="index"
:value="payment.id">{{ payment.name }}
</option>
</select>
this is my data
selectedPayment: '',
paymentsSelect: [],
these are my methods
pop(payment){
console.log(payment)
},
populate(){
var self = this
this.$http.get(this.$backendUrl + 'subjects/payment_method')
.then(function(response) {
self.paymentsSelect = response.data.data
})
.catch(function() {})
},
No need to add event, just bind the select input to a data property using v-model like :
<select v-model="selectedPayment" class="form-control" tabindex="12">
<option disabled value="" selected="selected">Select one</option>
<option
v-for="(payment, index) in paymentsSelect"
:key="index"
:value="payment">
{{ payment.name }}
</option>
</select>
selectedPayment changes when you select an option then use it in your script like this.selectedPayment
I have a form in which I am using html select element.
<select className="form-control" id="ntype" required >
<option value = "">None</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
I know with html input type element we can attach ref like below code
ref = {(input) => { this.nHeading = input; }}
and
<input
type = "text"
className = "form-control"
id = "tInput"
placeholder = "Sample input"
ref = {(input) => { this.sInput = input; }}
required
/>
How can I attach ref to <Select> element and get selected option value from the attached ref when form is submitted?
Do I need to attach ref to each options or select element itself?
You can store the value in a state on change and later use that i.e make it a controlled component
class App extends React.Component {
constructor() {
super();
this.state = {selectValue: ''}
}
callThis = (e) => {
this.setState({selectValue: e.target.value}, ()=> {console.log(this.state.selectValue)});
}
render() {
return (
<select onChange={this.callThis}className="form-control" id="ntype" required >
<option value = "">None</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Or you can use refs to get the value like this
class App extends React.Component {
constructor() {
super();
this.state = {selectValue: ''}
}
callThis = (e) => {
console.log(this.selectVal.value)
}
render() {
return (
<div><select ref={(input) => this.selectVal = input} className="form-control" id="ntype" required >
<option value = "">None</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
<input type="button" value="click" onClick={this.callThis}/></div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
I would give each element a value and onChange handler for the select element like this
<select className="form-control"onChange={this.onChange.bind(this)}>
<option value="">None</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
And define an onChange handler that sets the state of the selection
onChange(e){
this.setState({value: e.target.value}, function(){
// do other stuff
});
}
If you are using React functional components, you can do the following.
import { useState, useRef } from 'react';
...
const selectRef = useRef(null)
<select className="form-control" id="ntype" required ref={selectRef}>
<option value = "">None</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
then you can access the value in your submit logic by,
selectRef.current.value
You can just use an onChange function to set the value of the Ref. E.g.:
<select className="form-control" id="ntype" required onChange={e => {yourRef.current = e.target.value}} >
<option value = "">None</option>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>