I just received some really great help today with a prior jQuery problem and figured since my luck was running that maybe I could also get some help with some checkboxes. Can someone please tell me what I am doing wrong?
Thanks!
The checkboxes are correctly echoing the database bool values but when I submit the changed values, an alert() telles me that they are undefined.
else if (item.field == "admCustRptDly" && item.value == "1")
{
$('#admCustRptDly').attr('checked', true);
}
else if (item.field == "admCustRptSumm" && item.value == "1")
{
$('#admCustRptSumm').attr('checked', true);
}
else if (item.field == "admCustRptDtl" && item.value == "1")
{
$('#admCustRptDtl').attr('checked', true);
}
<tr>
<td class="admMarker">Daily<input type="checkbox" id="admCustRptDly" name="admCustRptDly" class="admChkbx"></td>
<td class="admMarker">Summary<input type="checkbox" id="admCustRptSumm" name="admCustRptSumm" class="admChkbx"></td>
<td class="admMarker">Detail<input type="checkbox" id="admCustRptDtl" name="admCustRptDtl" class="admChkbx"></td>
</tr>
$(function() { $('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admCustBtn").click(function()
{ // validate and process form
// first hide any error messages
$('.error').hide();
var admCustRPSecPhone =
$("input#admCustRPSecPhone").val();
var admCustRptDly =
$("checkbox#admCustRptDly").val();
var admCustRptSumm =
$("checkbox#admCustRptSumm").val();
var admCustRptDtl =
$("checkbox#admCustRptDtl").val();
var dataString =
'admCustID='+ admCustID +
'&admCustRptDly='+ admCustRptDly +
'&admCustRptSumm='+ admCustRptSumm +
'&admCustRptDtl='+ admCustRptDtl;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
alert( "Success! Data Saved");
}
});
return false; }); });
Actually both..
the checkboxes don't have value, so if you try to alert() their values it will lead to "undefined", but if you are facing this on alerting the checkbox itself you are probably doing something wrong.
Setting their values to true, won't lead to anything, as #Soviut said, most properties repeat their names on setting. So your input will get like:
<input type="checkbox" checked="checked" value="1" name="myCheck" />
So, try the above and give us some feedback =´p
Sorry in my case it was the .attr() - works fine for me, even in adobe air.
jQuery('#mycheckbox').attr( "checked" )
Your selectors for the checkboxes are not correct.
var admCustRPSecPhone = $("input#admCustRPSecPhone:checked").val() == 'on';
var admCustRptDly = $("input#admCustRptDly:checked").val() == 'on';
var admCustRptSumm = $("input#admCustRptSumm:checked").val() == 'on';
var admCustRptDtl = $("input#admCustRptDtl:checked").val() == 'on';
You could also use something like:
var admCustRptDly = $("#admCustRptDly:checkbox:checked").val() == 'on';
This will set the values to true/false depending on whether the checkbox is checked or not.
You have no value attribute set on your HTML input element
<input type="checkbox" value="1" id="admCustRptDly" name="admCustRptDly">
Related
i have 3 check boxes in 3 different pages,i want to check one check box at time means at first all 3 are unchecked and if i checked one check box remaining 2 check boxes should be disable.
each check box value i am storing in 3 different text file using array in the form of 1's and 0's.
now for one page i am reading check box values and based condition trying to disable check box but its not working.
I have Tried this
check box html code:
input type="checkbox" id="cb1" name="check[0]" value="1" />
java script:
<script type="text/javascript">
var cb1 =document.getElementById("cb1");
var cb2 = "<?php echo $cb2_arr[5] ?>" ; //cb2=1 or 0
var cb3 = "<?php echo $cb3_arr[6] ?>"; //cb3=1 or 0
if(cb2 ==1 || cb3 == 1){
cb1.disabled = true;
}else{
cb1.disabled = false;
}
</script>
cb1.disabled = true; for me its not working i kept alert statements above and below it ,only above one is displayed
Please help me how to set disabled property, thanks
try this to disabled and remove disabled,
if ($('#cb3').is(':checked') || $('#cb2').is(':checked')) {
$('#cb1').setAttribute('disabled', true);
}else{
$('#cb1').setAttribute('disabled', false);
}
You need to check input1.value == "", not simply input1 == ""
You also need to fire your method originally, and also run it every time your select lists change value.
Give the function a name
function setCheckState(evt) {
if (input1.value == "" || input2.value == "") {
result.disabled = true;
} else {
result.disabled = false;
}
}
Add event listeners
input1.addEventListener('change', setCheckState);
input2.addEventListener('change', setCheckState);
// Fire the method to get the initial checkbox state set
setCheckState();
Finally, you can reduce your if() statement to a simple assignment...
function setCheckState(evt) {
result.disabled = input1.value == "" || input2.value == "";
}
I'm trying to make a function that checks if any checkboxes generated by this line
foreach ($order->get_items() as $item ){
echo "<input type='checkbox' name='productinfo[]' value='" .$item->get_name() . "|" . $item->get_quantity() . "|" . $item->get_total() ."'>";
are checked, and if not it displays an error, how do you make one with php/javascript if you can? or do you need jQuery to make one. Preferably if none are checked it would prevent a form submit from being done
This will do the trick. Check the length of input element with the name productinfo[]" that are checked. In javascript the number 0 is false. All others are true.
The function console.error() will log an error to the console. But you can change that to any kind of error message you like.
function checkBoxCheck(e) {
if ($('input[name="productinfo[]"]:checked').length) {
console.log("at least one checked");
return true;
} else {
console.error("no checkbox checked");
return false;
}
}
$('#myForm').on('submit', checkBoxCheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="/dummy.html">
<input type='checkbox' name='productinfo[]' value='1'>
<input type='checkbox' name='productinfo[]' value='2'>
<input type='checkbox' name='productinfo[]' value='3'>
<input type='checkbox' name='productinfo[]' value='4'>
<input value="Check" type=submit>
</form>
You can use length of jQuery in order to check atleast one checkbox is checked
if($('input[type="checkbox"]:checked').length > 0){
//your code here
}else{
alert('Please check atleast one checkbox');
}
Note: this will check all checkboxes across the page, because your input checkbox has no class.
In order to check if a checkbox is checked use checked property in Jquery/Javascript like so:
Jquery:
var isChecked = $('input:checkbox').is(':checked'); // to check if any checkbox is checked
var isChecked = $('input[type=checkbox]:checked').length; // finds how many checkboxes are checked
if(length > 0){
alert(length); //alert how many checkboxes are checked
}
Javascript:
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
}
}
alert(count)
OR you can also use :s
var length=document.querySelectorAll('input[type="checkbox"]:checked').length
Set a onclick trigger to a function on the submit button. Change the type of button from submit to button.
<button type ="button" id = "some-id" onclick = "savebutton();">
Inside the Javascript function use the validation :
function savebutton(){
if(document.querySelectorAll('input[type="checkbox"]:checked').length == 0){
alert('None of the checkboxes are checked');
}else{
var some_value = document.getElementById('id_of_some_element_you_wish_to_save').value;
$.ajax({
url : 'backend.php',
method : 'POST',
data: {values_you_want_to_send:some_value},
dataType: 'json',
success:function(data) {
window.reload();
}
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
}
Well, the question's pretty self-explanatory. I've been looking for a while and haven't found a proper way to do this kind of validation.
All I need to do is to run an error message if all the inputs are empty. If one of them is filled, then I don't need to stop the form from submitting.
I thought something like:
function checkForm() {
$('input').each(function(){
if( $(this).val() == "" ){
return false;
}
});
});
But this will stop my form if there's, at least, one input without data.
Any ideas? Thanks in advance.
Reverse your logic. I.e. return true if any input has a value, otherwise return false:
function checkForm() {
$('input').each(function() {
if ($(this).val() !== '') {
return true;
}
});
return false;
};
Reverse your logic since you want to check if the value is non-empty for one input field.
Also you probably want to return from your actual function and not from the callback which has no effect.
function checkForm() {
let bool = false;
$('input').each(function(){
if( $(this).val() !== '' ){
bool = true;
}
});
console.log(bool);
return bool;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<button onclick="checkForm()">check</button>
I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});
I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});
You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />
You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});