Hi There I need to get the names and values of checkboxes that have been checked into an array name selected, I cannot for life of me get it working, below is my attempt, if someone could clrify what I am doing wrong that would be brilliant.
//Location AJAX
//var dataObject = new Object();
var selected = new Array();
$('#areas input.radio').change(function(){ // will trigger when the checked status changes
var checked = $(this).attr("checked"); // will return "checked" or false I think.
// Do whatever request you like with the checked status
if(checked == true) {
/*$("input:checked").each(function() {
selected.push($(this).attr('name')+"="+$(this).val();
});
alert(selected)*/
getQuery = $(this).attr('name')+"="+$(this).val()+"&location_submit=Next";
$.ajax({
type:"POST",
url:"/search/location",
data: getQuery,
success:function(data){
alert(getQuery);
console.log(data);
// $('body.secEmp').html(data);
}
});
} else {
//do something to remove the content here
alert("Remove");
}
});
You're missing the closing parantheses on the call to selected.push. It should be:
selected.push($(this).attr('name')+"="+$(this).val());
Otherwise, it looks fine.
Another, possibly simpler, way to do the same thing is to use map instead of each:
var selected = $('input:checked').map(function() {
return $(this).attr('name')+"="+$(this).val();
}).get();
Related
I am trying to perform an ajax request by setting FormData using jquery each loop after finding input and select element for update as follows:
$(document).on("click", ".update", function (e) {
e.preventDefault();
e.stopPropagation();
let thisBtn = $(this);
//Form Data
let formData = new FormData();
let thisRow = thisBtn.closest("tr");
thisRow.find("input,select").each(function() {
//console.log(this.value)
formData.append($(this).attr('name'), $(this).val());
});
$.ajax({
type: "POST",
url: '<?php echo base_url()?>exam/update',
data: formData,
processData: false,
contentType: false,
success:function(data){
if($.trim(data)=='yes')
{
alert('Success! Record updated successfully');
}
else
{
alert('Error! Record not updated successfully')
}
}
});
});
But getting some undefined params as follows:
But I want pure parameters except undefined
Without seeing your HTML we can't tell you exactly why, but from the output it's clear that you have some input and/or select elements in your form which have no name or value. They're probably hidden, so check the DOM inspector to find and remove them.
If you don't want to amend the HTML, then you can use an attribute selector to only find the input and select elements which have a name, like this:
let $thisBtn = $(this);
let formData = new FormData();
let $thisRow = $thisBtn.closest("tr");
$thisRow.find("input[name], select[name]").each(function() {
formData.append(this.name, $(this).val());
});
It seems that this piece of code is finding inputs/select which name attribute is undefined, what would explain the fact you are getting undefined values in the formData.
thisRow.find("input,select").each(function() {
//alert(this.value)
formData.append($(this).attr('name'), $(this).val());
});
I would recommend you to check whether the name is undefined before adding to the formData.
thisRow.find("input,select").each(function() {
//alert(this.value)
if($(this).attr('name'))
{
formData.append($(this).attr('name'), $(this).val());
}
});
I've set up a page with a bunch of contenteditbale divs, along with some js/ajax functionality so that a user can inline edit.
<div class="inlineEdit" contenteditable="true"></div>
JS is a s such:
$(document).ready(function(){
$('div.inline-edit').blur(function()
{
var pathArray = window.location.pathname.split( '/' );
var segment_3 = pathArray[3];
var editableObj = $(this);
var token_input = $('input.token');
var save_data ={};
var token_name = token_input.attr('name');
save_data['field'] = editableObj.attr('id');
save_data['id'] = editableObj.closest('.inline-id').attr('id');
save_data['editedValue'] = editableObj.text();
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
});
});
});
This part all works perfectly grand, all the right fields get updated with the right info. All i need is some way to validate that information before it get to the ajax
I know of JQuery Validation however I'm pretty sure it doesn't work with divs.
Is there a solution or am I stuck/have to change up the divs?
You can create a temporary input box and pass the value through it to check validity. I wrote a function to use HTML5 validation to check for validity.
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
In your case use like this:
if(validityChecker(save_data['editedValue'], 'number')){ // if you want to check for number
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
})
}
Demo:
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
save_data = 'This is not a number';
alert(validityChecker(save_data, 'number')) // false
alert(validityChecker(save_data, 'text')) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have 3 Dropdown List made using Select Option Element. In one list I am inserting manually data while in the other two I am getting Data from Ajax.
My Question is that I want to make specific option to be selected by default. It is successfully applied in the first list but when I try to apply the code in other 2 list it doesn't get affected.
Code Snippet
<select id="box1">...</select>
<select id="box2">...</select>
<select id="box3">...</select>
Ajax Success Callback for box2 to insert options
success: function(data){
modalFloorData = data;
$("#demo2").attr("disabled",false);
$("#demo2").html("<option value=''>Select Any Floor</option>");
for(var i=0; i< data.length;i++){
$("#box2").append("<option value='"+data[i].id+"''>"+data[i].name+"</option>");
}
}
When I triggered Click Event on Button
$(".editBtn").on("click",function(e){
var demoName1 = "value1";
var demoName2 = "value2";
var demoName3 = "value3";
//Ajax Code for fetching Data for the 2 Dropdown List box2 & box 3
//In box1 I am inserting options manually.
$("#box1 option[value='"+demoName1+"']").attr("selected","selected");//Getting Success
$("#box2 option[value='"+demoName2+"']").attr("selected","selected");
$("#box3 option[value='"+demoName3+"']").attr("selected","selected");
return false;
});
Any help would be appreciated...!!
You should set the value in ajax success call back. Because ajax is asynchronous. So values are setting before loading dropdown. Also you can use val() instead of attr() to set selected value.
$(".editBtn").on("click", function (e) {
var demoName1 = "value1";
var demoName2 = "value2";
var demoName3 = "value3";
$.ajax({
url: '...',
type: '...',
data: '...',
success: function (result) {
//do your stuff
//.....
//.....
$("#box2").val(demoName2);
$("#box3").val(demoName3);
}
})
$("#box1").val(demoName1);
return false;
});
i am trying to dynamically have javascript object properties to send through ajax..
Here is what i have done..
var checkBoxName = $(this).attr('name');
var postData = {
Module: ModuleID,
Group:GroupID
};
if($(this).is(":checked")){
postData.checkBoxName = 1;
}else{
postData.checkBoxName = 0;
}
$.ajax({
url: "<?php echo base_url(); ?>user_site/user_group_add_pri/updatePrivilege",
data:postData,
type: "POST",
success: function (output) {
console.log(output);
}
i have multiple checkboxes. every checkbox has different name so what i am trying to do is post data to controller with checkbox name and its value..
but instead it is sending checkBoxName for all checkboxes...
i mean CheckBoxName is a variable but when i did used it like this cuz i thought it would send its value but it is not sending,
i tried like this postData.checkBoxName = but instead of value of variable it is sending as Text??
=-=-=-=-=-=-=-=-=-=--=-=-=-=-=
Update:
The event Occurs when checkbox value is changed.
$("input[type='checkbox']").on('change',function(e){
///Above Code Inside Here
}
If I understand right, I might have an idea.
You can do a loop through all your checkboxes and check if they are checked or not. Then push it into a tab and send through ajax :
var infoCb = new Array();
$('input[type=checkbox]').each(function(){
var tempArray = {
'nameOfCb' : $(this).attr('name'),
'value' : $(this).attr('checked')
}
infoCb.push(tempArray);
});
And then send it via Ajax.
When i use blur function on textbox to check duplicate name using jquery ajax working fine.
Here is code:
function duplicate(data){
//alert(data); //successfully gives the value from the text input
$.post("test.php", {name: data}, function (data){
if(data){
alert('duplicate name');
}
});
}
$(function() {
$("#name").blur(function(){
var data = $("#name").val();
duplicate(data);
});
});
The problem is it show alert message, in some case we submit with duplicate name itself so there is no use of checking duplication.
Let me know the solution to check duplicate name using onsubmit function ( jquery ajax or javascript ).
Your question is confusing because you're using the same variable name, data, outside of your request as well as in the request callback.
I'm not sure if you're asking to check for duplication based on data that has already been submitted and is back on the page, data that exists on the server, or if the data's simply "yes".
Based on the code you provided, it would appear that data is considered to be duplicated if the server returns yes once the POST completes.
Either way, maybe this will help:
$(function() {
$('#name').blur(function() {
duplicate($('#name').val());
});
});
function duplicate(sData) {
var sDuplicateValue = ...; // assign this whatever constitutes a duplicate value
if(isDataDuplicate(sData, sDuplicateValue)) {
// you have duplicate data
}
$.post('test.php', { name: sData }, function(sResposeData) {
/* because of question ambiguity, i don't know if you want to compare
* sData and sResponseData, or sResponseData and "yes." if it's the latter,
* just do isDataDuplicate(sResponseData, "yes"); otherwise, do this:
*/
if(isDataDuplicate(sData, sResponseData) {
// it's the same..
}
});
}
function isDataDuplicate(sData, sDuplicateValue) {
if(sDuplicateValue === null) {
return sData === 'yes';
} else {
return sData === sDuplicateValue;
}
}
I'll do something like this:
$(function() {
$("#name").blur(function(){
var value = $("#name").val();
$.post(
"checkDuplicates.php",
{ name: value},
function (data){
if( data.response === 'yes'){
$("#name").css({
'border': '1px red solid'
}).parent().append('This name already exists');
} else {
return false;
}
},
'json'
);
});
});