How to get the value from drop down selection using react - javascript

I have been trying to develop a custom drop down component using list elements in react. Found the, following work around very promising, but I am bit confused how to change the default value when an item is selected from the drop down. For example: initially "Select movie" is selected and when I select an item like: "The prestige" it should appear in the field.
Can be check the demo here in the following link:
https://codesandbox.io/s/objective-williams-8je1y?file=/src/Dropdown.jsx
Any help would be highly appreciated.Thanks.

To achieve the following, you have to use the title prop as a default value of a new state:
const [dropdownTitle, setDropdownTitle] = useState(title)
then use the dropdownTitle as the display value for the dropdown:
<p className="dd-header__title--bold">{dropdownTitle}</p>
Lastly set the dropdownTitle whenever you select or click an item:
function handleOnClick(item) {
setDropdownTitle(item.value)
// rest of the code
I modified your sandbox, check this out: https://codesandbox.io/s/stoic-fog-98wce?file=/src/Dropdown.jsx

Related

<ng-select > after on changes formGroup control value still null,if searchTerm provided programmatically

I have requirement to set searchTerm value Programmatically(using Virtual keypad) and search the dropdown should show searchterm based options.
where form control is updateOn:'blur'.
But here i am facing issue like form control is not getting updated after selecting dropdown option based on searchTerm provided by virtual input key(in example stackblitz red color text control value is null).
Steps:
1.press virtual key pad button
2.select any option
3.now check red color text value:
Thanks.
It is getting updated, but you are using before it is updated. Even if you open the <ng-select> yourself, it will show different values in black and red.
If you can, I'd suggest for you to use change.id instead:
this.afterChangesFormControlValue = change.id;
But if you can't... if you wrap it inside a setTimeout(), even with a 0 delay, it will start working, since the setTimeout will be triggered only after the update is done:
setTimeout(() => {
console.log('on select option after given search term from virtual keyboar')
console.log("change:",change)
console.log("form control value:",this.form.controls.example.value)
this.afterChangesFormControlValue=this.form.controls.example.value;
}, 0);
Both should produce the same results - they did when I tested in your Stackblitz, but setTimeout is a bit unsightly.

Django Modelmultiplechoicefield Checkboxselectmultiple Problem Getting Selected Checkbox

I have been working all day to try and get the selected values on one set of checkboxes on my Django form and copy the selected ones only to an identical checkbox on my form. If a user clicks on a checkbox in form.author defined below, I want the same identical checkbox to automatically be checked on form.favorite_author defined below.
I've tried a JQuery approach as documented here...Copy Selected Checkbox Value From One Checkbox To Another Immediately Using JQUERY but no luck so far. I've recently begun exploring an avenue with the Modelmultiplechoicefield and the checkboxselectmultiple parameters within the form itself. From what I can tell, when I am using JQuery and trying to check a box on the form, the value is coming back as undefined which is most likely why it is not propagating the checkbox selection to the other checkbox.
Here is my form....
class ManagerUpdateNewAssociateForm(forms.ModelForm):
class Meta:
model = Library
self.fields['author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
self.fields['favorite_author'] = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Books.objects.all()
My HTML...
<div class="spacer83">
{{ form.author }}
</div>
<div class="spacer83">
{{ form.favorite_author }}
</div>
When I tried to trace JQuery, it told me the checkbox selections are undefined. I did read a bit about how Modelmultiplechoicefield, since it uses a queryset it doesn't show the selections, but I can't figure out how to get it to.
Thanks in advance for any thoughts.
In combination with the other issue included in this one, I went back to the JQuery route and explored further. From what I can tell, I was not able to use the class for the input because of the way the HTML for Django forms is generated in this use case. I ultimately was able to leverage the input name and then used the code below to interrogate the checkboxes accordingly:
$(document).ready(function() {
$("[name=author]").change(function() {
let selectedValA = $(this).val();
let isAChecked = $(this).prop("checked");
$(`[name=favorite_author][value="${selectedValA}"]`).prop("checked", isAChecked);
});
});
});

How to refresh HTML field on selecting the drop down list?

I want to get html field (a drop down list) refreshed as I get it by default on clicking the chart type from the (chart type) drop down list. The default selection after selecting a chart is shown below: (if I select "Pie Chart 2D" from the drop down list)
Now if I select another similar chart "Pie Chart 3D" (which has same drop down field) and also I select the field data, then the image is as below:
PROBLEM
Now if I select the "Pie Chart 2D" back again from the drop down list I get this 2nd image field set already. I want the field to be refreshed as it is shown in the 1st image of Pie Chart 2D. Therefore, how should I refresh the field?
NOTE:
The field that I want to refresh to default is "Define X-Axis" drop down list.
I hope I have cleared my problem, in case of confusion in the understanding I will be replying soon. I hope it is not difficult to solve!
Thanks for your time.
You can add an onchange event listener to your select. If you have a function updateDiv() in JS that would update your <div> element that you want to call with a change of the <select> element:
In HTML:
<select id="chartType" onchange="resetFieldToDefault();">
In jQuery:
$("select#chartType").change(resetFieldToDefault);
In (plain) JS:
document.getElementById("chartType").addEventListener("change", resetFieldToDefault);
EDIT
I don't think I answered the question correctly above. I believe the question was more along the lines of, How could I deselect all the options in that field (once a select field was changed)? So I only answered the first part of the question, but the second part about resetting the other <select> element remains unsettled. (Am I correct?)
To do this, add a listener as shown above. And then, add the (plain) JS function:
var resetFieldToDefault = function() {
var selectedOptions = document.getElementById("xAxisSelect").selectedOptions;
for(var i = 0; i < selectedOptions.length; i++)
selectedOptions[i].selected = false;
}
I would do something like this:
$("#chartType).on("change", function() {
refreshDivs(this.val());
});
function refreshDivs(value) {
if(value=="Scatter Chart") {
$("#divEventCategory").hide();
$("#divEventSubCategory").hide();
} else if ((value=="Bubble Chart") {
$("#divEventCategory").show();
$("#divEventSubCategory").show();
}
}
If you need to refresh the content of the dropdowns/listboxes based on the choice, just add the code in the corresponding section as well.

How to bind multiple function results as options to select in a form select pop down box?

Here is the fiddle http://jsfiddle.net/Dano007/b11xarpp/5/
To be clearer. In the drop down box, I'd like two options (text). when the user clicks one of these options the relevant function results are returned. Like see when clicking the buttons, which are for example only.
I've added the drop down box, but cannot see how to bind the results from the two queries to it.
Could I use something like ?
$("select#FriendsConnected option.filter-prop2").show();
$("select#FriendsConnected option.filter-prop1").show();
Feel like I've hot a brick wall with this and ideally would like some help with the fiddle to move past it.
In your HTML, change select id to a valid css id, something like: s_FriendsConnected
<select name="huge" class="btn-group select select-block mbl select-multiple" id="s_FriendsConnected">
In your Javascript, change the select = getElementByID(FriendsConnected)'s ID to your new select id: s_FriendsConnected
var select = document.getElementById("s_FriendsConnected");
This solves it on my local machine... will update with the jsfiddle in a while..
EDIT:
Here's the jsfiddle. : http://jsfiddle.net/b11xarpp/7/
UPDATE:::
As per your requirement, in this new jsfiddle, I've removed the buttons and placed option tags with values in the html.
In Javascript, I've removed the var select = document.getelementbyid() function.
Also, I've replaced your click functions for the buttons with on Change event to the select menu:
$('select#s_Friends').change(function(){
var selection = $(this).val();
if(selection=='f_connected')
FriendsConnected();
else if(selection=='f_requests')
FriendsPending();
});
That's mostly all. Here's the updated jsfiddle: http://jsfiddle.net/b11xarpp/8/

How to create dynamic select field with blank option and unfiltered state

I need to create a dynamic select field in Rails 3.2, where the options available in the second fields (states) depends on the value of the first (country). I've referred to the revised version of this Railscast, and am using the following code:
jQuery ->
$('#person_state_id').parent().hide()
states = $('#person_state_id').html()
$('#person_country_id').change ->
country = $('#person_country_id :selected').text()
escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/#])/g, '\\$1')
options = $(states).filter("optgroup[label='#{escaped_country}']").html()
if options
$('#person_state_id').html(options)
$('#person_state_id').parent().show()
else
$('#person_state_id').empty()
$('#person_state_id').parent().hide()
I need to make two changes to this code, which I think should be pretty straightforward for someone with stronger javascript skills than I have.
In the filtered list, I need to include a blank option. Currently selecting a country results in the first state state in the filetred list being selected. I need to leave the prompt "please select". How can I do this?
EDIT
SMathew's suggestions helped here. I'm using $('#person_state_id').html(options).prepend('<option></option>') which, together with a prompt attribute on the html tag, acheives the required result.
If no country is selected (ie the else statement) person_state_id should contain a complete, unfiltered list of all states. I've tried:
else
$('#person_state_id').html(states)
But this is not behaving as expected. I'm having these issues.
If I select a country that has associated state records, #person_state_id options are correctly filtered (and with smathews suggestion, a prompt is included).
If I select a country with no associated state records, #person_state_id contains all states, a blank option in the markup, but the first state option is selected by default. (It should be empty, with a blank option selected by default and a prompt displayed).
If I clear the selection in #person_country_id, #person_state_id contains an unfiltered list of all states (correct), and an empty option in the markup (correct) but the first state record is selected by default (should be a prompt).
How can I resolve these issues?
Thanks
Try
...
if (options) {
$('#person_state_id').html(options).prepend('<option>Please select</option>').parent().show()
} else {
$('#person_state_id').html(states).prepend('<option>Please select a state</option>').parent().show()
}
To deal with my second problem, I added the following coffeescript
jQuery ->
resetCountry = ->
$('#person_state_id').select2 "val", "0"
$('#person_country_id').bind("change", resetCountry);
This, coupled with smathew's answer, seems to be working
(I'm using select2 to format my select fields. You'll need a different approach to set the value if not using select2)

Categories

Resources