Bootstrap collapse with wrong behavior - javascript

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.

Related

How can I set some values using currentTarget with jQuery from different HTML elements?

Can anyone give me a hand with this?
I am trying to obtain different values depending which button is clicked and assign it into a variable.
A friend told me to add the values in an input to later by extracted by e.currentTarget but I was unable to make it work.
HTML:
<div class="curso-contenedor">
<div class="curso">
<input id="precio" value='12000' hidden>
<input id="cursoNombre" value='Web Developer' hidden>
<form><button class="btn-curso web-developer" id="webDeveloper">Agregar</button></form>
</div>
<div class="curso">
<input id="precio" value='13000' hidden>
<input id="cursoNombre" value='Marketing Digital' hidden>
<form><button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button></form>
</div>
</div>
jQuery:
$('.btn-curso').click(function(e){
let curso = {'precio': e.currentTarget('#precio'), 'curso': e.currentTarget('#cursoNombre')};
localStorage.setItem('datosCurso', JSON.stringify(curso));
e.preventDefault()
});
If anyone knows how to do this it would mean the world if you can help me since I have been trapped with this for days now trying different things.
Try this:
HTML
<div class="curso-contenedor">
<div class="curso">
<input name="precio" value='12000' hidden>
<input name="cursoNombre" value='Web Developer' hidden>
<button class="btn-curso web-developer" id="webDeveloper">Agregar</button>
</div>
<div class="curso">
<input name="precio" value='13000' hidden>
<input name="cursoNombre" value='Marketing Digital' hidden>
<button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button>
</div>
</div>
JQuery:
$('.curso-contenedor').on('click', '.curso', function(e){
let curso = {
'precio': $(e.currentTarget).find('input[name=precio]').val(),
'curso': $(e.currentTarget).find('input[name=cursoNombre]').val()
};
localStorage.setItem('datosCurso', JSON.stringify(curso));
e.preventDefault()
});
You should add delegate event listener to parent element
For more information: https://api.jquery.com/on/

Assigning unique models and ids to checkboxes within ng-repeat

I'm trying to understand data-binding with AngularJs and I'm working on a simple form that uses ng-repeat to render a set of accordions. The headings of each accordion has a status box that is red by default, yet when the accordion is expanded, checking the checkbox within should turn the status box green.
The problem I'm having is that when I check a checkbox, it turns the status box of each accordion heading green; not just the status box relevant to the checkbox.
I know I need to assign a unique model to each status box/checkbox but I'm unsure how. I've seen some examples with $index but I haven't been able to apply it to my problem.
The HTML is as follows:
<ul class="radio-accordion">
<li class="radio-accordion-item" ng-repeat="animal in ctrl.animalTypes">
<input id="input{{$index + 1}}" type="checkbox" name="input" />
<div class="radio-accordion-header grey">
<div class="radio-accordion-header-left">
<div class="radio-accordion-header-title-wrapper">
<span class="status-led {{ctrl.checkedStatus}}"></span>
<h1 class="radio-accordion-header-title text-blue">{{animal.name}}</h1>
</div>
</div>
<div class="radio-accordion-header-right"></div>
<label class="expander-blue" for="input{{$index + 1}}"></label>
</div>
<div class="radio-accordion-body white">
<div class="padd-10 marg-left40">
<div class="toolbar-flex marg-top-10 marg-bott0">
<input class="restyled"
id="input{{$index + 1}}"
name="input"
type="checkbox"
ng-model="ctrl.checkedStatus"
ng-change="ctrl.setConsent()"
ng-true-value="'green'"
ng-false-value="'red'" />
<label class="restyled-label"
for="input{{$index + 1}}"><em>I like this animal</em></label>
</div>
</div>
</div>
</li>
`
Any help appreciated!
EDIT: This is what I did in case it helps anyone in the future!
<ul class="radio-accordion">
<li class="radio-accordion-item" ng-repeat="animal in ctrl.animalTypes" ng-model="animal.checked>
<input id="input{{$index + 1}}" type="checkbox" name="input" />
<div class="radio-accordion-header grey">
<div class="radio-accordion-header-left">
<div class="radio-accordion-header-title-wrapper">
<span ng-class="{'status-led red': animal.checked == false, 'status-led green': animal.checked == true}"></span>
<h1 class="radio-accordion-header-title text-blue">{{animal.name}}</h1>
</div>
</div>
<div class="radio-accordion-header-right"></div>
<label class="expander-blue" for="input{{$index + 1}}"></label>
</div>
<div class="radio-accordion-body white">
<div class="padd-10 marg-left40">
<div class="toolbar-flex marg-top-10 marg-bott0">
<input class="restyled"
id="input{{$index + 1}}"
name="input"
type="checkbox"
ng-model="animal.checked"
ng-change="ctrl.isChecked(animal.checked)" />
<label class="restyled-label"
for="input{{$index + 1}}"><em>I like this animal</em></label>
</div>
</div>
</div>
</li></ul>
If you aren't concerned about adding additional properties to your animal objects , or if there already exists a property in those objects that would be used as checkbox indicator just use:
ng-model="animal.SomeProperty"
An alternate way is to use a separate object and use $index as each key:
ng-model="ctrl.checkedStatus[$index]"

Different way to generate divs via checkbox

Currently I am using the below method using JS to generate a block of text in a right column when a check box is clicked ticked in a left column.
This has been working fine, however each time I need to add a check box, I need to add a new class and new formContainer element. With the original 3 I had, wasn't a big deal. But now that I'm up to 10 and growing, getting a bit cumbersome.
What better possibilities exist to generate a div/block of text on a different part of the page as a result of a ticked check box?
Check Box
<input id="chk" data-detail="<br>Right 1" class="chkbox" type="checkbox" value="results" />1
Creating individual class
<div class="formContainer"></div>
Script
<script>
$('.chkbox').on('click',function(){
if($(this).is(':checked'))
{
$('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>');
}
else
{
$('.formContainer').html('');
}
});
</script>
If you are wanting them in columns you can generate them using bootstrap gridsystem.
<div class="formContainer>
<div class="container">
<div class="row">
<div class="col-m-4"></div>
<div class="col-m-4"></div>
<div class="col-m-4"></div>
</div>
<div class="row">
...
</div>
</div>
</div>
If you are wanting to keep them in the same column you could just use .append()
$('.formContainer').append('<div class="new">'+$(this).data('detail')+'</div>');
These can be used together to generate a fluid system or just the append can be used to keep adding divs to your formContainer
I would suggest appending a form after your checkbox using the Jquery function .after(newElement);
Play with it on codepen
Html:
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<style>
.formContainer{
height: 50px;
width: 100%;
background-color: gray;
}
</style>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
JQuery:
$(document).ready(function(){
$('.checkboxesThatAppends').click(function(){
var associatedFormId = $(this).attr('data-associated-form-id');
if(associatedFormId){
//if there is a form container associated with this checkbox already
//then let's remove that form.
//and remove the association from the checkbox
$('#'+associatedFormId).remove();
$(this).attr('data-associated-form-id', '');
}else{
//generate an Id for the new form to attach.
var newId = new Date().getTime();
$(this).attr('data-associated-form-id', newId);
$(this).parent().after('<div id="'+newId+'" class="formContainer"></div> ');
}
});
});
You can just use jQuery's append() and remove() methods in combination with wrapping HTML elements to achieve this effect.
JSFiddle: https://jsfiddle.net/xuc4tze0/1/
HTML
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 1" class="chkbox" type="checkbox" value="results" />1
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 2" class="chkbox" type="checkbox" value="results" />2
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 3" class="chkbox" type="checkbox" value="results" />3
</div>
</div>
CSS
.row {
display: flex;
width: 400px;
}
.left, .right {
flex: 0 0 50%;
}
Javascript / jQuery
$('.chkbox').on('click', function() {
if ($(this).is(':checked'))
// Find the row and add the 'right' column
$(this).closest('.row').append('<div class="right">' + $(this).data('detail') + '</div>');
} else {
// Find the 'right' column and remove it
$(this).closest('.row').find('.right').remove();
}
});
Depending on your need and the content of the divs I got a couple of suggestions :
Modal popups. If you these divs are just notifications then a popup would do (but doubt this is what you need).
List group, use bootstrap's neat class list group to show the needed info in an <ul> element, the JS that comes with these can be neat as well with special animations.
Use tooltips on each checkbox instead of getting a whole div appearing.
Last suggestion which I like least is putting all of your div's in a single container div on the right. Fix its width and height and set overflow attribute so you can scroll up and down the shown divs

jQuery show element beside currently selected button

Each of my radio buttons is inside a div, and immediately beside the input (radio) I have some text in a span with the CSS set to display:none. Since I have multiple radio buttons I'm trying set the span to show for ONLY the span beside the radio button that's selected. Thoughts?
Here's what I have currently.
$('input:checked').next().show();
Here's my fiddle for the full quiz I'm trying to build
http://jsfiddle.net/YSSWL/96/
Feel free to critique the rest of my jquery, as I'm likely over complicating something. I don't have a ton of experience with jquery or js (working on it).
Solution Edit: As Chausser pointed out I can use
$('input:checked').parent().find('span').show();
to select the span nearest the parent of the selected input and apply .show();
You can use:
$('input:checked').parent().find('span').show();
I updated your html to use some consistent classes and fixed your reset function as well. For working code check:
http://jsfiddle.net/YSSWL/106/
You can solve this completely with CSS:
.incorrect .incor { display: inline; }
http://jsfiddle.net/YSSWL/105/
Here is a better way to write this I think. A bit more flexible. Sorry I deleted a bunch of your stuff to make it clear what was going on.
JS:
$(document).ready(function () {
$(document).on('click', '#radiochk1', function(){
var checkedRadio = $('input[name="question1"]:checked');
$('.correct, .incorrect').removeClass('correct').removeClass('incorrect');
if(checkedRadio.hasClass('rightAnswer')){
checkedRadio.parent().find('span.answer').addClass('correct');
}else{
checkedRadio.parent().find('span.answer').addClass('incorrect');
}
});
$(document).on('click', '#resetq1', function(){
$('.correct, .incorrect').removeClass('correct').removeClass('incorrect');
$('input[name="question1"]').attr('checked', false);
});
});
HTML:
<form class="ra">
<div class="cor">
<input type="radio" name="question1" class="c1" />A. Choice A<span class="hiddencorr">Correct answer</span>
</div>
<div class="inc">
<input type="radio" name="question1" class="i1" />B. <span class="answer">Choice B</span>
</div>
<div class="inc">
<input type="radio" name="question1" class="i2 rightAnswer" />C. <span class="answer">Choice C</span>
</div>
<div class="inc">
<input type="radio" name="question1" class="i3" />D. <span class="answer">Choice D</span>
</div>
<div class="inc">
<input type="radio" name="question1" class="i4" />E. <span class="answer">Choice E</span>
</div>
</form>
<p class="rationale1"><b>Rationale:</b>
<br />
<br /><span class="rattext">Explanation of what was done wrong.</span>
</p>
<button id="radiochk1" class="checkhide">Check your answer</button>
<button id="resetq1" class="reset">Reset</button>

How to change the text of a <label> which is hidden

I want to change the text of a label whose parent has its display hidden. I am not able to access the label because of its parents visibility.
I would like to know is there a way to change the text of this label without the changing the visibility of the parent.
I tried changing the visibility of the label and changing the text and hiding it back, did not work.
$(document).ready(function(){
$("#394").find(".name").children("label").text("Home");
});
<div class="sample1" style="display: none;">
<div id="394">
<div class="name">
<label>house.jpg</label>
</div>
</div>
</div>
Any suggestions/ideas?
Answer:
First, Thank you all for the response.
I fixed the issue.
This is the change I made and it worked.
$(document).ready(function(){
$(".sample1").find(".name").children("label").text("Home");
});
<div class="sample1" style="display: block;">
<div style="display: none;" id="398">
<div class="name">
<label>Sample</label>
</div>
</div>
</div>
Sample
(Updated) http://jsfiddle.net/SXLnt/1/
(Old) http://jsfiddle.net/SXLnt/
Solution
$("#394 label").text("new_house.jpg");
$(".sample1").show(); // show hidden result
Sample HTML
<form id="parent_form" style="display: none; visibility: hidden;">
<label for="male" id="lb_male">Male</label>
<input type="radio" name="sex" id="male" />
<br />
<label for="female" id="lb_female">Female</label>
<input type="radio" name="sex" id="female" />
</form>
Sample JS (jQuery)
$("#lb_male").text("Man"); // Change text 1
$("#lb_female").text("Woman"); // Change text 2
//$("#parent_form").show(); // Show parent
Sample DOM result
IF the label's ID is lblSomething, you could do it in JQuery as so ...
$("lblSomething").val("Changed value")
Hope it helps.
If what you posted is your full code, it looks like you are missing a closing tag on your outer div. Try this:
<div class="sample1" style="display: none;">
<div id="394">
<div class="name">
<label>house.jpg</label>
</div>
</div>
</div>

Categories