Why Checkbox is not unchecking in jquery - javascript

I need to uncheck a checkbox. It is doing everything like alert or removing div, but not unchecking the checkbox. I have used both attr and prop methods. The checkbox id is ok. Even it doesn't show any error in firebug console.
$('html').on('click', '#inScopeDiv .remButton', function () {
var currId = $(this).attr('id');
var chkBoxId = "#chk"+currId;
alert(currId);
alert('#chk'+currId);
$(chkBoxId).prop("checked", false);
$(chkBoxId).attr("checked", false);
$('#div'+ currId).remove();
$('#inScopeActionDiv' + currId).remove();
});
HTML provided ::
<c:forEach items="${data.inScope}" var="inScopeValues">
<div class="col-md-12" style="background-color: snow;">
<input class="inScope" type="checkbox" id="chk${inScopeValues.key}" name="chk + ${inScopeValues.key}" value="${inScopeValues.value}">
${inScopeValues.value}
</div>
</c:forEach>
Button & Checkbox is below ::>
<input class="inScope" type="checkbox" id="chkisc_2" name="chkisc_2" value="In Scope 2">
<button id="chkisc_1" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>

The button you show in the updated question has id="chkisc_1", then in your function you take that and add #chk to the beginning of it which would mean you're looking for an element with the selector "#chkchkisc_1". Meanwhile, apparently the checkbox has id="chkisc_2", although it does seem to be created in a loop so perhaps there is also a _1 (though that would mean you have more than one element with the same id, which is invalid html).
Change the button to have id="isc_1", then when your JS adds #chk it will be looking for #chkisc_1:
$('html').on('click', '#inScopeDiv .remButton', function () {
var currId = $(this).attr('id');
var chkBoxId = "#chk"+currId;
$(chkBoxId).prop("checked", false);
$('#div'+ currId).remove();
$('#inScopeActionDiv' + currId).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="inScopeDiv">
<input class="inScope" type="checkbox" id="chkisc_1" name="chkisc_1" value="In Scope 1" checked>
<button id="isc_1" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>
<input class="inScope" type="checkbox" id="chkisc_2" name="chkisc_2" value="In Scope 2" checked>
<button id="isc_2" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>
</div>

You should use prop() and removeAttr() to achieve this.. Hope it helps!
var cb = $("#checkbox")
$('#button1').click(function() {
cb.prop("checked", true)
})
$('#button2').click(function() {
cb.removeAttr('checked')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox" />This is a checkbox
<br />
<br />
<button id="button1">Check checkbox</button>
<br />
<br />
<button id="button2">Uncheck checkbox</button>

let checkbox = document.querySelector("input");
checkbox.addEventListener("click",function(){
console.log("Sorry ( ͡° ͜ʖ ͡°)");
this.checked = false;
});
<input type="checkbox" />

Related

How to get data attribute from dynamic button if it changes

I would like to obtain the value of an attribute (here the title) of a dynamic button (created by the multiselect library) and display it in a text box, if there is a change.
Here's what I have now:
// for combine checkbox value
$(function() {
$('input').on('click', function() {
var values = [];
$('input[name=test]:checked').each(function() {
values.push($(this).parent().text());
});
$('[name="result"]').attr({
value: values.join('|')
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form oninput="txtrequete.value = (
txtdomain.value + ';' + result.value).replace(/\s+/g, '');" class="form-horizontal form-label-left">
FINAL
<div>
<input type="text" name="txtrequete" disabled="disabled" size='70'>
</div>
TEXT TEST FOR CONCAT
<div>
<input type="text" name="txtdomain" id="domainId" value="testvalue" />
</div>
CHECKBOX TEST FOR CONCAT
<div>
<label><input type="checkbox" name="test" /> test3</label><br />
<label><input type="checkbox" name="test" /> test4</label><br />
<input type="text" name="result" disabled="disabled" />
</div>
<div>
BUTTON CREATED FROM MULTISELECT JQUERY LIBRARY
</div>
<button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown" title="India, United State, Canada, Taiwan" aria-expanded="true">
<span class="multiselect-selected-text">4 selected</span> <b class="caret"></b></button>
<div>
<input type="text" name="spantitle" disabled="disabled" value="i would like the title value 'India, United State, Canada, Taiwan' HERE from the button attribute if change" size="70" />
</div>
</form>
has anyone ever used this before? Thank you in advance
<button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown"
title="India, United State, Canada, Taiwan" aria-expanded="true">
<span class="multiselect-selected-text">4 selected</span>
<b class="caret"></b></button>div>
<input type="text" name="spantitle" disabled="disabled"
value="i would like the title value 'India, United State, Canada, Taiwan' HERE from the button attribute if change"
size="70" />
</div>
If you have an event listener, just simply use the title attribute of your button and set it as value of your input field, like:
$('input[name=spantitle]').val($('.multiselect ').attr('title'));
If you are not sure when or how the dynamic changes happen, you could use MutationObserver.
The MutationObserver interface provides the ability to watch for
changes being made to the DOM tree. It is designed as a replacement
for the older Mutation Events feature which was part of the DOM3
Events specification.
Here is an example how it could work:
// for combine checkbox value
$(function() {
$('input').on('click', function() {
var values = [];
$('input[name=test]:checked').each(function() {
values.push($(this).parent().text());
});
$('[name="result"]').attr({
value: values.join('|')
});
});
});
$('#test').on('click', () => {
$('.multiselect ').attr('title', 'Just another attribute');
});
var observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === "attributes") {
$('input[name=spantitle]').val($('.multiselect ').attr('title'));
}
});
});
observer.observe($('.multiselect')[0], {
attributes: true // Listening to the attribute changes
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form oninput="txtrequete.value = (
txtdomain.value + ';' + result.value).replace(/\s+/g, '');" class="form-horizontal form-label-left">
FINAL
<div>
<input type="text" name="txtrequete" disabled="disabled" size='70'>
</div>
TEXT TEST FOR CONCAT
<div>
<input type="text" name="txtdomain" id="domainId" value="testvalue" />
</div>
CHECKBOX TEST FOR CONCAT
<div>
<label><input type="checkbox" name="test" /> test3</label><br />
<label><input type="checkbox" name="test" /> test4</label><br />
<input type="text" name="result" disabled="disabled" />
</div>
<div>
BUTTON CREATED FROM MULTISELECT JQUERY LIBRARY
</div>
<button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown" title="India, United State, Canada, Taiwan" aria-expanded="true">
<span class="multiselect-selected-text">4 selected</span> <b class="caret"></b></button>
<div>
<input type="text" name="spantitle" disabled="disabled" value="i would like the title value 'India, United State, Canada, Taiwan' HERE from the button attribute if change" size="70" />
</div>
</form>
<button id="test">Test me!</button>
Click on the button "Test me!" to change the title attribute and you may see that the object observer will change the value of your input field.

Compare two variables with generated numbers

Currently I learn the curve of PHP and for first time trying to make AJAX request to my PHP script. I got cart in my own written shop for learning purposes, it generates button and input field with same "data-id" attributes for each position. And of course, input field got "value" attribute with current amount of products.
Code:
Jquery:
$(document).ready(function() {
$(".btn").click(function () {
var id = $(this).attr("data-id");
var idInput = $(".field").attr("data-id");
var value = $(".field").attr("value");
if (id === idInput) {
$.post("/cart/addAjax/" + id, {}, function (data) {
$("#cart-count").html(data);
});
$.post("/cart/addAjax/" + value, {});
return false;
} else {}
});
});
Example of input of PHP generated HTML:
<input class="field" data-id="3" type="number" value="23">
<button class="btn" data-id="3">Quantity</button>
<input class="field" data-id="14" type="number" value="3">
<button class="btn" data-id="14">Quantity</button>
<input class="field" data-id="17" type="number" value="2">
<button class="btn" data-id="17">Quantity</button>
<input class="field" data-id="18" type="number" value="8">
<button class="btn" data-id="18">Quantity</button>
<input class="field" data-id="19" type="number" value="10">
<button class="btn" data-id="19">Quantity</button>
I want Jquery script to compare input/button "data-id" attributes and send "value" of selected "data-id" attribute request to PHP side, but don't know how to tell script get "value" from selected "data-id", guess its the reason why its POST successfully only for first generated product in cart, for the rest products script doesn't work. Can someone enlighten me how to achieve this? Thanks in advice.
You need to structor your html a little better.
I made some changes to the html and put each btn and field under a div.
This will make things easer to find the selected input by its btn click.
Read the comment to understand.
$(document).ready(function() {
$(".btn").click(function () {
var id = $(this).attr("data-id");
// now go to the selected btn Parent, and then find the .field
// there you are sure its the right field becouse both the button
// and the field is containe under one div{Parent}
var idInput = $(this).parent().find(".field")
console.clear();
console.log("you Selected id " +id + " and its value is " + idInput.val())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="field" data-id="3" type="number" value="23">
<button class="btn" data-id="3">Quantity</button>
</div>
<div>
<input class="field" data-id="14" type="number" value="3">
<button class="btn" data-id="14">Quantity</button>
</div>
<div>
<input class="field" data-id="17" type="number" value="2">
<button class="btn" data-id="17">Quantity</button>
</div>
<div>
<input class="field" data-id="18" type="number" value="8">
<button class="btn" data-id="18">Quantity</button>
<div>
<input class="field" data-id="19" type="number" value="10">
<button class="btn" data-id="19">Quantity</button>
</div>
$('button').on('click',function(){
var data = $(this).data('id');
var url = 'your php file';
$.post(url,data,function(rdata){
//do whatever yo want with returned data
});
});

Bootstrap 3 button group, trying to get the value of which button is clicked on

Learning Javascript here, just stuck for a brief moment.
I have a button group in html constructed with the following.
<div class="button-holder type_of_txt_btn_group" data-toggle="buttons">
<label class="btn btn-primary active" value="TE">
<input name="text" type="radio" id="txtbutton_id">Text
</label>
<label class="btn btn-primary" name="textbook" value="TK">
<input name="textbook" type="radio">Textbook
</label>
<label class="btn btn-primary" name="list" value="LI">
<input name="list" type="radio" value="list">List
</label>
</div>
The value attribute of each <label> is important for filtering purposes. So I want to make a function that, when you click one of the buttons, the function manages to return (or at least use) the value of the label a person clicked on. To check, I wanted to simply use a console.log expression. Ideally I would see either "TE" or "TK" or "LI" in the console.
$(".type_of_txt_btn_group label").on("click",function() {
var filteringType = ""
filteringType = $(this).val()
console.log(filteringType);
});
But so far this has been yielding what seem to be empty strings in my console and I'm not really sure why at this point. Here is the version I created on fiddle. https://jsfiddle.net/12rsob36/1/
Is this returning an empty string and if so why? Is it actually returning the values of the label elements like I would want it to, or is something wrong? What can I do to fix it?
You cannot access the value of a label with val() as it only supports form elements. You can use the data() function instead and set data-x attributes to the buttons.
Furthermore the official documentation suggests using <button> instead of <label>:
$(".type_of_txt_btn_group button").on("click",function() {
var filteringType = $(this).data('value')
console.log(filteringType);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="button-holder type_of_txt_btn_group btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" data-value="TE">Text</button>
<button type="button" class="btn btn-default" data-value="TK">Textbook</button>
<button type="button" class="btn btn-default" data-value="LI">List</button>
</div>
You can also access the values of the label using attr() method. It sets or returns the values of attributes of the selected element.
$(".type_of_txt_btn_group label").on("click", function() {
var filteringType = ""
var label = $(this).attr('name');
// filteringType=label.attr('name');
alert(label);
});
<div class="button-holder type_of_txt_btn_group" data-toggle="buttons">
<label class="btn btn-primary active" name="text">
<input name="text" type="radio" id="txtbutton_id" value="text">Text
</label>
<label class="btn btn-primary" name="textbook">
<input name="textbook" type="radio" value="textbook">Textbook
</label>
<label class="btn btn-primary" name="list">
<input name="list" type="radio" value="list">List
</label>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Please refer to the code above.Hope this is what you are looking for.

Toggle checked status on input inconstant in jQuery function

I fear I'm missing something painfully obvious, but this jquery function appears to be working inconsistently.
HTML:
<label id="income_this_tax_year">
<div class="left">
<p>Have you had Self-Employment, Sole Trade or CIS income during the tax year?</p>
</div>
<div class="right">
<input type="radio" name="income_this_tax_year" value="yes" />
<input type="radio" name="income_this_tax_year" value="no" />
<button type="button" data-value="yes" class="button">Yes</button>
<button type="button" data-value="no" class="button">No</button>
</div>
<div class="float-clear"></div>
</label>
jQuery:
$(document).ready(function(){
$('button').on('click', function(e) {
e.preventDefault();
var option = $(this).parent('.right').parent('label').attr('id');
var value = $(this).data('value');
$('#'+option).find('input[type=radio]').prop('checked', false);
$('#'+option+' input[value='+value+']').prop('checked', true);
var income_this_tax_year = $('input[name=income_this_tax_year]:checked').val();
console.log(income_this_tax_year);
})
});
jsfiddle
The buttons are to replace the interaction of the radio inputs. On the first initial clicks of each button it works as intended, but any consequent click returns undefined (and removes the checked status from the inputs entirely).
What makes this particularly tricky to debug is that when I inspect the DOM everything happens as expected. The radios checked status/attr does change, but jquery still reports it as undefined and visually the radio button isn't checked (you can see this if you inspect the result on jsfiddle and watch the inputs as you click the buttons).
Any thoughts?
You can use prop instead:
$(document).ready(function() {
$('button').on('click', function(e) {
e.preventDefault();
var option = $(this).parent('.right').parent('label').attr('id');
var value = $(this).data('value');
//$('#' + option).find('input[type=radio]').removeAttr('checked');
//replace here attr with prop
$('#' + option + ' input[value=' + value + ']').prop('checked', true);
var income_this_tax_year = $('input[name=income_this_tax_year]:checked').val();
console.log(income_this_tax_year);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="income_this_tax_year">
<div class="left">
<p>Have you had Self-Employment, Sole Trade or CIS income during the tax year?</p>
</div>
<div class="right">
<input type="radio" name="income_this_tax_year" value="yes" />
<input type="radio" name="income_this_tax_year" value="no" />
<button type="button" data-value="yes" class="button">Yes</button>
<button type="button" data-value="no" class="button">No</button>
</div>
<div class="float-clear"></div>
</label>
Use prop() instead of attr() and removeAttr() to change the checked status of radio buttons.
Check .prop('checked',false) or .removeAttr('checked')? for more info.
Demo
$(document).ready(function() {
$('button').on('click', function(e) {
e.preventDefault();
var option = $(this).parent('.right').parent('label').attr('id');
var value = $(this).data('value');
$('#' + option + ' input[value=' + value + ']').prop('checked', true);
var income_this_tax_year = $('input[name=income_this_tax_year]:checked').val();
console.log(income_this_tax_year);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<label id="income_this_tax_year">
<div class="left">
<p>Have you had Self-Employment, Sole Trade or CIS income during the tax year?</p>
</div>
<div class="right">
<input type="radio" name="income_this_tax_year" value="yes" />
<input type="radio" name="income_this_tax_year" value="no" />
<button type="button" data-value="yes" class="button">Yes</button>
<button type="button" data-value="no" class="button">No</button>
</div>
<div class="float-clear"></div>
</label>

Enabling or Disabling Buttons Based on CheckBox

I had an I Agree Checkbox that when checked or unchecked it used JS to toggle the Disabled setting on a button with id="submit1". However, I added more buttons and now it needs to toggle all of these buttons rather than just the first, so the ID isn't working anymore.
Current Code for checkbox:
<input type="checkbox" checked id="agree" name="agree" value="ON" onclick="javascript: if(document.getElementById('agree').checked==true){document.getElementByID('submit1').disabled=false;}else{document.getElementByID('submit1').disabled=true;}">
And for button:
<button onclick="do_file_form_submit(7);" id="submit1" name="submit1" class="custombutton">Button Number 1</button>
So, I have added more buttons, so I need 2 things:
I need JS or jquery that will loop through and toggle EACH button when the box is checked rather that just the single button (first button with the ID).
On page load, I also need it to check and see if the box is checked and if not, loop through and disable all of those buttons.
Thanks so much for any help you can give!!
Craig
HTML:
<input type="checkbox" checked id="agree" name="agree" value="ON">
<button onclick="do_file_form_submit(7);" id="submit1" name="submit1" class="custombutton">Button Number 1</button>
<button onclick="do_file_form_submit(7);" id="submit2" name="submit2" class="custombutton">Button Number 2</button>
jQuery:
$('#agree').change(function () {
if ($(this).is(":checked")) {
$('button').attr("disabled", false);
} else {
$('button').attr("disabled", true);
}
});
Here is the fiddle: http://jsfiddle.net/shahe_masoyan/UpxzB/3/
Check this out Your working page
function checkStatus() {
if ($('#agree_again').is(":checked")) {
$(".custombutton").attr('disabled', false);
}
else {
$(".custombutton").attr('disabled', true);
}
}
$("#agree_again").change(function () {
checkStatus();
});
You can call this checkStatus function on body load to check whether its checked or not on page load .
asign same classname for all button.
then use the class name for selector.
document.getElementByClassName("custombutton").disabled=false
Try this code. Hope this resolve your problem
$(function(){
//$("#agree").is(":checked")
EnableDisableButton(!$("#agree").is(":checked"))
$("#agree").click(function(){
EnableDisableButton(!$("#agree").is(":checked"));
})
function EnableDisableButton(isEnable){
$(".custombutton").attr("disabled",isEnable);
}
});
very simple
<input type="checkbox" checked="checked" id="agree" name="agree" value="ON"
class="agree_chk" />
<input type="button" class="button" id="button1" value="button1"/>
<input type="button" class="button" id="button1" value="button2"/>
<input type="button" class="button" id="button1" value="button3"/>
<input type="button" class="button" id="button1" value="button4"/>
and the javascript is
$(document).on('click','#agree',function() {
$('.button').attr({disabled:!$(this).is(':checked')})
});
js fiddle http://jsfiddle.net/5V2Y4/
try this code
<input type="checkbox" checked id="agree" name="agree" value="ON" onclick="change()">
<input type="button" id="button1">
<input type="button" id="button2">
<input type="button" id="button3">
<script>
$(document).ready(function() {
change();
});
function change() {
var i = 1;
for (i = 1; i <= 3; i++) {
var btnid = "button" + i;
if (document.getElementById("agree").checked) {
document.getElementById(btnid).disabled = false;
} else {
document.getElementById(btnid).disabled = true;
}
}
}
</script>
you can change the limit as the number of buttons changes

Categories

Resources