I have a jquery each code where i am trying to match the data set of the previous checkbox with current one, so if they do not match, just uncheck the checkbox, but seems i am missing something here
obj.each(function(i,e) {
var refer = $(e);
if(e.checked && refer.prev(e.dataset.stid) != e.dataset.stid) {
e.checked = false;
}
}
here i am not sure what is wrong, but it is not working, also i am trying to add a code that if there is no previous check, just exists from this block
.prev() is a jQuery method that can return one of two things: an element, or null.
Unless e.dataset.stid is null or undefined, the condition will always be satisfied, thus unchecking all your checkboxes.
To get the previous element's data-stid attribute, try comparing refer.prev().data("stid") instead.
let obj = $("input[type=checkbox]");
obj.each(function(i,e) {
if (i === 0) return;
var refer = $(e);
if(e.checked && refer.prev().data("stid") != e.dataset.stid) {
e.checked = false;
}
});
input:not(:nth-child(2)) { margin-left: 25px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-stid="1" checked> data-stid="1"
<input type="checkbox" data-stid="1" checked> data-stid="1"
<input type="checkbox" data-stid="0" checked> data-stid="0"
<input type="checkbox" data-stid="1" checked> data-stid="1"
Related
My program needs to store the value of multiple checkboxes in session Storage (checked or not checked), so that when the user returns to this page they are already checked or not checked. All the solutions to this problem that I have found involve the use of JQuery which we aren't supposed to use.
This is the HTML for the checkboxes
<fieldset>
<legend>Skills List</legend>
<p> <label for="teamwork">Teamwork</label>
<input type="checkbox" id="teamwork" name="Skill[]" value="Teamwork" checked="checked"/>
<label for="rubyskills">Ruby Experience</label>
<input type="checkbox" id="rubyskills" name="Skill[]" value="Rubyskills"/>
<label for="efficiency">Efficiency</label>
<input type="checkbox" id="efficiency" name="Skill[]" value="Efficiency"/>
<label for="communication">Communication</label>
<input type="checkbox" id="communication" name="Skill[]" value="Communication"/>
<label for="other">Other</label>
<input type="checkbox" id="other" name="Skill[]" value="other"/>
</p>
so, in vanilla JS this is how you would go about getting all of the checked inputs in your given fieldset. If you could update your question with a bit more detail and code on how you are saving to session storage I can help further.
let fieldset = document.getElementById("fieldset1") // get fieldset element
let p = fieldset.children[1]; // the p tag
let pchildren = p.children; // the contents of the p tag
let inputs = []; // where we will hold the input elements that are checked
for (let x = 0; x < pchildren.length; x++) { // looping through to get only the inputs that are checked
if (pchildren[x].nodeName == "INPUT" && pchildren[x].checked) {
inputs.push(pchildren[x]) // pushing into array
}
}
console.log(inputs);
Thanks but I solved it
function store_data() {
var teamwork = document.getElementById("teamwork").checked;
var rubyskills = document.getElementById("rubyskills").checked;
var efficiency = document.getElementById("efficiency").checked;
var communication = document.getElementById("communication").checked;
sessionStorage.setItem("teamwork", teamwork);
sessionStorage.setItem("ruby", rubyskills);
sessionStorage.setItem("efficiency", efficiency);
sessionStorage.setItem("communication", communication);
sessionStorage.setItem("other", other);
}
function prefill_form() {
if(sessionStorage.teamwork == "true") {
document.getElementById("teamwork").checked = true;
}
if(sessionStorage.ruby == "true") {
document.getElementById("rubyskills").checked = true;
}
if(sessionStorage.efficiency == "true") {
document.getElementById("efficiency").checked = true;
}
if(sessionStorage.communication == "true") {
document.getElementById("communication").checked = true;
}
if(sessionStorage.other == "true") {
document.getElementById("other").checked = true;
}
}
I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}
I am getting values (1 or 0) from my database via ajax/jquery and I want to set a bunch of checkbox checked states depending on the values returned for each.
So firstly, I am setting the values for all checkboxes. Then I run a function to set the checkbox checked state based on the values. When I try this, all checkboxes are checked regardless of value:
Snippet of my Ajax response (jQuery)
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
$("#checkbox1").prop('value',value[2]);
$("#checkbox2").prop('value',value[3]);
$("#checkbox3").prop('value',value[4]);
$("#checkbox4").prop('value',value[5]);
});
$("#div :checkbox").each(function () {
if ($(this).attr('value', '1')){
$(this).attr('checked', true);
}
else
if ($(this).attr('value', '0')){
$(this).attr('checked', false);
}
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
You are likely trying to set the value of the checkbox false with a string. This does not work. You need it to be a booelan true/false or 0/1 .. The value "0" will set the checkbox "checked". See the example and how the second checkbox remains checked.
$(document).ready(function() {
$("#chkbox1").prop("checked", 0);
$("#chkbox2").prop("checked", "0");
$("#chkbox3").prop("checked", 1);
$("#chkbox4").prop("checked", "1");
$("#chkbox5").prop("checked", parseInt("0"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>
<input id="chkbox1" type="checkbox" name="chk" checked />checkbox1
</label>
<label>
<input id="chkbox2" type="checkbox" name="chk" checked/>checkbox2
</label>
<label>
<input id="chkbox3" type="checkbox" name="chk" />checkbox3
</label>
<label>
<input id="chkbox4" type="checkbox" name="chk" />checkbox4
</label>
<p>
<label>
<input id="chkbox5" type="checkbox" name="chk" checked />checkbox5
</label>
</p>
To properly "check/uncheck" a chekcbox you should use the jQuery functions prop('checked',true) or prop('checked',false).
Change the if/else statement in this way:
if ($(this).attr('value', '1')){
$(this).prop('checked', true);
}
else
if ($(this).attr('value', '0')){
$(this).prop('checked', false);
}
You are not checking for current value you are setting value to 1 for all checkboxes;
if ($(this).attr('value', '1')){
.attr('attribute name', [new value to set]);
So you are using this function in wrong way. To get value try
if ($(this).attr('value')){
Here you will get 1 or 0 as you said you are getting 1 & 0 from server after ajax.
How to check checkbox checked or not using javascript ?
I have a lot of checkbox (dynamic data) . I want to know how can i check when checked chekcbox >= '1' using javascript ?
<input type="checkbox" id="1" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="2" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="3" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="4" name="test[]" onclick="test_fn()"/>
<script>
function test_fn() {
// check it's have checked checkbox or not ? //
}
</script>
Try to pass this in your inline handler,
<input type="checkbox" id="1" name="test[]" onclick="test_fn(this)"/>
And use this.checked to find out whether it is checked or not,
function test_fn(elem) {
alert(elem.checked);
}
DEMO
To check, if the the checked check box greater than or equal to 1, then just do
function test_fn(elem) {
if (document.querySelectorAll("input[name='test[]']:checked").length >= 1) {
alert("yes it is greater than or equal to 1")
}
}
DEMO
function test_fn()
{
if (this.checked) return true;
else return false;
}
Edit:
this reference won't work in this case, thanks to #RajaprabhuAravindasamy for pointing this out, read the comments or check this SO question for more information.
You need to pass a reference explicitly to the checkbox element:
function test_fn (el)
{
if (el.checked) return true;
else return false;
}
As for how to know if checked boxes count is more than one you can simply use a global variable to keep a track of the count like this:
var count = 0;
function test_fn (el)
{
el.checked ? count++ : count--;
return count > 1;
// if (count > 1) alert ("count is more than 1");
}
Demo
I have a form that submits values to database via Ajax and works fine but I also need to give option to user to reset the form to its default values in case they make a mistake.
The default values are stored in a javascript variable as json object
{"field_name1":"2","field_name3":"3","field_name3":"1000"...
problem I have is that the form has multiple input types , textarea , select , radio
and I need to figure out what they are based on the object key , look for name and return type , so I could do something like if radio set checked checked and so on
I tried
Object.each(dafaultValues, function(value, key){
var filed_name = MyForm.elements[''+key+''];
console.log(filed_name.type);
});
problem with this is that radio type have same name but different id's
<input type="radio" name="field_name5" id="field_name51" value="1">
<input type="radio" name="field_name5" id="field_name52" value="1" checked="checked">
and I endup with js error
Uncaught TypeError: Cannot read property 'type' of undefined
so what would be the best way to find out what the input type is before I can do
if(field.type ='radio'){
//set checked checked..
}
Take a look at this example. I just put it together very dirty, but you will get the idea ;)
HTML:
<form id="test">
<input type="radio" name="abc" value="1"/>
<input type="radio" name="abc" value="2"/>
<input type="radio" name="abc" value="3"/>
<input type="text" name="def" value="change" />
</form>
JS:
var values = {
'abc': '2',
'def': 'original'
};
var els = $('test').getElements('[name="abc"], input');
els.each(function(el) {
var defaultVal = values[el.get('name')],
type = el.get('type');
if (typeof defaultVal != 'undefined') {
return;
}
if (type == "radio") {
if (el.get('value') == defaultVal) {
el.set('checked', 'checked');
} else {
el.erase('checked');
}
}
if (type == "text") {
el.set('value', defaultVal);
}
});