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>
Related
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 with two select fields. The first select field will list items, the second select field will start empty but be populated by selecting an item from the first and pressing the add button. You would also be able to do the same. You can select an item from the second select field and hit the remove to add it back to the first select field. In the end, I want all the values of the second select field to be in a hidden form box separated by commas.
I've come across examples of this with javascript in the past, but now that I need them I can't seem to find them. Does anyone know of any sources that could show me how to accomplish something like this? At first, I was thinking of doing it using ajax but I would rather do it without loading another page. Any help in pointing me in the right direction would be greatly appreciated! Thanks in advance!
<form name="SelectItem">
<select name="SelectItem">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button>Add =></button>
<button><= Remove</button>
<select name="SelectedItems">
<option value=""></option>
</select>
</form>
You can use jquery append() to do it:
$(document).ready(function(){
$('.add').click(function(){
$('#select1').find('option:selected').appendTo('#select2');
});
$('.remove').click(function(){
$('#select2').find('option:selected').appendTo('#select1');
});
});
Working pen
You can use the add() and remove() methods on the select element:
const select1 = document.getElementById('select1')
const select2 = document.getElementById('select2')
const addItem = () => {
event.preventDefault();
if(select1.length === 0) return;
let itemIndex = select1.selectedIndex;
let item = select1.options[itemIndex];
select1.remove(itemIndex)
select2.add(item);
}
const removeItem = () => {
event.preventDefault();
if(select2.length === 0) return;
let itemIndex = select2.selectedIndex;
let item = select2.options[itemIndex];
select2.remove(itemIndex)
select1.add(item);
}
document.getElementById('addButton').addEventListener('click', addItem);
document.getElementById('removeButton').addEventListener('click', removeItem);
<form name="SelectItem">
<select name="SelectItem" id="select1">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="addButton">Add =></button>
<button id="removeButton"><= Remove</button>
<select name="SelectedItems" id="select2">
</select>
</form>
Below is one relatively simple approach you can take that takes advantage of event delegation technique:
const inSelectEl = document.querySelector('#in-item-list');
const outSelectEl = document.querySelector('#out-item-list');
const optionQuantity = inSelectEl.options.length;
const onClick = e => {
if (e.target.tagName !== 'BUTTON') {
return;
}
let a, b;
if (e.target.id === 'add') {
a = inSelectEl;
b = outSelectEl;
} else {
a = outSelectEl;
b = inSelectEl;
}
const selectedOption = a.options[a.selectedIndex];
b.options[b.options.length] = selectedOption;
}
document.querySelector('#container').addEventListener('click', onClick);
<!-- Added container to enable event delegation -->
<div id="container">
<select name="SelectItem" id="in-item-list">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="add">Add =></button>
<button id="remove"><= Remove</button>
<select name="SelectedItems" id="out-item-list" />
</div>
I am playing around with a select field. I want to access the key(displayed text) of it. This is currently working, but feels kind of stupid.
<select onChange={
(e) => {
console.log('e.target', e.target);
onChangeEvent(e.target.options[event.target.options.selectedIndex].text, e.target.value);
}}>
...
</select>
Is there something better for
e.target.options[event.target.options.selectedIndex].text
without using jQuery, additional modules...
If you don't care about IE:
const select = document.querySelector('.select')
select.addEventListener('change', (e) => {
const selected = e.target.selectedOptions[0]
console.log(selected.text, selected.value)
})
<select class="select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
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)