Show/hide div on select - javascript

I am trying to show div's depending on which value a select box is on. With my current script it is working, however, when I change the value of the select it shows the next div without hiding the previously selected one. I only want this JS script to show the currently selected div, not every div that is selected by the select box (ie. switching from one option to another).
js and html
<script>
$(function() {
$('#contract_bid').hide();
$('#equipment_purchase').hide();
$('#hiring_employees').hide();
$('#marketing').hide();
$('#expansion').hide();
$('#working_capital').hide();
$('#inventory_purchase').hide();
$('#refinancing').hide();
$('#other').hide();
$('#loan_application_requested_purpose').change(function(){
if($('#loan_application_requested_purpose').val() == 'Contract Bid') {
$('#contract_bid').show();
} else if($('#loan_application_requested_purpose').val() == 'Equipment Purchase') {
$('#equipment_purchase').show();
} else if($('#loan_application_requested_purpose').val() == 'Hiring Employees') {
$('#hiring_employees').show();
} else if($('#loan_application_requested_purpose').val() == 'Marketing') {
$('#marketing').show();
} else if($('#loan_application_requested_purpose').val() == 'Expansion/Renovation') {
$('#expansion').show();
} else if($('#loan_application_requested_purpose').val() == 'Working Capital') {
$('#working_capital').show();
} else if($('#loan_application_requested_purpose').val() == 'Inventory Purchase') {
$('#inventory_purchase').show();
} else if($('#loan_application_requested_purpose').val() == 'Refinancing') {
$('#refinancing').show();
} else {
$('#other').show();
}
});
});
</script>
# HTML
<div id="contract_bid"></div>
<div id="equipment_purchase"></div>
<div id="hiring_employees"></div>
<div id="marketing"></div>
<div id="expansion"></div>
<div id="working_capital"></div>
<div id="inventory_purchase"></div>
<div id="refinancing"></div>
<div id="other"></div>

Like this
Give all the divs a class, for example "loan_purpose"
change your script to this:
$(function() {
$('#loan_application_requested_purpose').on("change",function(){
$(".loan_purpose").hide();
// change all spaces to underscore and grab the first part of Expansion/
var $div = $("#"+$(this).val().toLowerCase().replace(/ /g,"_").split("/")[0]);
if ($div.length>0) $div.show();
else $("#other").show();
}).change(); // run change on load to show relevant already selected
});
Alternative to giving a class: if your divs have a common parent, you can do
$("#parentID > div").hide();
instead of
$(".loan_purpose").hide();
Alternative solution:
If you can change the values to reflect the IDs of the divs to show then the script will be much shorter:
<select id="loan_application_requested_purpose">
<option value="other">Please select</option>
<option value="equipment_purchase">Equipment Purchase</option>
.
.
<option value="expansion">Expansion/Renovation</option>
</select>
Then my script needs only
$(function() {
$('#loan_application_requested_purpose').on("change",function(){
$(".loan_purpose").hide();
$("#"+$(this).val()).show();
}).change(); // run change on load to show relevant already selected
});

First of all add common class to all your divs:
<div id="other" class="section"></div>
<div id="contract_bid" class="section"></div>
<!-- and so on ... -->
Then it will allow you to reduce your code:
$(function () {
$('.section').hide();
$('#loan_application_requested_purpose').change(function () {
$('.section').hide();
var val = $(this).val();
if (val == 'Contract Bid') {
$('#contract_bid').show();
} else if (val == 'Equipment Purchase') {
$('#equipment_purchase').show();
}
// other checks ....
else {
$('#other').show();
}
});
});
Note that it's cleaner to calculate value only once with var val = $(this).val(); and use it later.
And finally even better would be to use CSS to initially hide sections (and get rid of the first $('.section').hide();):
.section {
display: none;
}

<div id="#myDivs">
<div id="contract_bid"></div>
<div id="equipment_purchase"></div>
<div id="hiring_employees"></div>
<div id="marketing"></div>
<div id="expansion"></div>
<div id="working_capital"></div>
<div id="inventory_purchase"></div>
<div id="refinancing"></div>
<div id="other"></div>
</div>
if($('#loan_application_requested_purpose').val() == 'Contract Bid') {
$("#myDivs div").hide()
$('#contract_bid').show();
}else
{
...

you can hide the visible div before you display the hidden div:
$(function() {
$('#contract_bid').hide();
$('#equipment_purchase').hide();
$('#hiring_employees').hide();
$('#marketing').hide();
$('#expansion').hide();
$('#working_capital').hide();
$('#inventory_purchase').hide();
$('#refinancing').hide();
$('#other').hide();
$('#loan_application_requested_purpose').change(function(){
// here comes the change:
$('.loan_application_purpose:visible').hide();
if($('#loan_application_requested_purpose').val() == 'Contract Bid') {
$('#contract_bid').show();
} else if($('#loan_application_requested_purpose').val() == 'Equipment Purchase') {
$('#equipment_purchase').show();
} else if($('#loan_application_requested_purpose').val() == 'Hiring Employees') {
$('#hiring_employees').show();
} else if($('#loan_application_requested_purpose').val() == 'Marketing') {
$('#marketing').show();
} else if($('#loan_application_requested_purpose').val() == 'Expansion/Renovation') {
$('#expansion').show();
} else if($('#loan_application_requested_purpose').val() == 'Working Capital') {
$('#working_capital').show();
} else if($('#loan_application_requested_purpose').val() == 'Inventory Purchase') {
$('#inventory_purchase').show();
} else if($('#loan_application_requested_purpose').val() == 'Refinancing') {
$('#refinancing').show();
} else {
$('#other').show();
}
});
});
HTML:
<div id="contract_bid" class="loan_application_purpose"></div>
<div id="equipment_purchase" class="loan_application_purpose"></div>
<div id="hiring_employees" class="loan_application_purpose"></div>
<div id="marketing" class="loan_application_purpose"></div>
<div id="expansion" class="loan_application_purpose"></div>
<div id="working_capital" class="loan_application_purpose"></div>
<div id="inventory_purchase" class="loan_application_purpose"></div>
<div id="refinancing" class="loan_application_purpose"></div>
<div id="other" class="loan_application_purpose"></div>

Always hide all then show selected:
$( '#trigger' ).change( function() {
var selected_id = '#' + $('#trigger').val(); // Grab the ID to show
$( '.foo' ).hide(); // Hide all
$( selected_id ).show(); // Show selected
} ).change(); // Run at least once
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="trigger">
<option>d1</option>
<option>d2</option>
</select>
<div id="d1" class="foo">D1</div>
<div id="d2" class="foo">D2</div>

Here, you have to hide other div in if or elseif condition like in if
if($('#loan_application_requested_purpose').val() == 'Contract Bid') {
$('#contract_bid').show();
$('#equipment_purchase').hide();
$('#hiring_employees').hide();
$('#marketing').hide();
$('#expansion').hide();
$('#working_capital').hide();
$('#inventory_purchase').hide();
$('#refinancing').hide();
}

Related

IF returns false but should return true

HTML:
<div class="container" id="1" onclick="test()"> </div>
<div class="container" id="2" onclick="test()"> </div>
<div class="container" id="3" onclick="test()"> </div>
<div class="container" id="4" onclick="test()"> </div>
JS:
{
document.getElementById(e.target.id).appendChild(document.NewDiv("div", {id:"element1"}));
if (document.getElementById("1").contains(document.getElementById("element1")) &&
document.getElementById("2").contains(document.getElementById("element1")))
{
console.log("yes")
}
else
{
console.log("no")
}
};
This code returns "no" when element1 is in containers with id 1 and 2 but in my meaning it should be "yes"
But this code returns "yes" as should it be - if element1 is present in at least one of the two containers
{
document.getElementById(e.target.id).appendChild(document.NewDiv("div", {id:"element1"}));
if (document.getElementById("1").contains(document.getElementById("element1")) || //<-- changed
document.getElementById("2").contains(document.getElementById("element1")))
{
console.log("yes")
}
else
{
console.log("no")
}
};
I want this code to return "yes" if element1 is in container 1 and 2
{
document.getElementById(e.target.id).appendChild(document.NewDiv("div", {id:"element1"}));
if (document.getElementById("1").contains(document.getElementById("element1")) &&
document.getElementById("2").contains(document.getElementById("element1")))
{
console.log("yes");
}
else
{
console.log("no");
}
};
You can't have the same element in two different containers. Therefore the && condition can't be true, while || can.
id attribute must be unique, you should not have more than one element with the same id in the same document.
If you happened to have multiple elements with the same id, only the first element can be selected with document.getElementById().
However, theoretically you could use myelement.querySelector('[id="element1"]') to get element with id in the myelement container, but you should fix the code by not using the same ids.
if (document.getElementById("1").contains(document.getElementById("1").querySelector("[id='element1']")) &&
document.getElementById("2").contains(document.getElementById("2").querySelector("[id='element1']"))))
{
console.log("yes")
}
else
{
console.log("no")
}

Hide and show a div not working, the element changes its property When I use console.log() but not showing

I'm using ASP.NetCore 2.0 got a view and I'm trying to show and hide an element when the user uses a toggle button but I really don't know what's happening
My HTML:
<div class="row" id="ToggleClasificarIVA">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-check has-success">
<label class="control-label">Clasificar Impuesto al valor agregado</label>
<div class="switch">
<label>
<input type="checkbox" id="ClasificarIvaToggle" ><span class="lever"></span>
</label>
</div>
</div>
</div>
</div>
<div class="row" id="CodigoActividadDropdown" style="display:none">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-group has-success">
<label class="control-label">Codigo de Actividad</label>
<select class="form-control custom-select">
<option value="0">---Seleccione---</option>
<option value="1">Cedula Fisica</option>
<option value="2">Cedula Juridica</option>
<option value="3">Dimex</option>
<option value="4">Nite</option>
</select>
</div>
</div>
</div>
And my JS:
$('#ClasificarIvaToggle').click(function () {
if (this.checked) {
$('#CodigoActividadDropdown').css("display", "block");
alert("Checekado")
console.log(document.getElementById("CodigoActividadDropdown"))
}
else {
$('#CodigoActividadDropdown').css("display", "none");
alert("UnChecekado")
console.log(document.getElementById("CodigoActividadDropdown"))
}
});
I've tryed to use :
$('#ClasificarIvaToggle').click(function () {
if (this.checked) {
$('#CodigoActividadDropdown').css("display", "block");
alert("Checekado")
}
else {
$('#CodigoActividadDropdown').css("display", "none");
alert("UnChecekado")
}
});
Also:
$('#ClasificarIvaToggle').change(function () {
if (this.checked) {
$('#CodigoActividadDropdown').fadeIn('slow');
}
else {
$('#CodigoActividadDropdown').fadeOut('slow');
}
});
Even with js only:
document.getElementById("ClasificarIvaToggle").onclick = function () {
if (this.checked) {
document.getElementById("CodigoActividadDropdown").style.display = "block";
}
else {
document.getElementById("CodigoActividadDropdown").style.display = "none";
}
}
When I log the element with console.log(getElementByID("")), I can see the element changing the display property but it's not showing in my document.
I used exactly what you provided and it works on JSfiddle.
https://jsfiddle.net/fnchz375/
$('#ClasificarIvaToggle').click(function () {
if (this.checked) {
$('#CodigoActividadDropdown').css("display", "block");
alert("Checekado")
console.log(document.getElementById("CodigoActividadDropdown"))
}
else {
$('#CodigoActividadDropdown').css("display", "none");
alert("UnChecekado")
console.log(document.getElementById("CodigoActividadDropdown"))
}
});
Could you provide any logs/error from console you are getting. Also, feel free to try example on jsfiddle.
Try this one:
$(document).ready(function() {
$('#ClasificarIvaToggle'). change(function () {
if (this.checked) {
$('#CodigoActividadDropdown').hide();
}
else {
$('#CodigoActividadDropdown').show();
}
});
});
Try this once, this should not be failed :)
jQuery('body').on('change','#ClasificarIvaToggle',function(){
if(jQuery(this).is(":checked"))
{
jQuery(this).parents("#ToggleClasificarIVA").find("#CodigoActividadDropdown").show();
}
else
{
jQuery(this).parents("#ToggleClasificarIVA").find("#CodigoActividadDropdown").hide();
}
});

Change the css of a div when a specific image is clicked

I have three images and depending on which image is clicked I want to change the css of a specific div. I just don't understand how to connect the click of an image to the div.
Below is a (bad) example of how I think it should work. I don't understand how this is accomplished without creating a function for each image/click.
$('.circle_hiw_cont img').click(
function() {
if(this == content_img_1.jpg) {
$("#content_1").css("display", "block");
$("#content_2").css("display", "none");
$("#content_3").css("display", "none");
} else {
}
}
);
HTML:
<img id="content_img_1" src="images/conent_img1.jpg"/>
<img id="content_img_2" src="images/conent_img2.jpg"/>
<img id="content_img_3" src="images/conent_img3.jpg"/>
<div id="content_1">This is div 1</div>
<div id="content_2">This is div 2</div>
<div id="content_3">This is div 3</div>
CSS:
#content_1{display:block;}
#content_2{display:none;}
#content_3{display:none;}
You can add classes to the elements and use the index and eq methods:
var $img = $('.img').on('click', function() {
$('.div').hide().eq( $img.index(this) ).show();
});
Note that as this solution is index-based, the order of elements matters.
You can also try
var $contents = $('.content');
var $imgs = $('.circle_hiw_cont img').click(function() {
var $target = $('#content_' + this.id.replace('content_img_', '')).show();
$contents.not($target).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="circle_hiw_cont">
<img id="content_img_1" src="//placehold.it/64/ff0000" />
<img id="content_img_2" src="//placehold.it/64/00ff00" />
<img id="content_img_3" src="//placehold.it/64/0000ff" />
<div id="content_1" class="content">This is div 1</div>
<div id="content_2" class="content">This is div 2</div>
<div id="content_3" class="content">This is div 3</div>
</div>
if which div is shown is predefined, that should work:
$('.circle_hiw_cont img').click(
function() {
if( $(this).attr('src') === "content_img_1.jpg") {
$("#content_1, #content_2, #content_3").toggle();
} else {
}
}
);
You actually weren't too far off, this is going to refer to the current DOM node though, not the src of the image as your code assumes:
$('.circle_hiw_cont img').click(
function() {
if(this.src == "content_img_1.jpg") {
$("#content_1").css("display", "block");
$("#content_2").css("display", "none");
$("#content_3").css("display", "none");
} else {
}
}
);
The context this in the function call refers to the DOM element that was clicked. You will need to compare the appropriate attribute, instead.
$('.circle_hiw_cont img').click(
function() {
var $this = $(this);
if($this.attr('href') == 'content_img_1.jpg') {
...
} else {
}
}
);
Provide some class name to all the images say "imgClass" and
$('.imgClass').click(
function() {
$("#content_1").css("display", "block");
$("#content_2").css("display", "none");
$("#content_3").css("display", "none");
}
);

JQuery get a contiguous sequence of elements

I'm trying to get a contiguous array of elements using JQuery. For example for the this html:
<div class="parent">
<div class="childType2">1</div>
<div class="childType2">2</div>
<div class="childType2">3</div>
<div class="childType1">4</div>
<div class="childType1">5</div>
<div class="childType1">6</div>
<div class="childType1">7</div>
<div class="childType2">8</div>
<div class="childType1">9</div>
<div class="childType1">10</div>
<div class="childType1">11</div>
<div class="childType1">12</div>
</div>
I want it to return the div's containing 4,5,6,7 (The first sequnce of the divs with the class="childType1").
I tried to do
$("<div>test</div>")($('.parent .childType2').siblings('.childType1').addBack());
But this of course will add the div with the text test after the last childType1 (12).
I'm not so good with JQuery.
Edit:
Since the div's are dynamically generated, I ended up adding for each "group" a special class post-fix of the id related to his group, and used the method described in suspectus's answer. Not exactly what i had in mind, but it works :D.
You can use either .each (docs) or .filter (docs). If you use .filter() you can chain another jQuery method after it.
var state = 0;
var elements = [];
$('.parent div').each( function( i, elem ) {
if( state != 2 && elem.className === "childType1" ) {
state = 1;
elements.push( elem );
} else if ( state == 1 ) {
state = 2;
}
} );
console.log( elements );
Or more jQuery approach:
var state = 0;
$('.parent div').filter( function() {
if( state != 2 && $(this).hasClass( "childType1" ) ) {
state = 1;
return true;
} else if ( state == 1 ) {
state = 2;
}
return false;
} ).css( 'background-color', 'red' );
<div class="parent">
<div class="childType2">1</div>
<div class="childType2">2</div>
<div class="childType2">3</div>
<div class="childType1 inner">4</div>
<div class="childType1 inner">5</div>
<div class="childType1 inner">6</div>
<div class="childType1 inner">7</div>
<div class="childType2">8</div>
<div class="childType1">9</div>
<div class="childType1">10</div>
<div class="childType1">11</div>
<div class="childType1">12</div>
</div>
$(".inner") // gives the elements required
You could use filter for this :
var $elements = $(".childType1").filter(function() {
var no = parseInt($(this).text(), 10)
return (( no > 3) && ( no < 8))
});
now $elements will contain only those matched elements between 3 and 8 ie., 4 to 7.
You can use .each() method for looping all the divs having class="childType1"
Following is the complete code. Modify it according to your need.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(".childType1").each(function (i) {
if ( $(this).html() == "4" ||$(this).html() == "5" || $(this).html() == "6" ||$(this).html() == "7") {
alert($(this).html());
}
});
});
</script>
</head>
<body>
<div class="parent">
<div class="childType2">1</div>
<div class="childType2">2</div>
<div class="childType2">3</div>
<div class="childType1">4</div>
<div class="childType1">5</div>
<div class="childType1">6</div>
<div class="childType1">7</div>
<div class="childType2">8</div>
<div class="childType1">9</div>
<div class="childType1">10</div>
<div class="childType1">11</div>
<div class="childType1">12</div>
</div>
</body>
</html>

Is there a jQuery selector to accomplish this task?

I have these 4 HTML snippets:
Siblings:
<div class="a">...</div>
<div class="b">...</div> <!--selected-->
<div class="b">...</div> <!--not selected-->
Wrapped 1:
<div class="a">...</div>
<div>
<div class="b">...</div> <!--selected-->
</div>
<div class="b">...</div> <!--not selected-->
Wrapped 2:
<div>
<div class="a">...</div>
</div>
<div>
<div class="b">...</div> <!--selected-->
</div>
<div class="b">...</div> <!--not selected-->
Separated:
<div class="a">...</div>
<div>...</div>
<div class="b">...</div> <!--selected-->
<div>...</div>
<div class="b">...</div> <!--not selected-->
<div>...</div>
<div class="b">...</div> <!--not selected-->
How can I, with jQuery, select the next .b element for any given .a element, regardless of nesting?
I want something like this:
$('.a').each(function() {
var nearestB = $(this)./*Something epically wonderful here*/;
//do other stuff here
});
Can you try this to see if it suits your case?
$(document).ready(function () {
var isA = false;
$('div.a, div.b').each(function () {
if ($(this).attr('class') == "a")
isA = true;
if ($(this).attr('class') == "b" && isA) {
$(this).css("background", "yellow");
isA = false;
}
});
});
Regards...
Got it!
var both = $('.a, .b');
$('.a').each(function() {
var nearestB = both.slice(both.index(this))
.filter('.b')
.first();
//do stuff
});​
How are you deciding which .a to select? Is there a .b for ever .a? Are you looping over each? You could use the index of the .a and simply select the corresponding .b.
$(".a").each(function(){
var index = $(".a").index(this);
var theB = $(".b").get(index);
});
Ok, here's a modified version of Padel's solution, that behaves slightly differently
var lastA = null;
$('.a, .b').each(function() {
if($(this).hasClass('a'))
{
lastA = $(this);
}
else if(lastA)
{
doStuff(lastA,this); //doStuff(a,b)
lastA = null;
}
});
$("div.a").nextAll("div.b")
Does this work?

Categories

Resources