Show a hidden div using jQuery show() not working [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I have a hidden div called recipeDetailsDiv inside a form as below
$("#recipes").change(function() {
var selectedVal = $("#recipes").val();
if (selectedVal != "") {
$("#recipeDetailsDiv").show();
}
});
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="recipes">Recipes</label>
<select class="form-control" id="recipes" name="recipes" required>
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
</div>
</div>
<div class="card" style="margin-top: 10px;" id="recipeDetailsDiv" hidden>
<ul class="list-group list-group-flush">
<div id="populateRecipeDetails">Recipe Details</div>
</ul>
</div>
</form>
I am trying to show the hidden div when someone changed the drop down box
I included jQuery CDN too. But it is not showing on change of drop down box. This could be a simple problem. But I cannot figure out how to solve. Can someone help?
Edit 1
I have the following codes included in the following order
<?php include "commonFiles/assignModal.php"; ?>
<?php include "../commonFilesForAll/jsLibraries.php"; ?>
jsLibraries.php contain CDN.
assignModal.php is the same HTML codes I showed above

Your code is working fine. So as #Phil's comment, you should show us the side effect rendering code. Because it may be this problem: Event handler not working on dynamic content
Besides, I would suggest enhancement your logic code.
There are 2 ways to resolve:
Using toggle to handle the case empty select.
If the selected item is diff empty then use show, else then use hide
$("#recipes").change(function() {
const isToggle = $("#recipes").val() !== "";
$("#recipeDetailsDiv").toggle(isToggle);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="recipes">Recipes</label>
<select class="form-control" id="recipes" name="recipes" required>
<option></option>
<option >1</option>
<option>2</option>
</select>
</div>
</div>
</div>
<div class="card" style="margin-top: 10px;" id="recipeDetailsDiv" hidden>
<ul class="list-group list-group-flush">
<div id="populateRecipeDetails">Recipe Details</div>
</ul>
</div>
</form>

If recipes are optional and empty option are selected, you only need show div when an option are selected.
$("#recipes").change(function() {
$("#recipeDetailsDiv").show();
});
The show problem, you can refactor it for class. Creating a class which hides your div and use jQuery.removeClass().

Related

Dropdown Data is overlapped with some default elements

I have created a dropdown as below:
<div class="col s4">
<label class="control-label flabels">Name</label>
<div class="asteRisk">*</div>
<div class="row d-flex align-items-center">
<div id="FLevelRow" class="row">
<div class="select-wrapper">
<div class="form-group">
<div class="multipleSelection" id="TaskName">
<select required class="dynamic_Time form-control" id="TaskSKAdd">
<option value="">--Select--</option>
</select>
<div class="overSelect"></div>
</div>
</div>
</div>
</div>
</div>
</div>
and I have written below ajax success method in Js file to append ajax response to this dropdown options.
success: function (response) {
console.log("Lookupresponse", response)
for (var application of response) {
var value = application.NAME.toLowerCase();
$('#TaskName .dynamic_Time')
.append(`<option value="${application.id}" name="${value}">${value} </option>`)
}
},
But while running this code, by default some extra html elements and a select option appears before the above appended options and hence it hides appended options with ajax data from the dropdown list as shown in the below image. Because of that, original content are not visible while clicking on the dropdown. There is no error in the console also.

Change <select> id on click in jQuery

There is a select option in search form and it has an id (e.g. main_cat).
Now I want that when I click on a link('a'), the id of select should be changed with second_cat.
Note Give me solution with nesting div classes on jsFiddle, because main_cat id also used in another section on same page
Here is my sample code:
<div class="widget widget_vehicle_search">
<div class="search-form-widget">
<form id="wp-advanced-search" name="wp-advanced-search" class="wp-advanced-search" method="" action="">
<div id="wpas-main_cat" class="wpas-main_cat wpas-generic-field wpas-field">
<div class="label-container">
<label for="main_cat">Select A Manufacturer:<i class="icon-help-circled-1 tooltip"></i></label>
</div>
<select id="main_cat" name="main_cat">
<option value="any">Any Manufacturer</option>
</select>
</div>
</form>
</div>
</div>
When Click on a link main_cat id changed with second_cat
Hope you understand my question
I'm not sure if that what you mean, but you could attach click event to anchor then on click change the id attribute of the select by the new one :
$('a').on('click', function(){
$('#main_cat').prop('id', 'second_cat');
})
Hope this helps.
$('a').on('click', function(e){
e.preventDefault();
console.log('Before : '+$('select').prop('id'));
$('#main_cat').prop('id', 'second_cat');
console.log('After : '+$('select').prop('id'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget widget_vehicle_search">
<div class="search-form-widget">
<form id="wp-advanced-search" name="wp-advanced-search" class="wp-advanced-search" method="" action="">
<div id="wpas-main_cat" class="wpas-main_cat wpas-generic-field wpas-field">
<div class="label-container">
<label for="main_cat">Select A Manufacturer:<i class="icon-help-circled-1 tooltip"></i></label>
</div>
<select id="main_cat" name="main_cat">
<option value="any">Any Manufacturer</option>
</select>
</div>
</form>
</div>
</div>
<br>
<a href='#'>change select id</select>

Bootstrap Combobox Update

The Background
I have the following HTML document:
<!-- file: index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form</title>
<!-- Plugins CSS -->
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-combobox.css">
</head>
<body class="one-page fixed-header">
<div class="page-box">
<div class="page-box-content">
<h3>Form 1</h3>
<div class="content">
<div class="combobox-container" id="employee-name-box">
<label for="addScheduleLoc">Location: <span class="required">*</span></label>
<select class="form-control combobox location" name="addScheduleLoc" id="addScheduleLoc" required>
<option value selected="selected">---Select Location---</option>
</select>
</div>
<div class="combobox-container" id="employee-name-box">
<label for="addScheduleTier">Tier: <span class="required">*</span></label>
<select class="form-control combobox tier" name="addScheduleTier" id="addScheduleTier" required>
<option value selected="selected">---Select Tier---</option>
</select>
</div>
</div>
<hr>
<h3>Form 2</h3>
<div id="changeScheduleModalBody" class="content">
<div class="combobox-container" id="employee-name-box">
<label for="chScheduleLoc">Location: <span class="required">*</span></label>
<select class="form-control combobox location" name="chScheduleLoc" id="chScheduleLoc" required>
<option value selected="selected">---Select Location---</option>
</select>
</div>
<div class="combobox-container" id="employee-name-box">
<label for="chScheduleTier">Tier: <span class="required">*</span></label>
<select class="form-control combobox tier" name="chScheduleTier" id="chScheduleTier" required>
<option value selected="selected">---Select Tier---</option>
</select>
</div>
</div>
</div>
<!-- .page-box-content -->
</div>
<!-- .page-box -->
<script src="js/jquery-2.1.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-combobox.js"></script>
<script src="js/testJavascript.js"></script>
</body>
</html>
There is an AJAX call to a server which retrieves some data after the page has loaded and puts the data into a variable and is used to populate the comboboxes. There are multiple comboboxes that should contain the same information (eg. All comboboxes with class "location" should contain the same list of locations). I have simulated this in the following javascript file. Please note that the initialization of the comboboxes must happen first because I may need to update the contents of the associated <select> element after the combobox is initialized.
//file: js/testJavascript.js
var options = {
locations: "<option id='1'>London</option><option id='2'>Los Angeles</option><option id='3'>Sydney</option>",
tiers: "<option id='1'>Upper</option><option id='2'>Middle</option><option id='3'>Lower</option>"
}
$(document).ready(function(){
$('.combobox').combobox({
bsVersion: '3'
}); //This statement cannot be moved.
$('select.location').append(options.locations);
$('select.tier').append(options.tiers);
});
The Problem
The problem that I'm running into is after I append the options to the <select> elements, the comboboxes aren't updated to show the most recent information. I realize that if I call $('.combobox').combobox({...}); after options are added, the combobox will be correct. But I may need to update the information in the comboboxes after the comboboxes are initialized the first time.
The Question
How can I get the comboboxes to update after I add options to the corresponding <select> tag and after they have already been initialized?
After some more research and fiddling around, I found that the following code works to refresh the combobox. (using the issue shown here)
$('select.location').each(function(){ //need to run in .each to refresh all the elements
$(this).data('combobox').refresh();
});
$('select.tier').each(function(){
$(this).data('combobox').refresh();
});
Try to refresh your combobox using the following code :
$('select.location', 'select.tier').data('combobox','refresh');
Hope this helps.

How can I use the JQuery Validation Plugin to validate this form that have this specific constraint? [duplicate]

This question already has answers here:
jQuery Validate plugin, one out of two fields is required
(2 answers)
Closed 7 years ago.
I am pretty new in JQuery and I have the following problem related to a form validation.
So I think to not write the validator by myself but to use the JQuery Validation Plugin, this one: http://jqueryvalidation.org/
From what I have understand it provide me the built in required() method that make a specific field required (if the user don't insert a value for this field an error message is shown).
Ok...my problem is that in my form I have something like this:
<form method="post" action="consultazioneRicercaForm" id="consultazioneRicercaForm">
<div class="row">
<div class="col-md-4">
<label style="display: block;">Regioni:</label>
<select name="regioneSelezionata" id="selReg">
<option value="-">--SELEZIONARE UNA REGIONE--</option>
<option value="AB">ABRUZZO</option><option value="BA">BASILICATA</option><option value="CA">CAMPANIA</option><option value="CL">CALABRIA</option><option value="EE">REGIONE ESTERA</option><option value="EM">EMILIA ROMAGNA</option><option value="FR">FRIULI-VENEZIA GIULIA</option><option value="LA">LAZIO</option><option value="LI">LIGURIA</option><option value="LO">LOMBARDIA</option><option value="MA">MARCHE</option><option value="MO">MOLISE</option><option value="PI">PIEMONTE</option><option value="PU">PUGLIA</option><option value="SA">SARDEGNA</option><option value="SI">SICILIA</option><option value="TO">TOSCANA</option><option value="TR">TRENTINO-ALTO ADIGE</option><option value="UM">UMBRIA</option><option value="VA">VALLE D' AOSTA</option><option value="VE">VENETO</option>
</select>
</div>
<div class="col-md-4">
<label style="display: block;">Province:</label>
<select name="provinciaSelezionata" id="selProv"><option value="">--SELEZIONARE UNA PROVINCIA--</option></select>
</div>
<div class="col-md-4">
</div>
</div>
<div style="margin-top: 30px;" class="row">
<div class="col-md-4">
<label style="display: block;">Codice Meccanografico:</label>
<input type="text" value="" name="codMec" id="selCodMec">
</div>
<div class="col-md-4">
<label style="display: block;">Tipologia Progetto:</label>
<select name="tipologiaProgettoSelezionato" id="selTipologiaProgetto">
<option value="-">--TIPOLOGIA--</option>
<option value="WIFI">WIFI</option><option value="LIM">LIM</option><option value="Altro">Altro</option><option value="Classi 2.0">Classi 2.0</option><option value="Scuola 2.0">Scuola 2.0</option><option value="CSD">CSD</option>
</select>
</div>
<div class="col-md-4">
<label style="display: block;">Stato Progetto:</label>
<select name="statoProgettoSelezionato" id="selStatoProgetto">
<option value="-">--STATO PROGETTO--</option>
<option value="Da compilare">Da compilare</option><option value="In lavorazione">In lavorazione</option><option value="Da validare">Da validare</option><option value="Validato">Validato</option><option value="Rendicontato pregresso">Rendicontato pregresso</option>
</select>
</div>
</div>
<div style="margin-top: 30px;" class="row">
<div class="col-md-12">
<input type="submit" value="Cerca">
</div>
</div>
</form>
As you can see it contains some field of which those that have id="selReg" and id="selCodMec".
So my validation is focused only on the previous 2 fields and in particular the form can be considered valid if the field having id="selReg" OR the field having id="selCodMec" have a value setted. So if at least one of these 2 fields is valorized by the user my form is considered valid.
I think that in this case I can't use the required() method because it seems to me that the required() method is refered on a specific field and don't implement the previous logic.
How can I solve this problem? Can I use this JQuery Validation Plugin for my purpose?
Tnx
I use in one of my project the jQuery Validation as well.
Try to add a own validation rule:
$.validator.addMehtod('oneOrOther',function(value) {
if(!$("#selReg").val() && !$("#selCodMec").val())
return false;
else
return true;
});
Assign the validation to the field:
$("#consultazioneRicercaForm").validate({
...
rules: {
regioneSelezionata: {
oneOrOther: true
}
...
}
});
I hope, I understood your question correctly.

Bootstrap collapse with wrong behavior

My problem is that I have 2 blocks in modal and when I click on .emailInbound checkbox it toggle .in-serv-container open, but when I click on .accordion-heading to open comment part it makes .in-serv-container collapse.
What can be a reason?
HTML:
<label class="checkbox">
<input class="emailInbound" type="checkbox" onclick="toggleInServ(this)">Использовать Email для регистрации обращений
</label>
<div id='in-serv-container'>
<div><strong>Настройка входящей почты</strong></div>
<div>
<input class="emailOutserver" type="text" placeholder="Сервер входящей почты">
<input class="emailOutserverPort" type="text" placeholder="Порт">
</div>
<div>
<select class="emailOutProtocol half" style="width: 49%!important;">
<option value='usual'>Обычный</option>
<option value='ssl'>SSL</option>
</select>
<input class="emailInFolder half" type="text" placeholder="Папка входящей почты">
</div>
<div class="modal-body-container">
<input type="text" placeholder="Опции">
</div>
<button class="btn btn-link">Проверить подключение</button>
<hr>
</div>
<div class="accordion" id="comment-wrapper">
<div class="accordion-heading" data-toggle='collapse' data-target='#emailComment' onclick='toggleChevron(this)'>
<strong>Комментарий</strong> <i class='icon-chevron-right'></i>
</div>
<div id="emailComment" class="collapse" data-parent="#comment-wrapper">
<textarea class="emailComment"></textarea>
</div>
</div>
JS:
function toggleInServ(box){
var checked = $(box).prop('checked');
if(checked){
$('#in-serv-container').css('height', '170px');
}else{
$('#in-serv-container').css('height', '0px');
}
}
function toggleChevron(o){
var icon = $(o).children('[class*=icon]');
if(icon.hasClass('icon-chevron-right')){
icon.removeClass('icon-chevron-right');
icon.addClass('icon-chevron-down');
}else{
icon.removeClass('icon-chevron-down');
icon.addClass('icon-chevron-right');
}
}
If I'm in the right track at this, you want each dropdown to stay on opened if the checkbox is ticked? What ever is the case here, please provide us with your CSS-styling as well. Would be best if you'd give us JSFiddle of your case.
Changing just the
height
attribute of your CSS seems like a bad idea. Instead of that, you could try using
display: block;
and
display: none;
So it would really be a hidden field before it gets selected. Not the answer to the question itself, but just something to note.
It was because of 'bubbling'. I added e.stopPropoganation() and it help.

Categories