Passing id to jquery function - javascript

I have a button and a hidden div.
Button:
<input
type="button"
id="myButton"
name="answer"
value="OPTIONS"
style=" margin-top: -30px; margin-bottom: 10px;float: right;background-color: #C80918;border: none;color: #ffffff"
onclick="showDiv()" />
Hidden div:
<div id="customDiv" style="display:none;" class="answer_list" > WELCOME</div>
I have included a function to hide/show the div:
$('#myButton').click(function() {
$('#customDiv').toggle('slow', function() {
// Animation complete.
});
});
The button and the div are included inside a PHP loop. There is an identifier for every loop, it is $row['id'].
Now, when the button is clicked, only the first item from the loop is showing its div, I would need to pass the id to the jquery function to identify which button/item is clicked.
How could I change my code to pass the id of every loop item to the jquery function?
EDIT
<?php
//output customizable
$customizable = $row["customizable"];
if ($customizable == 1){
$output .= '
<div class="col-md-3 col-sm-6 col-xs-6" style="margin-top:12px;">
<div class="item-content" >
<button type="button" style="float: right;background-color: Transparent;border: none;" data-toggle="modal" data-target="#modalPort"
data-id="'.$row["id"].'" ><img src="info.png" width=30
></button>
<div class="img-container">
<img src="../administrar/application/admin/productos/'.$row["image"].'" class="img-responsive" /><br />
<h4 class="text-info" style= "color:#666">'.$row["nombre"].'</h4>
<h4 class="text-info" style= "color:#000"><strong>'.$row["name"].'<strong></h4>
<h5 class="text-info" style= "color:#000">'.$row['descripcion'].'</h5>
<h4 class="text-danger" style= "color:#000">$ '.$row["price"] .'</h4>
<input
type="button"
id="myButton"
name="answer"
value="OPTIONS"
style=" margin-top: -30px; margin-bottom: 10px;float: right;background-color: #C80918;border: none;color: #ffffff"
onclick="showDiv()" />
<input style= " color:#000" type="text" name="comentarios" id="comentarios' . $row["id"] .'" placeholder="Special Instructions" class="form-control" value="" />
<br>
';
if($statement_opc->execute())
{
$numero_opciones = 0;
$result_opc = $statement_opc->fetchAll();
foreach($result_opc as $row_opc)
{
if ($row_opc['producto'] == $row['id']) {
$numero_opciones = $numero_opciones + 1;
$output .= '
<div class="checkbox">
<label><input type="checkbox" data-nombre="'. $row_opc["nombre"] .'"
data-precio="'. $row_opc["precio"] .'" id="opcion'.$row["id"].'" class="opcion_cbox"
data-rowid="'. $row["id"] .'" value="">'.$row_opc['nombre'].' (+ $'.$row_opc['precio'].')</label>
</div>
';
}
}
}
?>
//zona custom
<?php
$output .= '
<div id="customDiv" style="display:none;" class="answer_list" > WELCOME</div>
';
?>
//fin zona custom

You could connect each button to the respective div using their individual index (so the first button will toggle the first div, the second will toggle the second...)
var buttons = $("input[type='button']");
var answers = $(".answer-list");
buttons.each(function(index, dom) {
$(dom).on("click", function(e) {
$(answers[index]).toggle("slow");
});
});
body {
display: block;
height: 120px;
}
input[type="button"] {
background-color: #C80918;
margin-bottom: 10px;
/*margin-top: -30px;*/
color: #ffffff;
float: right;
border: none;
}
.answer-list {
display: none;
}
.answer-list.slow {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="OPTIONS 1" />
<input type="button" value="OPTIONS 2" />
<input type="button" value="OPTIONS 3" />
<div class="answer-list">WELCOME 1</div>
<div class="answer-list">WELCOME 2</div>
<div class="answer-list">WELCOME 3</div>
Or you could have unique ids for each div and just somehow store that id in a data attribute in the respective button.
$("input[type='button']").on("click", function(e) {
$($(e.target).data("target")).toggle("show");
});
body {
display: block;
height: 120px;
}
input[type="button"] {
background-color: #C80918;
margin-bottom: 10px;
/*margin-top: -30px;*/
color: #ffffff;
float: right;
border: none;
}
.answer-list {
display: none;
}
.answer-list.slow {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" data-target="#answer-list-1" value="OPTIONS 1" />
<input type="button" data-target="#answer-list-2" value="OPTIONS 2" />
<input type="button" data-target="#answer-list-3" value="OPTIONS 3" />
<div class="answer-list" id="answer-list-1">WELCOME 1</div>
<div class="answer-list" id="answer-list-2">WELCOME 2</div>
<div class="answer-list" id="answer-list-3">WELCOME 3</div>
But you should never use duplicate ids on the same page or duplicate names on the same form.

You can simply do this :
$('#myButton').click(function() {
$('#customDiv').each( function() {
$( this ).toggle('slow', function() {
// Animation complete.
});
});
});
But you may think to change id#customDiv to a class.customDiv.
It's not good let two or more elements with the same id.
EDIT
On button click :
var ids = [];
$( 'div.checkbox' ).find( 'input' ).each( function() {
var currentID = $( this ).data( 'rowid' );
// Some code, id verification or others
ids.push( currentID );
});
Now ids contains id of all checkbox.
Documentation :
https://api.jquery.com/find/
https://www.w3schools.com/jsref/jsref_push.asp
https://api.jquery.com/data/

Related

How can I delete the div that I created from the created divs?

function create() {
$("<div class='question container' id='question' style='background-color:lavender; border:solid 15px darkcyan; height:500px; border-radius:32px'><div class='input-group' style='margin-top:10px'><input type='text' placeholder='Soru Gir...' class='form-control'/> <button class='btn btn-danger' onclick='remove()' >Sil</button> <button class='btn btn-success' onclick='createSelection()'>Şık Ekle</button></div></div></br>").insertBefore("#btn")
}
function remove() {$("#question").remove()}
Is that what you want? There are many things about your code. Here is some:
Don't use recurring id attributes.
Listen event like my example. This also affects dynamically added elements.
$('body').on('click', '.btn-danger', function(e) {
$(this).closest('.question').remove();
});
$('body').on('click', '.btn-success', function(e) {
var $quest = $(this).closest('.question');
$quest.clone().insertAfter($quest);
});
.question {
background-color: lavender;
border: solid 15px darkcyan;
border-radius: 32px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="question container">
<div class="input-group" style="margin-top: 10px">
<input type="text" placeholder="Soru Gir..." class="form-control"/>
<button class="btn btn-danger">Sil</button>
<button class="btn btn-success">Şık Ekle</button>
</div></br>
</div>
function create() {
$("<div class='question container' style='background-color:lavender; border:solid 15px darkcyan; height:500px; border-radius:32px'><div class='input-group' style='margin-top:10px'><input type='text' placeholder='Soru Gir...' class='form-control'/> <button class='btn btn-danger' >Sil</button> <button class='btn btn-success' onclick='createSelection()'>Şık Ekle</button></div></div></br>").insertBefore("#btn");
}
$('body').on('click','.question .btn-danger', function(){
$(this).closest('.question').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<input type="button" id="btn" value="create" onclick="create();" />
Add this to your javascript code:
$('body').on('click','.question .btn-danger', function(){
$(this).closest('.question').remove();
});

Unable to make button show or hide depending on whether another element has content

So this is probably a simple question. But I have to ask because it's not doing what I want.
Here is the button JavaScript:
$(document).ready(function(){
if ($(".saved-items").html().length > 0) {
$('.btn-01').show();
}
});
The button is shown if there is content in the div. But I would like it to hide again if the div has no content.
I tried:
$(document).ready(function(){
if ($(".saved-items").html().length > 0) {
$('.btn-01').show();
}
if ($(".saved-items").html().length < 0) {
$('.btn-01').hide();
}
});
Here is the HTML when an item is added:
<div class="col-sm-2">
<div class="saved-items"><h4>Items:</h4>
<ul>
<li><i class="fa fa-anchor" aria-hidden="true" style="color:#f60;margin-right:10px;"></i>RAW</li>
</ul>
<script>
$(document).ready(function(){
$('.btn-01').toggle($(".saved-items").html().trim().length > 0);
});
</script>
</div>
</div>
<div class="col-sm-2">
<a class="fancybox my-subject" href="#contact-formulier" value="Item X"><div style="display: block;" class="btn-01">Check Out</div></a>
</div>
</div>
And this is the HTML without any items saved:
<div class="col-sm-2">
<div class="saved-items">
<h4>Items:</h4>
</div>
</div>
<div class="col-sm-2">
<a class="fancybox my-subject" href="#contact-formulier" value="Item X"><div class="btn-01">Check Out</div></a>
</div>
But no go. Here is the CSS of btn-01:
.btn-01 {
background: #f60;
color: #fff;
border-radius: 2px !important;
padding: 5px;
text-align: center;
margin: 40px auto 0px auto;
width: 90%;
display: none;
border:none;
}
You can use toggle() to achieve this:
$('.btn-01').toggle($(".saved-items").html().trim().length > 0);
Working example
length of string is zero or greater than zero..can't be less than zero.
$(document).ready(function(){
if ($(".saved-items").html().length > 0) {
$('.btn-01').show();
}else{
$('.btn-01').hide();
}
});
please check https://jsfiddle.net/Shilpi/uhfruo1a/2/

Travel to particular HTML element of active elements

I need help with jQuery (or JavaScript). I have a form with three checkbox alike elements. Want to get description text and input value for sending the data via AJAX form. Ajax is working quite good but I can not travel to the DOM to bring my desired data.
$('.select-item').on('click', function() {
$(this).toggleClass('active');
})
var activeItems = $('.select-item.active');
for( var i = 0, l = activeItems.length; i < l; i++ ) {
console.log( activeItems[i].children[1] );
console.log( activeItems[i].children[2] );
}
.select-item {
background-color: #f7f7f7;
margin-bottom: 20px;
padding: 15px;
}
.selector {
height: 20px;
width: 20px;
border: 1px solid blue;
position: relative;
}
.selector .circle {
height: 10px;
width: 10px;
background-color: blue;
position: absolute;
top: 5px;
left: 5px;
opacity: 0;
}
.active .selector .circle {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="ticket-booking-form-1">
<div class="select-item active">
<!-- SELECTION ITEM -->
<div class="selector">
<div class="circle"></div>
</div>
<div class="description">
<h4 class="title-text">Day 1 Full Day Ticket <span class="text-color">$129</span></h4>
</div>
<div class="select-input">
<label for="qty-1">QTY</label>
<input type="text" id="qty-1" name="qty-1" value="1" class="form-control">
</div>
</div>
<div class="select-item">
<!-- SELECTION ITEM -->
<div class="selector">
<div class="circle"></div>
</div>
<div class="description">
<h4 class="title-text">Day 1 Full Day Ticket <span class="text-color">$129</span></h4>
</div>
<div class="select-input">
<label for="qty-1">QTY</label>
<input type="text" id="qty-1" name="qty-1" value="1" class="form-control">
</div>
</div>
<div class="select-item">
<!-- SELECTION ITEM -->
<div class="selector">
<div class="circle"></div>
</div>
<div class="description">
<h4 class="title-text">Day 1 Full Day Ticket <span class="text-color">$129</span></h4>
</div>
<div class="select-input">
<label for="qty-1">QTY</label>
<input type="text" id="qty-1" name="qty-1" value="1" class="form-control">
</div>
</div>
<!-- /END SELECTION ITEM -->
<button type="submit" class="btn btn-base btn-lg"><span>Proceed to Checkout</span>
</button>
</form>
The scenario is, Description text and input value of selected (checked) elements should be added into an array or object then I can send single/both/all data of selected (active) elements. Actually I am not good at JS so if you think without adding into array or object solution could be achieved, Perfect!
http://jsfiddle.net/getanwar/t2d3sjmq/
Once you see the fiddle will understand my question.
To get the value of the active inputs use
for( var i = 0, l = activeItems.length; i < l; i++ ) {
console.log( activeItems[i].children[2].children[1].value );
}
With JQuery you can use something like
$('.select-item.active > .select-input').each( function(index,element){
console.log( $(this).find('input').attr('value') );
});

How to hide div when it's already open?

I couldn't think of any better title, so I will try to explain my question here as clear as possible. I'm quite a newbie in JQuery so this is probably a very easy question.
I have some divs with a button on it. When you click the button, another div should pop-up.
My question is: How can I make the div, which is already open, close when clicking on another button?
I made a fiddle with some example code: http://jsfiddle.net/zuvjx775/1/
And the example code here:
HTML:
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2"value='click!' />
</div>
<div class="show_2">
</div>
</div>
JQuery:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
$('.show_'+id).show();
});
When show_1 for example is visible, and I click on the button in div2, I want show_2 to come up, which it does, but show_1 to dissapear.
Can someone point me in the right direction?
You can hide all divs that their class starts with 'show' before show the one you want. For example:
$('.showDiv').on('click', function() {
var id = $(this).attr('id');
$("div[class^='show']").hide();//find div class starts with 'show' and hide them
$('.show_' + id).show();
});
.test {
border: 1px solid black;
height: 100px;
width: 450px;
float: left;
}
.show_1 {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
display: none;
}
.show_2 {
width: 50px;
height: 50px;
background-color: green;
float: left;
display: none;
}
.wrapper {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2" value='click!' />
</div>
<div class="show_2">
</div>
</div>
Is the structure of the document fixed?
is so... I guess the easiest way of doing this is to just do the following:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
if(id == 1){
$('.show_1').show();
$('.show_2').hide();
}else{
$('.show_2').show();
$('.show_1').hide();
}
})

Hide Previous div and toggle next div on click a button?

I have a number of buttons in my html. Each button referring to a particular DIV. I want an easy way to hide the previously open DIV when another button is clicked. So far I have written a code in jquery, but I have a strange feeling that am putting in a lot of code into a simply achievable task. Is there a simpler way to do this than what I have tried to accomplish?
Here is what I have done so far.
My HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
<meta name="viewport" content="width=device-width"/>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<div id="body">
<input type="button" name="division1" value="div1" class="buttons" id="button1"/>
<input type="button" name="division2" value="div2" class="buttons" id="button2"/>
<input type="button" name="division3" value="div3" class="buttons" id="button3"/>
<input type="button" name="division4" value="div4" class="buttons" id="button4"/>
<input type="button" name="division5" value="div5" class="buttons" id="button5"/>
<input type="button" name="division6" value="div6" class="buttons" id="button6"/>
<div id="div1" class="divs"></div>
<div id="div2" class="divs"></div>
<div id="div3" class="divs"></div>
<div id="div4" class="divs"></div>
<div id="div5" class="divs"></div>
<div id="div6" class="divs"></div>
</div>
</body>
</html>
My CSS:
#body{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: #000;
}
.buttons{
width: 10%;
height: 5%;
position: relative;
left: 10%;
cursor: pointer;
z-index: 500;
}
.divs{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: none;
}
#div1{
background-color: #377D9F;
}
#div2{
background-color: #02B0E6;
}
#div3{
background-color: #4b9500;
}
#div4{
background-color: #aaa;
}
#div5{
background-color:#aa0000;
}
#div6{
background-color: aquamarine;
}
My Jquery:
$(document).ready(function () {
$("#button1").click(function () {
$('#div1').toggle(100);
$("#div2,#div3,#div4,#div5,#div6").hide();
});
$("#button2").click(function () {
$("#div2").toggle(100);
$("#div1,#div3,#div4,#div5,#div6").hide();
});
$("#button3").click(function () {
$("#div3").toggle(100);
$("#div1,#div2,#div4,#div5,#div6").hide();
});
$("#button4").click(function () {
$("#div4").toggle(100);
$("#div1,#div2,#div3,#div5,#div6").hide();
});
$("#button5").click(function () {
$("#div5").toggle(100);
$("#div1,#div2,#div3,#div4,#div6").hide();
});
$("#button6").click(function () {
$("#div6").toggle(100);
$("#div1,#div2,#div3,#div4,#div5").hide();
});
});
I kind of have around 50 DIV's in my html like the above ones. And I think using the above JQUERY is a waste of coding lines. I know there will be a better way to do this. My code seems to work well, but is there any way in jquery to just hide the previous DIV, no matter which button user clicks?
$(document).ready(function(){
$(".buttons").click(function () {
var divname= this.value;
$("#"+divname).slideToggle().siblings('.divs').hide("slow");
});
});
Going with this sentence I kind of have around 50 DIV's in my html like the above ones
This would be a lot more clean as well as convenient if you use a select tag, instead of using button to show and hide each div
Demo
HTML
<select id="show_divs">
<option>Select to show a div</option>
<option value="1">Show 1</option>
<option value="2">Show 1</option>
</select>
<div class="parent">
<div id="show1">This is the first div</div>
<div id="show2">This is the second div</div>
</div>
jQuery
$('#show_divs').change(function() { //onChange execute the function
var showDiv = $(this).val(); //Store the value in the variable
$('div.parent > div').hide(); //Hide all the div nested inside .parent
$('#show' + showDiv ).show(); //Fetch the value of option tag, concatenate it with the id and show the relevant div
});
CSS
div.parent > div {
display: none; /* Hide initially */
}
If you want to avoid using id's, you can also create your custom attribute, like data-show="1" and data-show="2" so on...
Try this
$(document).ready(function() {
$(".divs").hide();
$(".buttons").click(function() {
$(".divs").hide().eq($(this).index()).show();
});
});
DEMO
<input type="button" value="div1" class="buttons" id="button1" />
<input type="button" value="div2" class="buttons" id="button2" />
<input type="button" value="div3" class="buttons" id="button3" />
<input type="button" value="div4" class="buttons" id="button4" />
<input type="button" value="div5" class="buttons" id="button5" />
<input type="button" value="div6" class="buttons" id="button6" />
<div id="div1" class="divs">div1</div>
<div id="div2" class="divs">div2</div>
<div id="div3" class="divs">div3</div>
<div id="div4" class="divs">div4</div>
<div id="div5" class="divs">div5</div>
<div id="div6" class="divs">div6</div>
<script language="javascript">
$(document).ready(function () {
$(".buttons").click(function () {
$('.divs').hide();
$('#div'+$(this).attr('id').replace('button','')).toggle(100);
})
})
</script>

Categories