Showing and hiding select boxes using javascript/ - javascript

I have a little bit of test code that intends to have a select box display when a certain option is selected and then hide when that option is changed.
HTML:
<form>
<select id="sel1" name="sel1" class="chzn-select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="sel2" name="sel2" selected="selected" style="display:none">
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
JS:
var selCategory = $('#sel1');
$(selCategory).change(function () {
$('option:selected').each(function () {
if ($(this).text() ==='2') {
$('#sel2').show();
}
else if($(this).text() ==='1') {
$('#sel2').hide();
}
else if($(this).text() ==='3') {
$('#sel2').hide();
}
});
});
This bit of code works great if only this:
if ($(this).text() ==='2') {
$('#sel2').show();
}
Is the JavaScript but falls down when adding the else if statements. Also would it be better to display the select box itself or a containing div Tag? The only reason the second select box isn't a chosen-select is that chosen doesn't seem to like elements that are already hidden (problems with width).
Any help would be appreciated.

Your $('option:selected') selector is looking at the options from all select elements, not just #sel1. So #sel2 is shown (due to "2" selected in the #sel1), then immediately hidden (due to "1" selected in #sel2 itself). Make sure you're looking only at the value you want:
var selCategory = $('#sel1');
selCategory.change(function () {
selCategory.find('option:selected').each(function () {
if ($(this).text() =='2') {
$('#sel2').show();
}
else {
$('#sel2').hide();
}
});
});

I would make it easier, grab the value and concatenate the sel ID from that:
$("#sel1").change(function() {
$("select:not(#sel1)").hide(); //hide other selects, excluding #sel1
$("#sel" + this.value).show();
});

Related

Why is my <Select> html element not updating properly after changing its content?

So I have a simple select element, which of course contains a bunch of option elements.
I'm making a simple search function in a text input field, which basically hides all option elements inside the select element that doesn't contain the search text. This works fine.
BUT, after I have hidden the necessary option elements and only shown the ones I want, there's a strange bug with the dropdown. When I click the dropdown (select element) after the changes have been made (hiding and showing option elements), it's empty on the first click. But if I click it again, it's updated correctly with the right visible option elements.
I've searched and searched and tried 20 different things to solve this annoying little issue, but I can't figure out why I have to click my dropdown twice before the changes are visible?
Can someone shed some light on this or offer a solution?
Here's some code, the option elements are dynamically created somewhere else but the code works fine for hiding/showing the option elements:
var timeoutId2;
$(document).on("input propertychange change", ".searchField", function() {
clearTimeout(timeoutId2);
var searchInput = $(this).val();
if (searchInput == "") {
$(".monsterOption").css("display", "block");
} else {
$(".monsterOption").css("display", "none");
timeoutId2 = setTimeout(function() {
$(".monsterOption").each(function(i, ele) {
var monstername = $(this).data("monstername");
if (monstername.toLowerCase().indexOf(searchInput.toLowerCase()) != -1) {
$(".monsterDropdown").val(monstername);
$(this).css("display", "block");
}
});
}, 300);
}
});
<input class="searchField" type="text" placeholder="search here">
<select class="monsterDropdown">
<option class="monsterOption" data-monstername="Car 1">Car 1</option>
<option class="monsterOption" data-monstername="Car 2">Car 2</option>
<option class="monsterOption" data-monstername="Plane 1">Plane 1</option>
<option class="monsterOption" data-monstername="Boat 1">Boat 1</option>
<option class="monsterOption" data-monstername="Boat 2">Boat 2</option>
</select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
You are using setTimeout to show the results after 300 milliseconds, creating the illusion that the results only show up after expanding the select the second time.
Removing it should work:
var timeoutId2;
$(document).on("input propertychange change", ".searchField", function() {
clearTimeout(timeoutId2);
var searchInput = $(this).val();
if (searchInput == "") {
$(".monsterOption").css("display", "block");
} else {
$(".monsterOption").css("display", "none");
$(".monsterOption").each(function(i, ele) {
var monstername = $(this).data("monstername");
if (monstername.toLowerCase().indexOf(searchInput.toLowerCase()) != -1) {
$(".monsterDropdown").val(monstername);
$(this).css("display", "block");
}
});
}
});
<input class="searchField" type="text" placeholder="search here">
<select class="monsterDropdown">
<option class="monsterOption" data-monstername="Car 1">Car 1</option>
<option class="monsterOption" data-monstername="Car 2">Car 2</option>
<option class="monsterOption" data-monstername="Plane 1">Plane 1</option>
<option class="monsterOption" data-monstername="Boat 1">Boat 1</option>
<option class="monsterOption" data-monstername="Boat 2">Boat 2</option>
</select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

Div class not showing on dropdown select?

Good day
I require some aid with this issue.
I have a "Location1" dropdown with about 10 options. I then have a div class I would like to show if the user selects "Other".
Code:
<script>
$(document).ready(function(){
$("#Location1").on('change' function(){
if (this.value == 'Other') {
$(".otherlocation1").show();
}
else {
$(".otherlocation1").hide();
}
});
});
</script>
It's supposed to hide div class "otherlocation1" on by default, and then show "otherlocation1" based on a selection from the "Location1" text box.
Only problem is, it's not working. I've tried numerous other ways and can't get it working.
Any help would be appreciated.
You are missing a , after change. Try this:
$(document).ready(function() {
$("#Location1").on('change', function() {
if (this.value == 'Other') {
$(".otherlocation1").show();
} else {
$(".otherlocation1").hide();
}
});
});
.otherlocation1{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='Location1'>
<option disabled selected>Select an option</option>
<option value='Other'>Other</option>
<option value='Other 2'>Other 2</option>
<option value='Other 3'>Other 3</option>
<option value='Other 4'>Other 4</option>
<option value='Other 5'>Other 5</option>
</select>
<p class='otherlocation1'>otherlocation1</p>
In Jquery the on function takes two parameters.
events
handler
So when you call the on function you pass the event and the handler separated by a comma ',' . Refer this for more info.
Thus refactor your line as follows
$("#Location1").on('change', function()

pass element ID as a parameter to jquery

I have a select box on a web form that, depending on what is selected, will show a hidden div.
<script>
$(document).ready(function () {
$("#Select1").change(function () {
$(this).find("option:selected").each(function(){
if($(this).attr("Value")=="2"){
$("#hiddentable11").show();
}
else if($(this).attr("Value")=="3"){
$("#hiddentable11").show();
}
else{
$("#hiddentable11").hide();
}
});
}).change();
});
</script>
The form will have 35 to 40 of these Select box/hidden div combinations. The option values in the select boxes will all be the same every time (0,1,2,3,4). If the user chooses option 2 or 3 for Select1, hiddentable11 appears. If they choose option 2 or 3 for Select2, hiddentable 12 appears I don't want to copy/paste this code 40 times and in the code change Select1/hiddentable11 to Select2/hiddentable12, Select3/hiddentable13 etc. How do I change this code so that I can reuse it for all of the select/div combinations?
Give all the select boxes a class, e.g. class="select". Then you can usethis.id` to get the ID of the target element, and concatenate it to the DIV id.
$(".select").change(function() {
var num = this.id.slice(6); // get N from id="SelectN"
$("#hiddentable1" + num).toggle($(this).val() == "2" || $(this).val() == "3"));
});
Then just make a .Select class, and use this, pass in the corresponding hidden table as a user defined unique data attribute (I'll use data-hidden as an example). Then you can create the proper selector for each item by doing "#"+$(this).attr("data-hidden"):
$(".Select").change(function () {
$(this).find("option:selected").each(function(){
if($(this).attr("Value")=="2") {
$("#"+$(this).attr("data-hidden")).show();
}
else if($(this).attr("Value")=="3") {
$("#"+$(this).attr("data-hidden")).show();
}
else {
$("#"+$(this).attr("data-hidden")).hide();
}
});
}).change();
Try this. With this you don't need to depend on ID's. You may multiple select boxes to your code and table combo and never have to change your js code.
<select id="select1">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<div id="hiddentable11">
Hidden Contents of Select1
</div>
<select id="select2">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<div id="hiddentable12">
Hidden Contents of Select2
</div>
<select id="select3">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<div id="hiddentable13">
Hidden Contents of Select3
</div>
$("select").change(function () {
var index = $('select').index($(this));
index++;
var $this = $(this).find("option:selected").val();
$("#hiddentable1" + index).css("display", $this === "2" || $this === "3" ? "inline-block" : "none");
});
http://jsfiddle.net/njzatgku/1/

Validating multiple select box

Select box 1
<select name="slt_drop1" id = "slt_drop1">
<option value ="0">----------</option>
...........
</select>
Select box 2
<select name="slt_drop2" id = "slt_drop2">
<option value ="0">----------</option>
...........
</select>
Select box 3
<select name="slt_drop3" id = "slt_drop3">
<option value ="0">----------</option>
...........
</select>
Select box 4
<select name="slt_drop4" id = "slt_drop4">
<option value ="0">----------</option>
...........
</select>
In a HTML form I've used 4 select buttons, if the user selects the value as "0" i.e (Default value) in any of the select button it should show message near to the select button , "please select the correct value" for that particular for example if the value of slt_drop3 is "0" it should alert near slt_drop3 select option . The message should be displayed for individual button and not common alert .
maybe this is what you want ? Demo
$("select").change(function()
{
if($(this).val() == "0")
$(this).after(' <small> please select the correct value</Small>');
else
if($(this).next().prop("tagName").toLowerCase() == "small")
$(this).next().remove();
});
$("select").trigger("change");
Do you use jQuery in your project? I think you can listen when you change the value of select and validate it:
$(function() {
$('select').on('change', validate);
function validate(e) {
var select = $(e.currentTarget);
var id = select.attr('id');
var val = select.val();
if (val === '0') {
showMessage(id);
} else {
hideMessage(id);
}
}
function showMessage(id) {
$('.message[data-select-id="' + id + '"]').show();
}
function hideMessage(id) {
$('.message[data-select-id="' + id + '"]').hide();
}
});
Add blocks for messages near each select tag and show it if necessary
<select name="slt_drop1" id = "slt_drop1">
<option value ="0">----------</option>
...........
</select>
<div class='message' data-select-id='slt_drop1'>please select the correct value</div>
Add a common class to each SELECT element.
Use jQuery to select that elements which match that class.
Bind a change event to the selector and apply the logic to check for "0" value
$(document).ready(function() {
$('select.is-valid').change(function() {
var $el = $(this);
if($el.val() == 0) {
$el.after('<div>Select a different value</div>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="test[]" class="is-valid">
<option value="0">---</option>
<option value="1">1</option>
</select>
<select name="test[]" class="is-valid">
<option value="0">---</option>
<option value="1">1</option>
</select>
<select name="test[]" class="is-valid">
<option value="0">---</option>
<option value="1">1</option>
</select>
That's a basic example of what you're trying to achieve. Actual element/validation placement is up to you. I would recommend making a "Submit" button to check the validation but I assume you know how to do that.

Jquery for retaining the selected value in select option

i am playing some show/hide function using my select drop down. Here is the html for select,
<select id="sel1" size="1" name="">
<option selected="selected" value="0">Select Here</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Here is my jquery,
$(document).ready(function(){
$("#sel1").change(fun);
});
function fun(){
var selected = $("#sel1 option:selected");
if(selected.val() == 1) {
$("#div1").slideDown("slow");
$('#div2').slideUp("slow");
} else if(selected.val() == 2) {
$("#div1").slideUp("slow");
$('#div2').slideDown("slow");
} else {
$("#div1").slideUp("slow");
$('#div2').slideUp("slow");
}
};
But after the value sent to the server and return back, I want to retain the div1 or div2 based on the value select in the dropdown. But as of now, both the div are not displaying because of display=none at initial level. Any way to retain this?
If your HTML is generated using a server-side language, your best option would be to only add the display: none CSS property to them when appropriate. Alternatively, you could just trigger the change event handler when the DOM is ready, using:
$(document).ready(function(){
$("#sel1").change(fun).trigger('change');
});

Categories

Resources