Can anyone help me make jquery validation on a javascript function. basically it change the UI whenever you choose one of the accounts on a dropdown menu: I want to check that one of them in the checkbox was selected to display "you need to check one of them"
$("#selectAcc").change(function() {
var type = $("#selectAcc option:selected").text();
$("#accountInfo").empty();
if (type === "Saving Account") {
$("#accountInfo").append("<label>Rate: </label><input type='text' name='rate'><br>");
$("#accountInfo").append("<input type='checkbox' name='days' value='90' id='90'/>90 days<br>");
$("#accountInfo").append("<input type='checkbox' name='days' value='180' id='180'/>180 days<br>");
$("#accountInfo").append("<input type='checkbox' name='days' value='360' id='360'/>360 days<br>");
$("input:checkbox").click(function() {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
If you are looking for a way to count the checkboxes that are checked based on a grouping by the name attribute this might help you:
$("input:checkbox").click(function() {
var clicked_count = $('input:checkbox[name="'+$(this).attr("name")+'"]:checked').length;
console.log( clicked_count + " checkboxes are checked" );
});
So you might display "you need to check one of them" when the result of this is 0.
connect the listener to an element that isnt added after dom.
$("#accountInfo").on('click', 'input', function(){
// do something
});
Could you try with radio button instead? Something like this:
http://jsfiddle.net/3Ab3z/1
Or if you are checking is there any checkbox checked;
$("#selectAcc").change(function() {
var checked=0;
$( "input:checkbox" ).each(function() {
if($(this).is(':checked')){
checked++;
}
});
if(checked==0){
alert('Please check days!');
}
});
Related
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);
}
});
}
}
I am creating a 'my account page as part of a larger project. And I am using jquery to get data about which radio button the user has selected. I cannot figure out why it isnt working, i believe the problem is with the jquery used to dictate when a radio button is clicked.
JQUERY:
$("input[name=currentTree]").on('change',function(){
var currentTreeId = $(this).val();
alert ('data:' + currentTreeId);
$.post('selectTree.php',{currentTreeId:currentTreeId} ,function(data,status){
alert(data + ' is the current tree');
});
});
$("input[type=radio][name=currentTree]").change(function(){
var currentTreeId = $(this).val();
alert ('data:' + currentTreeId);
$.post('selectTree.php',{currentTreeId:currentTreeId} ,function(data,status){
alert(data + ' is the current tree');
});
});
Try this:
$('input[type=radio][name=currentTree]').change(function() {
if ($(this).val() == 'typeA') {
alert("Got Type A Radio");
}
else if ($(this).val() == 'typeB') {
alert("Got Type B Radio");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="typea">Type A</label><input id="typea" type="radio" name="currentTree" value="typeA">
<label for="typeb">Type B</label>
<input id="typeb" type="radio" name="currentTree" value="typeB">
$("input[name=currentTree]").on('change', function(){
...
});
Example: https://jsfiddle.net/b80sa4kx/
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);
});
This is a validation check that already works i have a name,Email and some other input fields this checks if everything is filled in and if not it makes the inputfields red. if everything is correct it will create a table with the values of the inputfields i have filled in.
<script>
$(document).ready(function(){
$('input[name="submit"]').click(function(e) {
e.preventDefault();
formIsValid = true;
var errors = [];
$('.errors').html("");
$('input.required').each(function() {
if ($(this).val() == '') {
formIsValid = false;
message = $(this).attr('id') + ' is required';
errors.push(message);
$(this).addClass("red");
} else{
$(this).removeClass("red");
}
});
if (formIsValid == true) {
$('.data').append('<tr class="datarow"><td>'+$('input[name="name"]').val()+'</td><td>'+$('input[name="email"]').val()+'</td><td>'+$('input[name="phone_number"]').val()+'</td><td class="delete">X</td></tr>');
updateTotalRows();
$('.delete').click(function() {
$(this).parent().remove();
updateTotalRows();
})
}
});
function updateTotalRows() {
$('.total').html('Ik heb nu : ' + $('.datarow').length + ' rows');
}
});
</script>
<script>
function selectCountry() {
$('.data').append('<tr class="datarow"><td>'+$('.info_link').val()+'</td><td>'+'</td><td class="delete">X</td></tr>');
updateTotalRows();
}
</script>
I already have a clickable dropdown with country's in it but when i click it should use my function selectCountry. That function should make a table with the name of the subitem i have clicked.
Landen
Nederland
Duitsland
Frankrijk
<script>
$(".dropdown")
.bind("click", function (selectCountry) {
console.log((selectCountry))
});
</script>
<script>
$(function(){
$('.info_link').click(function(){
alert($(this).text()); //$('#table tr:last').append($("<td></td>").text());
});
});
</script>
so my question is how do i make a clickable dropdown that takes the value of the subitem and puts it in a table.
You can use a standard <select id="mySelect"><option value="abc">ABC</option></select> element and add a function on element value change:
$("#mySelect").change(function() {
var optionValue = $(this).val();
$('#table tr:last').append('<td>' + optionValue + '</td>');
});
in this fiddle
I have a button add which when clicked adds input datas to a new row as given in the screenshot.The group button is used for creating a group of user numbers.Suppose I want to create a group friends which will contains mobile numbers of 1st row,2nd row and last row. So for this I will just select the checkboxes of 1st row,2nd row and the last row.Then after pressing the group button it will create a group.Group name along with group members(mobile numbers) should be stored in database.So i am using ajax.Please tell me how to pass mobile numbers of selected rows.
following is the jquery
var val=0;
$(document).ready(function(){
$('#btn1').click(function(){
if($(".span4").val()!="")
{
$("#mytable").append('<tr id="mytr'+val+'"></tr>');
$("#mytr"+val).append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr'+val+'" checked ></td>');
$(".span4").each(function () {
$("#mytr"+val).append("<td >"+$(this).val()+"</td>");
});
val++;
}
else
{
alert("please fill the form completely");
}
});
$('#btn2').click(function(){
var creat_group=confirm("Do you want to creat a group??");
if(val>1){
alert(creat_group);
}
});
});
What is group and why do i want it?
Suppose if i have some 100 records,out of that some are java employee,some are .net employee and some are mainframe
Suppose if i want to send sms only to java employee,if i am not having group then out of 100 records
I have to manually check who are java employees.So in order to avoid that I want to create groups 1 for java,1 for .net and another for mainframe.So in order to send sms to only java people I can select the java group and send sms
Try this,
var obj={};// add this
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" checked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
// add below code
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
// add upto above line
val++;
} else {
alert("please fill the form completely");
}
});
Also Update and add below code,
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
}
});
// to get the checked data only
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
obj[key]=null;
}
});
Demo
As said in my comment here's my answer, you need to add that to your $('#btn2').click():
Working Fiddle
$(document).ready(function () {
$('#btn2').click(function () {
var checkedRows = $('#mytable').find("input:checked").parent().parent();
var total = checkedRows.length;
var info = [];
for(i = 0; i < total; i++){
var row = $(checkedRows[i]).children();
var tmpInfo = [];
tmpInfo["name"]= row[1].innerHTML;
tmpInfo["email"]= row[2].innerHTML;
tmpInfo["phone"]= row[3].innerHTML;
info.push(tmpInfo);
}
console.log(info);
$.post('yourpage', info, function(){
//on success code, can be an alert or anything you want.
});
});
});
Explanation: Basicly we first find all the checked checkboxes parent row and create an array (checkedRows);
Then we loop through this array (it's much quicker than using $.each) and add the table cell 1 2 and 3's inner HTML to the info array. (td 0 is the checkbox's cell so we don't need it);
Send info to your server, it should be an array of n sub-arrays (depending on how many rows were checked), the sub-arrays will be holding the name, email and phone.