Select tag status check with javascript? - javascript

I have two select tags now what i want is that only one should be selected at a time that is from two select tags user should only select one and if the user select from both the tags then it should display error that only one should be selected
What i am using
var $institution=document.getElementById('institutionselect').value;
var $section=document.getElementById('sectionselect').value;
if($institution.selectedIndex = 0 && $section.selectedIndex = 0){
alert('please select one amongst two');
return false;
}else if($institution.selectedIndex = null && $section.selectedIndex = null){
alert('please select one amongst two');
return false;
}
Please help in correcting the code Thank you!

Problem is you are assigning instead of comparing. Use == instead of =.
if($institution.selectedIndex = 0 && $section.selectedIndex = 0)
Also update this line removing .value in order to use .selectedIndex:
var $institution=document.getElementById('institutionselect');
var $section=document.getElementById('sectionselect');
An example:
var check = function() {
var $institution = document.getElementById('institutionselect');
var $section = document.getElementById('sectionselect');
if ($institution.selectedIndex == 0 && $section.selectedIndex == 0) {
alert('please select one amongst two');
return false;
}
};
<select id='institutionselect'>
<option>Select</option>
<option>Item 1</option>
<option>Item 2</option>
</select>
<select id='sectionselect'>
<option>Select</option>
<option>Item 1</option>
<option>Item 2</option>
</select>
<button onclick="check();">Check</button>

All you need to do is checking for both value in one condition like so :
var $institution = document.getElementById('institutionselect').value;
var $section = document.getElementById('sectionselect').value;
// if both variable have values
if ( $institution && $section ){
alert('please select one amongst two');
return;
}
// do something here
DEMO

Related

Filtering with jQuery "find" and "filter" with multiple dropdowns

I have been trying to make some filter options for a page on a clients website with multiple dropdown menus. I can make it work, but it will always reset the filtering when I select an option. I need them to work "together". It's for filtering rooms in a hotel (not a lot of rooms there).
So the first dropdown is the number of persons that can fit in a room, then the type of room to rent, and finally the number of bedrooms in that room/house.
A user can user all 3 dropdowns to filter his results, or he can use only 1. Whatever he likes. He must be able to select "3" in the first dropdown, then it filters everything to show only rooms with up to "3" in the results box. After, if he selects "Studios" in the second dropdown, it needs to keep in mind he has selected "3" for the number of persons that fits in the room, but also the keep in mind that he just selected "Studios" now, so it should display Studios that can have up to 3 persons. etc.
I think you get the idea.
Here's my HTML code:
<select class="bedroom-min">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select class="type">
<option value="all">Select...</option>
<option value="casitas">Casitas</option>
<option value="studios">Studios</option>
<option value="dorm">Dorm</option>
</select>
<select class="bedrooms">
<option value="all">Select...</option>
<option value="1">1 bedroom</option>
<option value="2">2 bedrooms</option>
</select>
<div class="property-load-section">
<div class="property-item" data-bedrooms="5" data-type="casitas" data-bed="1">Room #529</div>
<div class="property-item" data-bedrooms="4" data-type="studios" data-bed="2">Room #737</div>
<div class="property-item" data-bedrooms="3" data-type="dorm" data-bed="2">Room #123</div>
<div class="property-item" data-bedrooms="2" data-type="studios" data-bed="2">Room #126</div>
<div class="property-item" data-bedrooms="1" data-type="casitas" data-bed="1">Room #523</div>
</div>
And here's the jQuery code :
//Filtering for number of person that can sleep in that room
$("select").change(function() {
var minValue = $('select.bedroom-min').val();
$('.property-load-section').find('.property-item').filter(function () {
return $(this).attr('data-bedrooms') < minValue;
}).fadeOut('fast');
$('.property-load-section').find('.property-item').filter(function () {
return $(this).attr('data-bedrooms') >= minValue;
}).fadeIn('fast');
});
//Filtering for type of rooms
$("select.type").change(function() {
var roomType = $('select.type').val();
$('.property-load-section').find('.property-item').filter(function () {
return $(this).attr('data-type') != roomType;
}).fadeOut('fast');
});
//Filtering for the number of bedrooms
$("select.bedrooms").change(function() {
var roomBed = $('select.bedrooms').val();
$('.property-load-section').find('.property-item').filter(function () {
return $(this).attr('data-bed') != roomBed;
}).fadeOut('fast');
});
Here's a CodePen link: https://codepen.io/anon/pen/bRxXVK?editors=1010
Can anyone help me out with this? I'm pretty new to javascript/jQuery. Thanks a lot
I would recommend doing the same logic for each select's change event and in that logic you should check for all of the three filtering options at once. In the cases of type and bedrooms the value "all" should also be taken into consideration as it is a special value which will not be equal to the data- attributes you set.
With that said here is the modified JavaScript code:
//call the same function for each select's change event
$("select.bedroom-min, select.type, select.bedrooms").change(updateRooms);
function updateRooms() {
//get all the values
var minValue = $('select.bedroom-min').val();
var roomType = $('select.type').val();
var roomBed = $('select.bedrooms').val();
$('.property-load-section')
.find('.property-item')
.hide()
.filter(function () {
var okMinBedrooms = $(this).attr('data-bedrooms') >= minValue;
var okRoomType = true;
if(roomType !== "all"){
okRoomType = $(this).attr('data-type') === roomType;
}
var okRoomBed = true;
if(roomBed !== "all"){
okRoomBed = $(this).attr('data-bed') === roomBed;
}
//only fade a room if it satisfies all three conditions
return okMinBedrooms && okRoomType && okRoomBed;
}).fadeIn('fast');
}
And a CodePen link.
Check out this fiddle - https://jsfiddle.net/pjz958n6/.
$("select").change(function() {
var minValue = $('select.bedroom-min').val();
var roomType = $('select.type').val();
var roomBed = $('select.bedrooms').val();
$('.property-load-section').find('.property-item').filter(function () {
return $(this).attr('data-bedrooms') < minValue
|| ($(this).attr('data-type') != roomType || roomType == "all")
|| ($(this).attr('data-bed') != roomBed || roomBed == "all");
}).fadeOut('fast');
$('.property-load-section').find('.property-item').filter(function () {
return $(this).attr('data-bedrooms') >= minValue
&& ($(this).attr('data-type') == roomType || roomType == "all")
&& ($(this).attr('data-bed') == roomBed || roomBed == "all");
}).fadeIn('fast');
});
All you need to do is just evaluate all the select options on change of any. The similar for fade-out, just that you need to do an || contrary to && in fade-in.
Here is the fixed JavaScript code or JsFiddle :
$(document).ready(function(){
// Once document is ready
// Reference to dropdowns
var ddlRooms = $('select.bedroom-min');
var ddlType = $('select.type');
var ddlBedRooms = $('select.bedrooms');
// Hook up event handler for change event
ddlRooms.change( doFilter );
ddlType.change( doFilter );
ddlBedRooms.change( doFilter );
// Start with initial filtering
doFilter();
function doFilter(){
// Start with hiding all property item
$('.property-load-section > .property-item').hide();
// Get the selected values
var selectedRooms = parseInt(ddlRooms.val());
var selectedType = ddlType.val();
var selectedBedRooms = ddlBedRooms.val();
// Get items matching rooms
var matched = $('.property-load-section').find('.property-item').filter(function () {
// Current property item
var curPropertyItem = $(this)
var curPropertyRooms = parseInt(curPropertyItem.attr('data-bedrooms'))
var curPropertyType = curPropertyItem.attr('data-type');
var curPropertyBeds = curPropertyItem.attr('data-bed');
//console.log('Rooms matched: ' + roomMatched());
//console.log('Type matched: ' + roomTypMatched());
//console.log('Beds matched: ' + bedsMatched())
return ( roomMatched() && roomTypMatched() && bedsMatched() );
function roomMatched(){
return curPropertyRooms >= selectedRooms;
}
function roomTypMatched(){
if ( selectedType === 'all' ){
return true;
}
else if( curPropertyType === selectedType ){
return true;
}
else{
return false;
}
}
function bedsMatched(){
if( selectedBedRooms === 'all' ){
return true;
}
else if ( curPropertyBeds === selectedBedRooms ){
return true;
}
else{
return false;
}
}
});
// Show matched property
//console.log('Matched items: ' + matched.length);
matched.show();
}
})

Jquery Select Dropdown to add or remove a class

I am building a web application where you can mark TV shows as "Want to Watch", "Currently Watching", "Finished Watching", or "Stopped Watching." There is a dropdown to select between these. If "Currently Watching" is selected, two more dropdowns should also be displayed for a user to enter their last watched season and episode. However, I am having trouble getting the jQuery to work properly
HTML
<select name="updateTvStatus" class="form-control" id="updateTvStatus">
<option value="4" selected>Want to Watch</option>
<option value="1">Currently Watching</option>
<option value="2">Finished Watching</option>
<option value="3">Stopped Watching</option>
</select>
<div id="last-watched" class="hidden">
<select name="updateLastSeason" class="form-control" id="updateLastSeason">
<option value="0">Select Season:</option>
<option value="1">Season 1</option>
<option value="2">...</option>
</select>
<select name="updateLastEpisode" class="form-control" id="updateLastEpisode">
<option value="0">Select Episode:</option>
<option value="1">Episode 1</option>
<option value="2">...</option>
</select>
</div> <!-- /last-watched -->
jQuery
$(document).ready(function() {
$("#updateTvStatus").change(function() {
var TVstatus = $("#updateTvStatus").val();
var ishidden = $('#last-watched').hasClass("hidden");
if (TVstatus == 1 && ishidden == TRUE) {
$('#last-watched').removeClass("hidden");
} elseif (TVstatus != 1 && ishidden == FALSE) {
$('#last-watched').addClass("hidden");
}
});
});
else if (elseif) - syntax error.
Since JS is case sensitive, you'll ve to change TRUE/FALSE to true/false.
You've specified class selector instead of id selector. Pls change $('.last-watched') to $('#last-watched').
(And you may use === instead of == for strict comparison).
So, a completed code ll look like this to work:
$(document).ready(function() {
$("#updateTvStatus").change(function() {
var TVstatus = $("#updateTvStatus").val();
var ishidden = $('#last-watched').hasClass("hidden");
if (TVstatus == 1 && ishidden == true) {
$('#last-watched').removeClass("hidden");
} else if (TVstatus != 1 && ishidden == false) {
$('#last-watched').addClass("hidden");
}
});
});
I don't know what exactly you are looking for . But this is what you want for :
$(document).ready(function() {
$('#last-watched').hide();
$("#updateTvStatus").change(function() {
var TVstatus = $("#updateTvStatus").val();
if(TVstatus == 1){
$('#last-watched').show();
}else {
$('#last-watched').hide();
}
});
});
</script>

Change selected option

I have the following select:
<select id="sitestyle" name="stil">
<option value="blue">Blå</option>
<option value="green">Grön</option>
<option value="red">Röd</option>
<option value="pink">Rosa</option>
</select>
I'm saving the value the user has selected to localStorage. Say the user selects value="pink" and it is then saved to the localStorage, user closes browser and opens again i want value="pink" to be selected automatically. Currently it is always value="blue" regardless of what is saved in the localStorage.
Can't use jQuery/Ajax but javascript is fine.
edit
I have the following JS:
function setStyleFromStorage(){
style = localStorage.getItem("style");
document.getElementById('css_style').setAttribute('href', style);
if(style == "blue"){
document.getElementById("sitestyle").selectedIndex() = 0;
}else if(style == "green"){
document.getElementById("sitestyle").selectedIndex() = 1;
}else if(style == "red"){
document.getElementById("sitestyle").selectedIndex() = 2;
}else if(style == "pink"){
document.getElementById("sitestyle").selectedIndex() = 3;
}
}
Use following code to change select box value.
function setStyleFromStorage(){
if(localStorage.style){
document.getElementById("sitestyle").value = localStorage.style;
}
}
document.getElementById("sitestyle").onchange = function(){
localStorage.style = this.value;
}
JSFIDDLE

Hide Element with JS due to two conditions

I'm not that familiar with JavaScript. What I was doing so far was to hide a part of my form (see below: "Memo"), when someone changed an input-text-field via onchange (field-name: "ordernumber").
Therefore I'm using this funktion:
<script language="JavaScript" type="text/javascript">
function takeawayfield()
{ dok=0;
if (document.getElementById("ordernumber").changed == true) dok=1
if (dok==0)
{document.getElementById("Memo").style.display = "none";}
else
{document.getElementById("Meno").style.display = "inline";}
}
</script>
This works pretty fine, but now I'd like to add another condition from a dropdown (select option). In other words: When you change ordernumber AND select a certain option, "Memo" should disappear. I tried a lot, but I can't get it to work properly. This was my latest try:
function takeawayfield()
{ dok=0;
if (document.getElementById("ordernumber").changed == true && document.getElementById("system").value == "sys1") dok=1
if (dok==0)
{document.getElementById("Memo").style.display = "none";}
else
{document.getElementById("Memo").style.display = "inline";}
Two things are not working right with this one: It performs when only one of the conditions is true (although I used &&) and it seems to be unrelevant which option from the dropdown ist selected. Right now it performs with every option, but it should only perform with "sys1".
BTW: I added onchange="javascript:takeawayfield()" to both of the affected form-elements (input text and select option). I guess that's right?
What am I doing wrong?
Thanks in advance!
EDIT:
Here are the html-tags:
<input type="text" name="ordernumber" id="ordernumber" value="<?php echo htmlspecialchars($ordernumber); ?>" onchange="javascript:takeawayfield()">
<select name="system" id="system" onchange="javascript:takeawayfield()">
<option value="sys1">System 1</option>
<option value="sys2">System 2</option>
<option value="sys3">System 3</option>
</select>
Try this:
var dok = 0,
initialValue = "",
ordernumber = null,
system = null,
memo = null;
window.onload = function() {
// get dom objects
ordernumber = document.getElementById("ordernumber");
system = document.getElementById("system");
memo = document.getElementById("Memo");
// set initial value
initialValue = ordernumber.value;
};
function takeawayfield() {
if (ordernumber.value != initialValue && system.value == "sys1") {
dok = 0;
memo.style.display = "none";
} else {
dok = 1;
memo.style.display = "inline";
}
};
jsFiddle
If you want to react to changes by the user after the page has loaded you could listen to the keyup event of the input box and the dropdown.
Here's an example:
window.onload = function() {
document.getElementById("ordernumber").addEventListener('keyup', takeawayfield, false);
document.getElementById("system").addEventListener('change', takeawayfield, false);
function takeawayfield()
{
if (document.getElementById("system").value == "sys1") {
toggleMemo(false);
}
else {
toggleMemo(true);
}
}
function toggleMemo(show) {
var memo = document.getElementById("Memo");
if (show) {
memo.style.display = "inline";
}
else {
memo.style.display = "none";
}
}
};
http://jsfiddle.net/je5a7/
If your dropdown (select/option) have values in the option tag then the code below should be work fine. (after the user selects)
The select for example:
<select id="system">
<option value="sys1">system 1</option>
</select>
Your code
document.getElementById("system").value == "sys1"
OR you change your code:
if (document.getElementById("ordernumber").changed == true) dok=1;
else dok=0;
if (document.getElementById("system").value == "sys1") dok=1
else dok=0;

Values of two select boxes

Briefly Explaining my program :
I Have 3 select boxes
If the value selected by the user in the 1st box is 2 & Value selected by the user in second box is 3 (option values) then the third select box should display an array.
This code doesn't work but shows an idea:
if ($('#firstbox').click(function() { ($(this).val() == '2'); } &&
$('#secondbox').click(function() { ($(this).val() == '3'); }) {
// Array Display here (not included the coding here, because there is no issue with this coding.. seems working fine)
}
I need help for the code included in if statment and && operation for checking the expression.
var select1 = $('#firstbox');
var select2 = $('#secondbox');
$([select1, select2]).change(function () {
if ( select1.val() == 2 && select2.val() == 3 ) {
// run your code here...
}
});
You need to either bind the click event to the third select box or bind to the change event of the first two boxes and callback a common function which updates the third one.
$("#firstbox, #secondbox").change(UpdateThird);
function UpdateThird() {
var a = $("#firstbox").val();
var b = $("#secondbox").val();
if (a == 2 && b == 3) {
// ...
}
}
assuming
<select id="firstbox">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="secondbox">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
script:
$('#secondbox, #firstbox').on('change',function(){
if($('#firstbox').val() == 2 && $('#secondbox').val() == 3)
alert('array display code here...');
})

Categories

Resources