Trying to find this on click and then toggle class? - javascript

I'm trying to toggle the class of this on click, I tried this but it doesn't seem to work. Any ideas? I have included some HTML now so that it is more easily understood what is going on.
$('.play-with-friends').on('click', function(){
$('.flipper', this).toggleClass('flipped');
});
HTML:
<div class="flipper">
<div class="row game-cards">
<div class="container col-lg-6">
<canvas id="game-circles"></canvas>
</div>
<div class="col-lg-6 game-info">
<h6 class="text-center">{{AwayTeam}} # {{HomeTeam}}</h6>
<p class="text-center">{{MatchTime}}</p>
<form>
<div class="form-group text-center">
<label for="home-team">{{HomeTeam}} -2.5</label>
<input type="number" class="form-control text-center" placeholder="Home Team Bet">
</div>
<div class="form-group text-center">
<label for="away-team">{{AwayTeam}}</label>
<input type="number" class="form-control text-center" placeholder="Away Team Bet">
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
<button type="button" class="btn btn-secondary btn-block play-with-friends">Play With Friends</button>
</form>
</div>
</div>
</div>

So please change your code to select .flipper:
$('.play-with-friends').on('click', function(){
$('.flipper').toggleClass('flipped');
});

When you do $('.some-class', elem) you're saying you want to target .some-class that's a child of elem. That's not what your HTML is showing – you actually have .flipper way above at the top level. How about using a different method, like closest, which will find an ancestor with the selector you specify:
$('.play-with-friends').on('click', function() {
$(this).closest('.flipper').toggleClass('flipped');
});

Related

Manipulating the DOM of a collection of divs using Jquery

Am working on the frontend part of an application whereby I have
some form inputs (wrapped in divs). Each div has a button called
Add Beneficiary. Basically when the user clicks on the button, the div
below it should be displayed (which is hidden by default) and the
sequence continues (each button on a div clicked the div below it
displays).
On the button of each div I have writen some logic whereby on click event
a function called addBeneficiary is triggered. I parse the id of the
button clicked. Next in the function I manipulate the DOM by reaching
out to the parent div and displaying it but the logic does not
work.
~ Kindly assist?
Markup
<!--Person One-->
<div class="container mg-t-30" id="beneficiary1">
<div class="row col-11 mx-auto">
<div class="col-12">
<div class="row">
<div class="col-6">
<label> Category</label>
<input type="email" class="form-control" placeholder="Enter email">
</div>
<div class="col-6">
<label>Family Size</label>
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<div class="row">
<div class="col-12">
<button class="float-right btn btn-primary" id="btnBen1" onclick="addBeneficiary(this.id)">Add Beneficiary</button>
</div>
</div>
</div>
</div>
</div>
<!--Person Two-->
<div class="container mg-t-30" style="display:none;" id="beneficiary1">
<div class="row col-11 mx-auto">
<div class="col-12">
<div class="row">
<div class="col-6">
<label> Category</label>
<input type="email" class="form-control" placeholder="Enter email">
</div>
<div class="col-6">
<label>Family Size</label>
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<div class="row">
<div class="col-12">
<button class="float-right btn btn-primary" id="btnBen1" onclick="addBeneficiary(this.id)">Add Beneficiary</button>
</div>
</div>
</div>
</div>
</div>
Logic
function addBeneficiary(beneficiary){
let check = $('#' + beneficiary).parents('div').last().prop('id');
//console.log(check);
$("check").css("display", "block");
}
Its not working because both parents div id is "beneficiary1". And you can't use same id with multiple tag. It should be unique like beneficiary1, beneficiary2 & so on... And also little bit change into your script.
function addBeneficiary(beneficiary){
let check = $('#' + beneficiary).parents('div').next('div');
//console.log(check);
check.css("display", "block");
}
jsfiddle https://jsfiddle.net/y2mva6es/

Displaying closest div based on different factors

I have different file inputs I want displayed once the previous one has been selected. At the moment I have
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<div class="input-group inputMargBtm">
<input type="text" class="form-control" id="fileOneContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileOne" name="fileOne" class="fileGroup" accept=".jpeg,.jpg">
</span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<div class="filePadd">
<div class="input-group">
<div id="hideDivTwo" class="hiddenDiv">
<input type="text" class="form-control" id="fileTwoContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileTwo" name="fileTwo" class="fileGroup" accept=".jpeg,.jpg" disabled="true">
</span>
</span>
</div>
</div>
</div>
</div>
</div>
But I also have a lot more hidden rows for up to 10 inputs. So I dont need to create new code for each input within my Javascript, I am trying to display things dynamically. Essentially, if I select a file, it should display the next file input.
At the moment I have this
$(".fileGroup").on('change',function(){
var id = $(this).attr('id');
if (id.length) {
$(this).parents('.row').nextSibling('.row').child('.hiddenDiv').css("display", "table-footer-group");
}
});
So I get the id of the changed fileGroup. I then attempt to get its parents row, then get the next row, and display its hidden div. At the moment this does not seem to work. What would be the best way to display the next input block?
Thanks
Try with this code:
$(".fileGroup").on('change',function(){
var $next_element = $(this).parents('.row').next('.row').find('input[type="file"]');
if ($next_element.length) {
$next_element.prop('disabled', false);
}
});
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<div class="input-group inputMargBtm">
<input type="text" class="form-control" id="fileOneContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileOne" name="fileOne" class="fileGroup" accept=".jpeg,.jpg">
</span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<div class="filePadd">
<div class="input-group">
<div id="hideDivTwo" class="hiddenDiv">
<input type="text" class="form-control" id="fileTwoContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileTwo" name="fileTwo" class="fileGroup" accept=".jpeg,.jpg" disabled="true">
</span>
</span>
</div>
</div>
</div>
</div>
</div>
The code is rather simple:
1. grab .row parent
2. look for the next element with .row class
3. find an file input in the next .row element
4. if the input exists, set its disabled attribute to
false

JavaScript Get the closest element and input a value to the input

I have a piece of HTML that looks like this
<div id="imageContent">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="input-group form-group">
<input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source">
<span class="input-group-btn">
<button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button>
</span>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input class="form-control" type="text" placeholder="http://postbackurl.com"/>
</div>
</div>
</div>
</div>
Above that I have a button that looks like this
<div class="row text-center">
<div class="col-md-12">
<button type="button" class="btn btn-wd btn-info btn-fill btn" onclick="add_fields();" rel="tooltip">Add More Images</button>
</div>
</div>
Once that button is pressed I run a function to get the #imageContent div and append a new row with the same as before.
<script type="text/javascript">
function add_fields() {
var div = document.getElementById("imageContent");
div.insertAdjacentHTML('afterend','<div class="row"><div class="col-md-5 col-md-offset-1"> <div class="input-group form-group"><input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source"><span class="input-group-btn"> <button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button> </span> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" type="text" placeholder="http://postbackurl.com"/> </div> </div> </div>');
}
</script>
This works as expected and adds a new row into the imageContent div.
See picture. If I click Select Image, it launches a modal window with all of my images, and when I select one, it runs this piece of js.
onInsertCallback: function (obj){
/** Populate the src **/
currentModalBtn.closest('.input-group').find('input.file-src').val(obj.src);
$('#myModal').hide();
}
The problem I am having is that it does not get the correct input area to insert the value into, and instead always updates the first element. The full js code looks like this.
$(document).ready(function() {
jQuery(document).ready(function() {
/** Keep track of which modal button was clicked. **/
var currentModalBtn;
jQuery('.modal-btn').click(function() {
currentModalBtn = jQuery(this);
});
jQuery('.laradrop').laradrop({
onInsertCallback: function(obj) {
/** Populate the src **/
currentModalBtn.closest('.input-group').find('input.file-src').val(obj.src);
$('#myModal').hide();
},
onErrorCallback: function(jqXHR, textStatus, errorThrown) {
// if you need an error status indicator, implement here
//Swal here
swal({
title: 'Error!',
text: 'An Error Occurred',
type: 'error',
showConfirmButton: false,
showCancelButton: true
});
},
onSuccessCallback: function(serverData) {
//
}
});
});
});
My question is, how can I ensure that I get the right input field that the button was clicked on to update that fields value and make sure the others stay as they were.
move var currentModalBtn; outside the ready so it is available to the callback(s)
Also have only one
$(document).ready(function() {
jQuery(document).ready(function() {
you have a mess of jQuery/$ and so on - this will likely work better:
function add_fields() {
var $div = $("#imageContent");
$div.append('<div class="row"><div class="col-md-5 col-md-offset-1"> <div class="input-group form-group"><input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source"><span class="input-group-btn"> <button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button> </span> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" type="text" placeholder="http://postbackurl.com"/> </div> </div> </div>');
}
var currentModalBtn;
$(function() {
/** Keep track of which modal button was clicked. **/
$("#imageContent").on("click",".modal-btn", function() {
currentModalBtn = $(this);
});
$("#test").on("click",function() {
currentModalBtn.closest('.input-group').find('input.file-src').val("hello");
$('#myModal').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row text-center">
<div class="col-md-12">
<button type="button" class="btn btn-wd btn-info btn-fill btn" onclick="add_fields();" rel="tooltip">Add More Images</button>
</div>
</div>
<div id="imageContent">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="input-group form-group">
<input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source">
<span class="input-group-btn">
<button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button>
</span>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input class="form-control" type="text" placeholder="http://postbackurl.com"/>
</div>
</div>
</div>
</div>
<button type="button" id="test">
click
</button>

Closing Dynamically created DIV

So I have a section to add a color and I got it to dynamically create a copy of the div with a new ID for each dynamic div.
The problem is that once the div is created, I don't know how to close it (i.e. remove it from DOM via a "close" action). I know it's because it's dynamic content. You cant bind event likes the static content, it's will not bind to the elements because they don't appear at the time you bind. I just don't know how to go about getting it to close.
The div I want to close starts with "Color" + incremented number. I hope I explained this correctly and any help would be appreciated. Thanks.
<div class="col-xs-12" style="max-width: 800px">
<div class="col-md-12">
<h3>COLOR ROTATION</h3>
<!--Begin color rotation well-->
<div id="color">
<div class="well well-sm">
<div class="row">
<div class="col-md-6">
<div class="form-group"><a><span class="glyphicon glyphicon-remove-sign" aria-hidden="true" style="padding-right: 2px;"></span></a>
<label class="control-label">Color 1</label>
<input class="form-control" maxlength="100" placeholder="Enter Color" required="required" type="text" />
</div>
</div>
<div class="col-md-6">
<label class="control-label">DROPDOWNS REQUIRED?</label>
<div class="form-inline">
<div class="radio">
<label>
<input name="optradio" type="radio" />Yes</label>
</div>
<div class="radio">
<label>
<input name="optradio" type="radio" />No</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End color rotation well-->
</div>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span><a id="addcolor">Add Color</a>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
Here's the link to the working example:
jsfiddle
Sure, see this updated fiddle;
Essentially you want to bind an event to the document using .on(), like:
$(document).on('click', '.remove', function(e){
$(this).closest('.color-wap').remove();
});
I added the .color-wrap class to the #color div to avoid working with duplicated ID's via cloning, and added the .remove class to the remove button
1)Use the .on() to bind events on dynamically created elements
2)jquery selector ^ can help in selecting the div with id of color-number.
3).animate() to toggle height of the div or .remove if you want to completly remove the element.
$(function() {
var count = 0;
$('#addcolor').click(function() {
count++;
var clonediv = $('#color');
$(clonediv).clone().insertBefore('#color');
$(clonediv).attr("id", "color" + count);
});
$(document).on("click", ".glyphicon-remove-sign", function() {
$(this).closest("div[id^='color']").animate({"height":"toggle"});
//$(this).closest("div[id^='color']").remove();
})
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12" style="max-width: 800px">
<div class="col-md-12" id="test">
<h3>COLOR ROTATION</h3>
<!--Begin color rotation well-->
<div id="color">
<div class="well well-sm">
<div class="row">
<div class="col-md-6">
<div class="form-group"><a><span class="glyphicon glyphicon-remove-sign" aria-hidden="true" style="padding-right: 2px;"></span></a>
<label class="control-label">Color 1</label>
<input class="form-control" maxlength="100" placeholder="Enter Color" required="required" type="text" />
</div>
</div>
<div class="col-md-6">
<label class="control-label">DROPDOWNS REQUIRED?</label>
<div class="form-inline">
<div class="radio">
<label>
<input name="optradio" type="radio" />Yes</label>
</div>
<div class="radio">
<label>
<input name="optradio" type="radio" />No</label>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End color rotation well-->
</div>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span><a id="addcolor">Add Color</a>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>

Add/Remove button not working on duplicated form fields - jquery

I have used the code from the following answer: jquery clone form fields and increment id to created a clone-able area of my form and all is working well except for the "Add another" and "Remove row" button.
Only the original clone-able areas Add / Remove buttons work so the next cloned area's add / remove buttons don't do anything meaning you have use the first row's which is confusing.
I really can't see what is going on. Any help would be greatly appreciated!
The HTML:
<div id="previous-jobs">
<div class="panel-group" id="accordion">
<div id="clonedInput1" class="clonedInput panel panel-default">
<div class="panel-heading clearfix">
<h4 class="panel-title pull-left">
<a class="heading-reference accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapse1">
Entry #1
</a>
</h4>
<div id="action-buttons" class="pull-right">
<button type="button" class="btn btn-success clone">Add another</button>
<button type="button" class="btn btn-danger remove">Delete Row</button>
</div>
</div>
<div id="collapse1" class="input-panel panel-collapse collapse">
<div class="panel-body">
<div class="row">
<div class="form-group col-sm-6">
<label class="p-date-from-title input-title" for="p-date-from">Date From</label>
<input type="text" class="ci-df form-control" id="p-date-from1" name="p-date-from" value="[[+!fi.p-date-from]]" placeholder="Date from">
</div>
<div class="form-group col-sm-6">
<label class="p-date-to-title input-title" for="p-date-to">Date To</label>
<input type="text" class="ci-dt form-control" id="p-date-to1" name="p-date-to" value="[[+!fi.p-date-to]]" placeholder="Date to">
</div>
</div>
<div class="form-group">
<label class="p-employer-title input-title" for="p-employer">Employer</label>
<input type="text" class="ci-em form-control" id="p-employer1" name="p-employer" value="[[+!fi.p-employer]]" placeholder="Employer">
</div>
<div class="form-group">
<label class="p-position-title input-title" for="p-position">Position</label>
<input type="text" class="ci-po form-control" id="p-position1" name="p-position" value="[[+!fi.p-position]]" placeholder="Position">
</div>
<div class="form-group">
<label class="p-salary-title input-title" for="p-salary">Salary</label>
<input type="text" class="ci-sa form-control" id="p-salary1" name="p-salary" value="[[+!fi.p-salary]]" placeholder="Salary">
</div>
<div class="form-group">
<label class="p-full-part-time-title input-title" for="p-full-part-time">Full/Part Time</label>
<select class="ci-fpt form-control" id="p-full-part-time1" name="p-full-part-time" value="[[+!fi.p-full-part-time]]">
<option value="Full Time">Full Time</option>
<option value="Part Time">Part Time</option>
</select>
</div>
<div class="form-group">
<label class="p-leaving-reason-title input-title" for="p-leaving-reason">Reason for Leaving</label>
<input type="text" class="ci-rfl form-control" id="p-leaving-reason1" name="p-leaving-reason" value="[[+!fi.p-leaving-reason]]" placeholder="Reason for leaving">
</div>
</div>
</div>
</div>
</div>
The jQuery:
var regex = /^(.*)(\d)+$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").click(function(){
cloneIndex++;
$(this).parents(".clonedInput").clone()
.appendTo("#accordion")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
this.name = match[1] + (cloneIndex);
}
$(this).find('.heading-reference').attr("href", "#collapse" + cloneIndex).html('Entry #' + cloneIndex);
});
});
$("button.remove").click(function(){
$(this).parents(".clonedInput").remove();
});
For dynamically added elements, use .on() jQuery documentation .on() (For jQuery 1.7 and above)
In the example you posted, they used .live() which is for jQuery 1.7 and below.
Add this outside of any $(document).ready() function:
$(document).on('click', 'button.clone', function(){
...
});
By doing this, the event handler gets added to the document so any time an event bubbles up to it that originated from a button.clone element, it will trigger that function. So when buttons get added after the page is loaded, they will still trigger the click event, even when they weren't available when the page initially loaded.
If you just use $('button.clone').click(...) only the buttons that are on the page when it is first loaded will trigger the click event.

Categories