I currently have a code that shows a DIV based on two checkboxes. Currently, you can select both checkboxes and both DIVs will show. I do not want this to occur. How can I make it so you select both checkboxes it shows another DIV?
In summary, one checkbox shows one DIV, another checkbox shows another, both will show something completely else.
<input type="checkbox" name="checkbox_insert"
id="checkbox_insert" value="insert">Insert<br>
<input type="checkbox" name="checkbox_update"
id="checkbox_update" value="update">Update</p>
<script type="text/javascript">
$('#checkbox_insert').change(function() {
$('#insert_div').toggle();
});
$('#checkbox_update').change(function() {
$('#update_div').toggle();
});
</script>
<div id="insert_div" style="display:none">
INSERT
</div>
<div id="update_div" style="display:none">
UPDATE
</div>
<div id="both_div" style="display:none">
BOTH
</div>
var $i = $('#checkbox_insert, #checkbox_update'),
$d = $('div'),
$b = $d.filter('#both_div');
$i.change(function () {
$b.toggle($i.filter(':checked').length === $i.length);
$d.filter('#' + this.value + '_div').toggle(this.checked);
});
http://jsfiddle.net/EeJXy/
You'll want something like this (using jQuery):
EDIT Updated booleans in toggle() (working example here http://jsfiddle.net/uYUK2/):
$('input[type="checkbox"]').on('change', function() {
var inserted = $('#checkbox_insert').prop('checked');
var updated = $('#checkbox_update').prop('checked');
$('#both_div').toggle(inserted && updated);
$('#insert_div').toggle(inserted && !updated);
$('#update_div').toggle(updated && !inserted);
});
Related
I have a form in which i have two checkboxes (Checkbox 1 and Checkbox 2).
Now, what i want is:
1.) If only Checkbox 1 is selected while adding the details then in edit mode only Checkbox 1 should be selected. (which is happening)
2.) If only Checkbox 2 is selected while adding the details then in edit mode only Checkbox 2 should be selected. (which is happening)
3.) If both of them were selected while adding the details then in edit mode both Checkboxes should be selected. (which is not happening)
If someone can point me in the right direction or point my mistake that would be really great.
I have already checked many solutions for this here but none of them works for me or you can point me towards the link which i may have missed.
I will add my jquery function as well as how i am storing them in database in comma separated way.
Checkboxes:-
<div class = "error_placement_checkbox">
<div align = "center" class="ui inverted form" id = "idcheckbox">
<div align = "center" class=" inline required fields">
<label> Checkboxes </label>
<div class="field">
<div class="ui checkbox">
<input type = "checkbox" name = "p_act1" value = "Checkbox_1" >
<label> Checkbox 1 </label>
</div>
</div>
<div class="field">
<div class="ui checkbox">
<input type = "checkbox" name = "p_act2" value = "Checkbox_2" >
<label> Checkbox 2 </label>
</div>
</div>
</div>
</div>
</div>
My jquery function:-
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
if ($(this).val() == "<c:out value = '${product.p_act}' />")
($(this).prop('checked' , true));
});
});
</script>
In my Controller Servlet:- // To store them in comma separated.
List<String> items = new ArrayList<>();
if (request.getParameter("p_act1") != null) { items.add (request.getParameter("p_act1")); }
if (request.getParameter("p_act2") != null) { items.add (request.getParameter("p_act2")); }
String p_act = String.join(" , ", items);
Edit:-
This is my whole jquery function
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
// console.log(this.value);
if ("<c:out value = '${product.p_act}' />".split(",").includes($(this).val()))
($(this).prop('checked' , true));
// console.log(this.value);
});
});
</script>
edit2:-
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="checkbox"]').each(function(index)
{
console.log(this.value);
if ("11,22".split(",").includes($(this).val()))
($(this).prop('checked' , true));
console.log(this.value);
});
});
</script>
in console:-
(index):269 Checkbox_1
(index):272 Checkbox_1
(index):269 Checkbox_2
(index):272 Checkbox_2
When debugging js/jquery, always use rendered code - you'll see that you have something like:
if ($(this).val() == "123,456")
At no point, does either of your checkboxes have the value of "123,456"
So the if never works if you have both ticked as it's comparing a single value with a combined string. You could compare by using split and checking with includes:
if ("123,456".split(",").includes($(this).val())
So your code would be:
if ("<c:out value = '${product.p_act}' />".split(",").includes($(this).val())
Or you could pass them to the js as an array instead of multiple join/split.
I am working on a attendance module and this is the prototype of the code, but I have some errors.
As you can see there are dynamically generated buttons and they change colour on click event. I am also storing the value of the buttons in textboxes on click as I have to handle this data on backend with PhP, the error is that when I turn a button to green it's value goes into a textbox and when again i turn it red same value goes into another textbox also, which I don't want. So please help me in solving this problem by reducing the duplicacy of data or by providing a code of a different submit button which when clicked checks the color of all the buttons and stores the values in different textboxes respectively, one for red and one for green. Thanks in advance.
<html>
<head>
<title>Button click event</title>
</head>
<body>
<?php
for($i=0;$i<=10;$i++) {
?>
<button class="btnColorChange" id="<?php echo $i; ?>" style="background-color:#FF0000"><?php echo $i; ?></button>
<?php
}
?>
<div>
<input type="text" name="text1" id="textbox1" value=""/><br><br>
<input type="text" name="text2" id="textbox2" value=""/><br><br>
</div>
<script>
$(".btnColorChange").click(function(){
xyz = this.id
if(this.clicked){
$(this).css('background-color', '#FF0000');
const tb=document.querySelector("#textbox1");
tb.value=tb.value+","+xyz;
console.log(xyz)
this.clicked = false;
} else {
$(this).css('background-color', '#008000');
const tb2=document.querySelector("#textbox2");
tb2.value=tb2.value+","+xyz;
console.log(xyz)
this.clicked = true;
}
});
</script>
</body>
</html>
First, the below statement is wrong:
there are dynamically generated buttons...
When talking about "dynamic" elements, we talk about element that were not existing on page load. It's not the case here, since they were created before page load, on the server-side. Using a loop does not make them "dynamic".
To store clicked/unclicked ids, I suggest you to use some arrays for this.
As I understand it, you want all the "clicked" and "unclicked" ids separately.
The "never clicked" are ignored.
Using two arrays, you can store ids in the relevant group... And even sort them (optionnally).
And you can send those arrays straight to your backend... So the input elements would now be just for testing purposes.
See comments in code:
// Arrays to store ids
var clicked = [],
unclicked = [];
$(".btnColorChange").on("click",function(){
// useful for this demo
console.clear();
// Get the clicked element id
var this_id = this.id;
console.log("Clicked id: "+this_id);
// Toggle the classes (button colors)
$(this).toggleClass("clicked unclicked");
// Check if in array
var in_clicked = $.inArray(this_id,clicked);
var in_unclicked = $.inArray(this_id,unclicked);
//console.log(in_clicked+" "+in_unclicked)
// If clicked
if($(this).hasClass("clicked")){
if(in_clicked==-1){
clicked.push(this_id);
clicked.sort();
}
if(in_unclicked>-1){
unclicked.splice(in_unclicked,1);
}
}
// If unclicked
if($(this).hasClass("unclicked")){
if(in_unclicked==-1){
unclicked.push(this_id);
unclicked.sort();
}
if(in_clicked>-1){
clicked.splice(in_clicked,1);
}
}
// Show arrays content in console
console.log(clicked);
console.log(unclicked);
// Show the ids in inputs as a coma separated string
$("#textbox1").val(clicked.join(","));
$("#textbox2").val(unclicked.join(","));
});
.unclicked{
background-color: #FF0000;
}
.clicked{
background-color: #008000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btnColorChange unclicked" id="1">1</button>
<button class="btnColorChange unclicked" id="2">2</button>
<button class="btnColorChange unclicked" id="3">3</button>
<button class="btnColorChange unclicked" id="4">4</button>
<button class="btnColorChange unclicked" id="5">5</button>
<br>
<br>
<div>
<input type="text" name="text1" id="textbox1" value=""/><br><br>
<input type="text" name="text2" id="textbox2" value=""/><br><br>
</div>
Please run the snippet in full page mode, because of the console logs.
For more reading, the below demo uses the following methods:
.on()
.toggleClass()
$.inArray()
.hasClass()
.push()
.sort()
.splice
.val()
.join()
You certainly noticed that I used two CSS rules for the button colors, instead of inline style attributes.
CodePen
If i understood you well, you want for example the Button to handle updates of textbox1 on first click and update textbox2 on second click. You could do this.
$(".btnColorChange").on("click", function(){
var btn = $(this);
var id = btn.attr("id");
if(btn.hasClass('clicked')){
var textboxselected = $("#textbox1");
var backgroundColor = "#FF0000";
btn.removeClass('clicked');
}else{
var textboxselected = $("#textbox2");
var backgroundColor = "#008000";
btn.addClass('clicked');
}
btn.css("background-color", backgroundColor);
textboxselected.val(textboxselected.val()+id);
});
Suppose you want to update same textbox
$(".btnColorChange").on("click", function(){
var btn = $(this);
var id = btn.attr("id");
var textvalue = $("#textbox1").val();
if(btn.hasClass('clicked')){
var backgroundColor = "#FF0000";
btn.removeClass('clicked');
}else{
var backgroundColor = "#008000";
btn.addClass('clicked');
}
btn.css("background-color", backgroundColor);
$("#textbox1").val(textvalue);
});
Its untested but hopes it works for you.
I have multiple forms on a page and also multiple input boxes with plus/minus signs.
I'm having trouble to get those input boxes to work seperately. Probably because of some wrong/same id's or something like that or maybe a wrong setup of my code. The thing is I can't find my error in the code and I don't get any errors in my console.
What I have:
function quantity_change(way, id){
quantity = $('#product_amount_'+id).val();
if(way=='up'){
quantity++;
} else {
quantity--;
}
if(quantity<1){
quantity = 1;
}
if(quantity>10){
quantity = 10;
}
$('#product_amount_'+id).val(quantity);
}
And my html:
//row 1
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_1234"/></div>
<div class="change" data-id="1234">
+
-
</div>
//row 2
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_4321"/></div>
<div class="change" data-id="4321">
+
-
</div>
I thought something like this would do the trick but it doesn't :(
$(document).ready(function(){
$('.change a').click(function(){
var id = $(this).find('.change').data('id');
quantity_change(id)
});
});
Any help greatly appreciated!
You should use closest() method to get access to the parent div with class change, then you can read the data attribute id's value.
var id = $(this).closest('.change').data('id');
alert(id);
Since you are already binding the click event using unobutrusive javascript, you do not need the onclick code in your HTML markup.
Also your quantity_change method takes 2 parameters and using both, but you are passing only one. You may keep the value of way in HTML 5 data attributes on the anchor tag and read from that and pass that to your method.
<div class="change" data-id="1234">
+
-
</div>
So the corrected js code is
$(document).ready(function(){
$('.change a').click(function(e){
e.preventDefault();
var _this=$(this);
var id = _this.closest('.change').data('id');
var way= _this.data("way");
quantity_change(way,id)
});
});
Here is a working sample.
Hi all I am struggling to achieve my my goal and I really need some help.
I have a list of single check boxes that I need to be able to get the values and be able to put them in to a list
So for example 3 check boxes on the screen there could be more, the user clicks on one one or all of the them, and I want to be able to output the following:
<ul>
<li>Checkbox1 Value</li>
<li>Checkbox2 Value</li>
<li>Checkbox13Value</li>
</ul>
I also need to be able to save the selected values to a hiiden field as well like this if possible:
Checkbox1 Value | Checkbox2 Value | Checkbox3 Value
There will be 2 sections on the page with where I will need this functionality so I assume I will be looking into the div tags that contain the check boxes.
I have found some code but I get it to do what I need
function updateTextArea() {
var allVals = [];
$('#c_b :checked').each(function() {
allVals.push($(this).val());
});
$('#EXCUR').val(allVals)
$('#t').val(allVals)
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
My HTML will be like this:
<div id="c_b">
<div>
<input type="checkbox" value="one_name">
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<div id="c_G">
<div>
<input type="checkbox" value="one_name" checked>
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<textarea id="t"></textarea> <!-- UL LIST SHOULD GO HERE -->
<input type="hidden" id="EXCUR" />
<div id="OP"></div>
Any help with this would be great, I just cant get it to work
Many thanks in advance
Jason
Here is a fiddle of what I think you're looking for but if you answer my comment above I'll be able to help you further.
You can use jQuery's map() to extract the values you want into an array and then join the items in the array however you want.
Something like this:
function updateTextArea() {
var items = $.map($('#c_b :checked'),function(el, ix) {
return 'Checkbox' + (ix+1) + ' ' + $(el).val();
});
if(items.length > 0) {
$('#t').val('<ul><li>' + items.join('</li><li>') + '</li></ul>');
$('#EXCUR').val(items.join(' | '))
} else {
$('#t').val('');
$('#EXCUR').val('');
}
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
Fiddle to demonstrate
function updateTextArea(){
var vals = []
var str="<ul>";
//iterate over checked boxes
$("input:checked").each(function(){
var v = $(this).val()
vals.push(v)
str += "<li>" + v + "</li>"
})
str+="</ul>"
$("#EXCUR").val(vals.join("|"));
$("#t").val(str);
}
$(function(){
//bind click to all checkboxes in the page
$(":checkbox").click(updateTextArea);
})
why after two click this code adding several input together?
$('.add_input').live('click', function () {
var scntDiv = '.'+$(this).closest('div.find_input').find('div').attr('class');
var i = $('.adding').size();
var input = $(scntDiv).clone().wrap("<div>").parent().html();
alert(scntDiv)
$(scntDiv + ' .add_input').remove();
$(input).appendTo(scntDiv);
$('<div></div>').appendTo('.add_in');
$(scntDiv + ' .add_in div a:first').remove('')
i++;
return false;
});
html: (i use of this html twice)
<div class="column find_input">
<div class="ai_service">
<div class="column">
<div class="mediumCell">
<input type="text" name="name" style="width: 160px;" placeholder="خدمات دیگر" title="نام پکیج تور خارجی">
</div>
</div>
<div class="column" style="margin: 5px 3px;">
<div class="mediumCell add_in">
</div>
</div>
</div>
</div>
Hmm if you're just trying to add an extra input field, your code seems a little overcomplicated for that... Try this?
$('a.add_input').live('click', function(e) {
e.preventDefault();
var $this = $(this);
var $wrapper = $this.closest('div.find_input');
var $input = $wrapper.find('input[name=name]').eq(0).clone();
$wrapper.children('div').eq(0).append($input);
};
I didn't replicate everything from your code, just the cloning/adding new input. If you posted simplified code and my example doesn't apply, I apologize. Also, I think you wanted to append your cloned input into div.ai_service?
In terms of why your original code adds multiple inputs, the cloning process you go through probably first clones one input, adds it, clones the whole thing again (2 inputs), adds 2, and so on. You can use $().eq(0) to limit your jQuery object to the first element it finds that matches your selector.
Try this
$('a.add_input').live('click', function (e) {
e.preventDefault();
var $column = $(this).closest("div.column");
var input = $column.prev("div.column").clone().wrap("<div />").parent().html();
$column.before($(input));
});