How can I optimize this jquery script? Different classes and same function - javascript

I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.
$(document).ready(function () {
$('.sub-cat select').change(function () {
if ($('.sub-cat select option:selected').text() == "Other") {
$('.sub-cat .other-category').show();
}
else {
$('.sub-cat .other-category').hide();
}
});
$('.prod-type select').change(function () {
if ($('.prod-type select option:selected').text() == "Other") {
$('.prod-type .other-category').show();
}
else {
$('.prod-type .other-category').hide();
}
});
$('.prod-finnish select').change(function () {
if ($('.prod-finnish select option:selected').text() == "Other") {
$('.prod-finnish .other-category').show();
}
else {
$('.prod-finnish .other-category').hide();
}
});
$('.prod-color select').change(function () {
if ($('.prod-color select option:selected').text() == "Other") {
$('.prod-color .other-category').show();
}
else {
$('.prod-color .other-category').hide();
}
});
$('.prod-included select').change(function () {
if ($('.prod-included select option:selected').text() == "Other") {
$('.prod-included .other-category').show();
}
else {
$('.prod-included .other-category').hide();
}
});
$('.prod-series select').change(function () {
if ($('.prod-series select option:selected').text() == "Other") {
$('.prod-series .other-category').show();
}
else {
$('.prod-series .other-category').hide();
}
});
});

Assign a common class i.e. 'commonClass' to all the parent element i.e. 'sub-cat, prod-included,...', then use various DOM traversal methods to target 'other-category' element.
Learn to use this, element which initiated the event
$('.commonClass select').change(function () {
$(this).closest('.commonClass').find('.other-category').toggle($('option:selected', this).text() == "Other");
});
References
.closest()
.find()
.toggle()

Please check below code. On selection of other option
$(document).ready(function () {
$('select').change(function () {
if($(this).find('option:selected').text() == "other"){
$(this).next().show();
}
else{
$(this).next().hide();
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<div class="sub-cat">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="other">other</option>
</select>
<div class="other-category" style="display: none;">
<p>sub-cat other-category</p>
</div>
</div>
<div class="prod-type">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="other">other</option>
</select>
<div class="other-category" style="display: none;">
<p>prod-type other-category</p>
</div>
</div>
</body>
</html>
show below div .

You can select several elements at once by separating their class selections with a comma.
$('.sub-cat, .prod-type, .prod-finnish, .prod-color, .prod-included, .prod-series').change(function() {
var $this = $(this); // cache this so we don't have to wrap it twice
$this.toggle($this.find('option:selected').text() == "Other"));
});
It's then just a matter of using .toggle() and passing in a boolean; In our case whether the selected option has "Other" as its text.
This has a really good performance advantage since you only need one event delegate to handle the change event for all the elements in the selector.

You can utilize data-attributes to help you out. I didnt test out this code, but I think something like this could possibly work. Update your HTML to be something like this
<select data-target="sub-cat"></select>
<div class="other-category" data-target="sub-cat"></div>
Followed by this abbreviated jquery code...
$(document).ready(function () {
$('select').change(function() {
var target = $(this).data('target'),
isSelected = $(that).find('option:selected').text() == "Other";
$(this).find('.other-category[data-target="'+target+'"]').toggleClass(isSelected);
})
});
By storing the attributes in a data-attribute, you can easily access that in your javascript code, targeting specific elements much more easily.

Related

JQuery check multiple Selects value

I have a number of HTML selects like follows on one page:
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>
I want to use Jquery to check each select to ensure the initial value "select" has been changed - eg: another options has been selected. If it hasn't changed I want to change the selects color.
I've tried the following Jquery but it's not fully functional:
if($('select').val() == 'select') {
alert('got one...');
$(this).css({'color' : 'red'});
}
Note: the page has around 25 selects and I'm try to get one piece of jquery to cover all.
You can use change event handler and check for selected value: Check the snippet below
$('select').on('change', function() {
if ($(this).val() == 'select') {
alert('got one...');
$(this).css({
'color': 'red'
});
} else {
$(this).css({
'color': 'initial'
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>
check out this: .val()
$("select").each(function(){
if($(this).val() == "YourDefaulValue"){
$(this).css({'color' : 'red'});
}
});
You have to iterate the elements yourself. Luckily, it's quite simple and a very small change to your code:
$('select').each(function() {
var $this = $(this);
if($this.val() == 'select') {
// probably shouldn't alert here...
// alert('got one...');
$this.css({'color' : 'red'});
}
}
If you need to check all selects you have to test if one or more is "unselected". To achieve this you may do:
$(function () {
$('#resetBtn').on('click', function(e) {
$('select').each(function(index, element) {
$(this).css({'color' : 'black'});
});
});
$('#checkBtn').on('click', function(e) {
$('select').each(function(index, element) {
if (element.selectedIndex == 0) {
alert('got one...');
$(this).css({'color' : 'red'});
}
});
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<button id="checkBtn">Check select</button>
<button id="resetBtn">Reset select</button>
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>

show and hide div depending upon selected checkbox with combobox option

I have used this multiselect checkbox with a combobox option..
JsFiddle
In my jsfiddle that checkbox with a combobox type will not work. I have too many codes. So, I didn't included. See this link for full codes I'm trying to show and hide the div content depending upon selected checkbox. it does not work. I tried this code separately (without a combobox checkbox only). it works. I have problem with checkbox with a combobox type. How do I show/hide div content based upon selected checkbox with combobox option?
Without Combobox Fiddle
Javascript
document.getElementById("option_1").onclick = function() {
if(this.checked)
document.getElementById('choose_the_correct_answer').style.display = "block";
else
document.getElementById('choose_the_correct_answer').style.display = "none";
}
I have tried this Jquery code too
$(document).ready(function(){
$('#option_1').on('change', function() {
if ( this.value == '1')
{
$("#choose_the_correct_answer").show();
}
else
{
$("#choose_the_correct_answer").hide();
}
});
});
HTML
<select id="control_3" name="control_3[]" multiple="multiple" size="5">
<option value=""></option>
<option id="option_1" value="option_1">Choose the Correct Answer</option>
<option id="option_2" value="option_2">Fill in the Blanks</option>
<option id="option_3" value="option_3">True or False</option>
<option id="option_4" value="option_4">Match the Following</option>
<option id="option_5" value="option_5">Two Mark Questions</option>
<option id="option_6" value="option_6">Five Mark Questions</option>
<option id="option_7" value="option_7">Others</option>
</select>
<div id="choose_the_correct_answer">choose the correct answer</div>
<div id="fill_in_the_blanks">fill in the blanks</div>
<div id="true_or_false">true or false</div>
<div id="match_the_following">match the following</div>
<div id="two_mark_questions">two mark questions</div>
<div id="five_mark_qustions">five mark questions</div>
<div id="others">others</div>
try
$('#option_1').on('click', function() {
});
and
the condition should be
if ( this.value == 'option_1')
JSFIDDLE
$(document).ready(function(){
$('#option_1').on('click', function() {
if ( this.value == 'option_1')
{
$("#choose_the_correct_answer").show();
}
else
{
$("#choose_the_correct_answer").hide();
}
});
});
UPDATE:
AND a better option will be to use .togggle() if you intend to use multiselect
UPDATED DEMO
JS:
$(document).ready(function(){
$('option').on('click', function() {
if ( this.value == 'option_1')
{
$("#choose_the_correct_answer").toggle();
}
else if ( this.value == 'option_2')
{
$("#fill_in_the_blanks").toggle();
}
else if ( this.value == 'option_3')
{
$("#true_or_false").toggle();
}
else if ( this.value == 'option_4')
{
$("#match_the_following").toggle();
}
else if ( this.value == 'option_5')
{
$("#two_mark_questions").toggle();
}
else if ( this.value == 'option_6')
{
$("#five_mark_qustions").toggle();
}
else if ( this.value == 'option_7')
{
$("#others").toggle();
}
});
});
New Update: using normal dropdown with multiselect
use
$('select').on('change', function() {
FIDDLE

jquery change function hide and show div

have this code, i want to convert it to be able to allow the user to pick ANY possible select and have div [id='setprice'] show up or something to that effect. currently i have 4 options, but it could be up to 10+ depends on how many are in the database. but it shouldn't matter, i just want which ever gets selected to open the setprice div. Thanks.
$("#category").change(function () {
$("#setprice").hide();
if ($(this).val() == "cow") { $("[id='setprice']").show(); }
else if ($(this).val() == "dog") { $("[id='setprice']").show(); }
else if ($(this).val() == "monkey") { $("[id='setprice']").show(); }
else if ($(this).val() == "kungfoo") { $("[id='setprice']").show(); }
});
HTML
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice'>this is hidden onload, then shows on any #category selection</div>
Seems to be alot of cofusion in what im asking, These options i've given are random names, the categories that are going to be loaded, are from a database and more could be added depending how it expands, so i want the script to not show div=setprice, but when anything gets selected in #category to open setprice.
You will need to call the function only when the value of the select box isn't empty.
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
Here is a working fiddle.
This is the cleanest you will get this.
DEMO
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
The $("#setprice").toggle(!!this.value); is just a way to use a boolean inside the .toggle() method,
otherwise you do it equally like:
var $setPriceEl = $("#setprice");
$("#category").change(function () {
$setPriceEl.hide(); // hide by default
if(this.value) $setPriceEl.show(); // show only if has value
});
or even:
$("#category").change(function () {
$("#setprice")[this.value ? "show" : "hide" ]();
});
Please find the answer below ...
HTML :
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice' style="display:none;">this is hidden onload,
then shows on any #category selection</div>
JQUERY :
$(document).ready(function(){
$("#category").change(function() {
$("#category option:selected" ).each(function() {
var str = $( this ).text();
if(str == "Select"){
$("#setprice").hide();
}else{
$("#setprice").show();
$("#setprice").text(str);
}
});
}).trigger("change");
});

Issues getting values from multiple <select>/<option>

Im having issues with the following code. Im simply trying to get the values from whatever is selected from my layout_select2 options.
Currently when selection multi_select and then a option from layout_select2 i end up with the first value from layout_select1 due to the way i load the url. I need a suggestion on how to fix this or reference either of my <select> object's
See Demo
Html
<select id='multi_select' name='multi_select'>
<option value='bing.com'>Bing.com</option>
<option value='Google.com'>Google.com</option>
</select>
<select name='layout_select' id='layout_select1'>
<option value='/images/search?q=windowsphone'>Windows Phone - Images</option>
<option value='/search?q=android'>Android - Search</option>
</select>
<select name='layout_select2' id='layout_select2'>
<option value='/search?q=Windows'>Windows - Images</option>
<option value='/images/search?q=Robots'>Robots - Search</option>
</select>
<input type='button' id='button' value='Click Me' />
JavaScript
$(document).ready(function () {
$('#button').click(function () {
var url = 'http://www.' + $('#multi_select').val() + $('#layout_select1').val();
window.location = url;
});
$('#layout_select1').show();
$('#layout_select2').hide();
$('#multi_select').change(function () {
if ($('#multi_select option:selected').text() == "Bing.com") {
$('#layout_select1').fadeIn('slow');
}
if ($('#multi_select option:selected').text() == "Google.com") {
$('#layout_select1').hide();
$('#layout_select2').fadeIn('slow');
} else {
$('#layout_select1').fadeOut('slow');
}
});
});
You can filter the layout_select elements to use the value of the visible select like this:
$('#layout_select1, #layout_select2').filter(':visible').val();
When you combine this with a couple tweaks to your fiddle, it works pretty well:
$(document).ready(function () {
$('#button').click(function () {
var url = 'http://www.' + $('#multi_select').val() + $('#layout_select1, #layout_select2').filter(':visible').val();
window.location = url;
});
$('#layout_select1').show();
$('#layout_select2').hide();
$('#multi_select').change(function () {
if ($('#multi_select option:selected').text() == "Bing.com") {
$('#layout_select1').fadeIn('slow');
$('#layout_select2').hide();
} else {
$('#layout_select2').fadeIn('slow');
$('#layout_select1').hide();
}
});
});

javascript focus problem

I have a form with 3 fields. Country, state and users
I am trying to do the following. when United states is selected as a country, the state field will show. The problem is that when i use the tab key on the keyboard, it is skipping the state field and its going on the users field. So i tried using the focus property so when i select United states, the state will show + selected, but I had no luck.. Below please find the code I am using
$(document).ready(function () {
$("#cmbCountries").change(function () {
$("#cmbCountries option:selected").each(function () {
if ($(this).text() == "United States") {
$("#cmbstate").show();
$("#cmbstate").focus();
}
else {
$("#cmbstate").hide();
}
});
}).change(); });
Any help please?
Chek this out
And javascript
$(function (){
$("#cmbstate").hide();
$("#cmbCountries").change(function () {
if($(this).val() == 'US')
{
$("#cmbstate").show();
$('#cmbstate').focus()
}
else{
$("#cmbstate").hide();
$('#users').focus();
}
})
})
And html
<input type="text" name="text" id="first" />
<select id="cmbCountries">
<option value="OTHER">OTHER</option>
<option value="US">US</option>
<option value="OTHER1">OTHER1</option>
</select>
<select id="cmbstate">
<option value="value">Value 1</option>
<option value="value">Value 2</option>
<option value="value">Value 3</option>
</select>
<select id="users">
<option value="asf">asdfasdf</option>
<option value="fadfas">sdffd</option>
</select>
The Tabindex values must be wrong, try and manually set the Tabindex of each input to 0, 1, 2 respectively and then you should be able to tab between them easily
Please try using this code,
$(document).ready(function () {
$("#cmbCountries").change(function () {
$("#cmbCountries option:selected").each(function () {
if ($(this).text() == "United States") {
$("#cmbstate").show();
$("#cmbstate").select();
}
else {
$("#cmbstate").hide();
}
});
}).change(); });
changed focus() to select()
I had once done this in my project also which worked for me.

Categories