When click button Selectlist goes default with Javascript - javascript

<select asp-for="ProductFilter.BrandId"
asp-items="#(new SelectList(Model.ProductFilter.Brands,"Id","Name"))">
<option>Chose one</option>
</select>
<button type="button" onclick="clearRadioButtons()" class="btn btn-outline-info mt-3">Clear</button>
I have some list items and 1 default item which is "Chose One" and what i want is when i click Clear button just make select list choosen value "Chose One" how can i do this with javascript? Thanks For helping!
For example i got A,B,C,D in options and of course default Chose one and when someone chose C and after click "Clear" button i want to make it "Chose One" back.

Add empty value to the default option and add an id to the select element:
<select id="brand-select" asp-for="ProductFilter.BrandId" asp-items="#(new SelectList(Model.ProductFilter.Brands,"Id","Name"))">
<option value="">Chose one</option>
</select>
Then select default option like this:
function clearRadioButtons() {
var selectElement = document.getElementById("brand-select");
selectElement.value = "";
}

To fulfill your requirements I'll propose two solutions that should (or at least one of them) work for you.
Option 1: Default Form Behavior (let the browser do the trick for you)
For this situation I'd rather use the reset button type of the form element. The button[type="reset"] resets all* the form fields to their original values when the browser loaded the page.
Here's an example, you may choose an option from the list and then click on "Reset" to revert the list to its original state.
<form>
<select>
<option value="" selected>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<button type="reset">Reset</button>
</form>
all:* keep in mind, the button[type="reset"] will try to reset all the form fields to their original values and not only your select element.
Note: in the above example, i intentianally set the option with the text "Choose" as selected using the selected attribute in order for that option to be selected no matter what its position in the select element.
Option 1: JavaScript Workaround
In case the first solution cannot be used, here's a solution that relies on JavaScript to do the trick.
The idea here is to set a default option by specifying an ID for it (so we can easily retrieve it by JavaScript) and an Event Listener on the button that resets the list.
const list = document.getElementById('list'),
defaultOption = document.getElementById('default-option'),
resetBtn = document.getElementById('reset-list');
// listen for "click" events on the "Reset" button
resetBtn.addEventListener('click', e => {
/**
* the below line is required only when you use a link (for example) instead of a button or the button type is different from "[type=button]".
/* The role of that line is to prevent the default behavior of the clicked element. In case of a link, the line prevents the unwanted jump on the page as the browser tries to follow the link and it scrolls the page all the way to the top (or simply follows the link if an "href" attribute is set on the "a" tag).
*/
e.preventDefault();
// reset the list
defaultOption.selected = !0;
});
<select id="list">
<option value="" id="default-option" selected>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<button type="button" id="reset-list">Reset</button>
I recommend using the selected attribute on the option you want to be reselected once the "Reset" button is clicked.

Related

select method to restore to default value

Iam trying to do something that look easy but i cant find any soulotion,
i have <select> tag with 5 <option> all i want to do is when i click a button (have function inside of it) the select tag will be the default one (the first one)
for example :
<select className={'smallSelect'} onChange={appliances}>
<option defaultValue =''>Add</option> {/* The default */}
<option value='<Fan/>'>Air-Conditioner</option>
<option value='<HotTub/>'>boilermaker</option>
<option value='<Bulb/>'>lamp</option>
<option value='<Radio/>'>stereo system</option>
</select><br/> {/* After clicking the button the option will be the default */}
<button className={'myButton'} onClick={newAppliances}>Add</button>
I assume the button onClick event calls the function newAppliances?
You need to set the select value to ''. So add something like this at the end of your newAppliances function.
document.getElementById('.smallSelect').value = '';
See this:
How do I programmatically set the value of a select box element using JavaScript?
For React
The above solution is for normal javascript, if you want to do the react way, read this:
React JSX: selecting "selected" on selected <select> option

Reset text field on Mouse press / Input - jQuery UI Autocomplete

Simple JS fiddle containing my code in working state
I have a jQuery UI Autocomplete field, with a Dropdown button attached. It works floorlessly, however - its kinda annoying you have to manually delete the words inside the field for a search.
I am unsure if jQuery UI has a feature for it, unless i'd love to know.
I've tried to use onClick functions with JS, however since my field is not exactly an "form field" I've got kinda lost here.
My goal is to: reset the text field when a user presses it.It has prewritten text in it "Please select (Or Type)"
my cshtml file looks as following
cshtml
And it looks like this on the browser browser
Code for Image 1:
<select asp-for="Dinosaur" class="combobox" id="dinoType" asp-items="Html.GetEnumSelectList<Dinosaurs>()">
<option selected="selected" type="text" onclick="resetText()" value="0">Please select (Or Type)</option>
</select>
<span asp-validation-for="Dinosaur" class="text-dark" />
As you can see it has the text in, which i have to CTRL + A, DELETE before i can search in my field.
A function to clear this text when a user presses it will easen the pressure.
I might just be stupid to see the simple solution, i just feel like I've tried some of the things that I'd believe would work. (As the onclick="ResetText()" with a JS code attached to it)
When I click on drop down this is what showing.
Best Regards,
You don't want to wire an onclick listener on your option element, you want an onchange event listener on your select element. onclick is not supported on option elements.
use onchange instead of using onclick and this action should be on the select tag. not on the options. Try this example.
$('select').on('change', function() {
if (this.value === 'disabled') {
this.value = '';
}
console.log(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select asp-for="Dinosaur" class="combobox" id="dinoType" asp-items="Html.GetEnumSelectList<Dinosaurs>()">
<option selected="selected" type="text" value="disabled">Please select (Or Type)</option>
<option type="text" value="One">One</option>
<option type="text" value="two">two</option>
</select>
<span asp-validation-for="Dinosaur" class="text-dark" />

On checkbox click change select box into a textbox with the same ID

Wondering if it is possible that when a checkbox is clicked it changes the select box to a textbox with the same id "Wine_name"
Not really clued up when it comes to javascript, so any help will be greatly appreciated.
The reason I need this, when a user is filling out a form, if the selectbox does not have the option they want to select, they can click the check box which will then allow them to manually type in the text they want.
Well.. you can do it.. just keep in min that you have to disable the hidden input so that it wont be processed when the form is submited.
Have a look at the code that i've come up to do it.
I'm not sure it you really need the same 'id' attribute, if you're just sending a form and processing the result on the server side, you can 'name' the submitted parameters with the 'name' attribute. So that you can freely use different ids on the view side without changing the backend to conditionally verify it.
var checkbox = document.querySelector("#custom_value");
var select = document.querySelector("#selection");
var altSelect = document.querySelector("#selection_alt");
checkbox.addEventListener('change', function(event) {
select.classList.toggle('hidden');
select.disabled = !select.disabled;
altSelect.classList.toggle('hidden');
altSelect.disabled = !altSelect.disabled;
});
.hidden {
display: none;
}
<input type="checkbox" id="custom_value"> Alternative
<br>
<select id="selection" name="selection">
<option value="1">1</option>
<option value="1">2</option>
<option value="1">3</option>
<option value="1">4</option>
<option value="1">5</option>
</select>
<input type="text" disabled class="hidden" name="selection" id="selection_alt" placeholder="Custom value..">

jquery-select2: selection of multiple options at once with a button

I have a list of users that can be selected (multiple selection is possible). Of course all users can be selected manually, which is excellent.
Further on I have user groups. Most of the times it is required to select only those users of a group. Therefore i would like to have a kind of quickway to add all the users, just by clicking on the a group name.
I'm a big fan of select2, but i wasn't able to get this to work.
I have found that via the .val() function elements could be selected. But these elements are only displayed when another element is selected.
So i need a kind of update function. How can i do this?
I have tried to trigger events (like change) but without success.
Can you help me?
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/css/select2.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/js/select2.full.js"></script>
<script type="text/javascript">
$("#id_invited_user").select2({
"placeholder": "Select user",
});
$("#testbuttonclick").on('click',function (clickEvent){
clickEvent.preventDefault();
$("#id_invited_user").val([1,2]);
});
</script>
<select multiple="multiple" class="selectmultiple form-control"
id="id_invited_user" name="invited_user">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
<option value="4">Option4</option>
<option value="5">Option5</option>
</select>
<a href="" id="testbuttonclick" >select predefined options</a>
You have all of the right code, except you are missing one important detail.
Whenever you change the value of Select2 (or any other JavaScript component), you should always trigger the change event. This event is nativly triggered by the browser when the value is changed, but it must be manually triggered when the value is changed programmatically.
$("#id_invited_user").trigger("change");
This should always be placed after your call to .val(xyz).

jQuery show/hide multiple 'Other' input fields based on select drop down

I am using the follwoing jQuery to show/hide an 'Other' title field on page:
$('label[for=customerTitleOther], #customerTitleOther').hide();
$('.jTitle').change(function() {
if($(this).val() != 'Other') {
$('label[for=customerTitleOther], .jOther').hide();
}
else {
$('label[for=customerTitleOther], .jOther').show();
}
});
The field & associated label are hidden by default. However, the application i am building has scope for multiple entries on the same page so there may be multiple other fields like. Any ideas on how to extend the jQuery to cope with any number of 'Other' fields on page?
Well, it's not trivial, but what I've implemented is a "toggleOnSwitch" mechanism. Fragments of the page are annotated with the class name "toggleOnSwitch" and another class that tells what <option>, checkbox, or radio button determines visibility. The event handlers attached to the "toggler" elements (that is, the <options> or input fields) add or remove a particular class from the "toggled" elements, and (when switched "off" make sure that input fields are marked as "disabled" and a couple of other book-keeping tasks like that.
One trick is that when the "toggler" element is something like an <option> or a radio button input, when one element is toggled "off" the code has to check to see whether another element is toggled "on". That's because there's no event logged when one radio button loses the "checked" setting because another one has been clicked.
I've been thinking about posting my code for this, but it'd have to be cleaned up a little and stripped of one or two specialized hacks for my own application. Also, I'd want to make it use John Resig's "metadata" plugin instead of the cheesy version I did myself (before I knew "metadata.js" is available).
To answer my own question:
$(".jTitle").change(function(){
//set the select value
var val = $(this).val();
if(val != "Other") {
$(this).nextAll('.jOther').hide();
} else {
$(this).nextAll('.jOther').show();
}
})
With the HTML being:
<td>
<select id="titleDepend1" class="inlineSpace jTitle">
<option value="Please select">Please select...</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
<option value="Dr">Dr</option>
<option value="Other">Other</option>
</select>
<label for="otherDepend1" class="inlineSpace jOther">Other</label>
<input type="text" class="text jOther" name="otherDepend1" id="otherDepend1" maxlength="6" />
</td>
So all the following elements with class jOther will be shown onChange.

Categories

Resources