How can I find in JQuery input by name, if I have dot array syntax from Laravel?
Input example:
<input type="text" name="Payments[0][1][Amount]">
<input type="text" name="Reservations[0][Date]">
Laravel validation response from ajax request:
errors: {
Payments.0.1.Amount: "Field is required",
Reservations.0.Date: "Field should be date"
}
Problem: How can I looping through errors array in javascript access input names, if I only have array dot names?
For example, transform Payments.0.1.Amount to Payments[0][1][Amount], or Reservations.0.Date to Reservations[0][Date]
for (const [key, value] of Object.entries(errors)) {
key = somehowParseDotInputToArray(key); // how? :)
$('#app input[name="' + key + '"]').append( '<p class="error">'+ value +'</p>' );
}
Have allready found solution, maybe someone also helps :)
function DotArrayToJs(str){
var splittedStr = str.split('.');
return splittedStr.length == 1 ? str : (splittedStr[0] + '[' + splittedStr.splice(1).join('][') + ']');
}
Simply split the name in an error object from . . Using var $nameArr = name.split('.');
Suppose name = Reservations.0.Date it will be like
let nameArr = ['Reservations','0','Date']
then make name as you want so
var newName = $nameArr[0] + '['+ $nameArr[1] +']' + '[' +$nameArr[2] + ']';
newName will look like Reservations[0][Date]
loop this process for all name variable and make new error object.
Juste in case someone has multi-level arrays
function getFieldnameFromLaravelDotName(laravelDotName) {
let parts = laravelDotName.split(".");
let fieldName = "";
let prefix = "";
let suffix = "";
parts.forEach((part, i) => {
if (fieldName != "") {
prefix = "[";
suffix = "]";
}
fieldName += prefix + part + suffix;
});
return fieldName;
}
console.log(getFieldnameFromLaravelDotName("noDotInThis"));
console.log(getFieldnameFromLaravelDotName("one.level"));
console.log(getFieldnameFromLaravelDotName("many.level.array.plop"));
Related
I use a ternary operator to check which checkboxes in a form have been selected. If a value has been selected, I affix the name-value pair to a query string which is then passed in an AJAX call. If not, I attach a name with an empty string value.
It works fine, I'm just wondering if there's a more compact/elegant way to do this as it seems somewhat verbose. I'm wondering if it's possible to use a for loop. The reason I'm not sure if this would work is it would involve dynamically assigning variable names within the loop based on the index.
var fields = $('input[name="apn"]').serializeArray();
var apn1 = fields[0] ? fields[0]["value"] : ''
query += '&apn1=' + apn1;
var apn2 = fields[1] ? fields[1]["value"] : ''
query += '&apn2=' + apn2;
var apn3 = fields[2] ? fields[2]["value"] : ''
query += '&apn3=' + apn3;
var apn4 = fields[3] ? fields[3]["value"] : ''
query += '&apn4=' + apn4;
var apn5 = fields[4] ? fields[4]["value"] : ''
query += '&apn5=' + apn5;
...
Map the values and indices to an array of objects, and just pass that directly to $.ajax, jQuery will use $.param on it for you :
var fields = $.map($('input[name="apn"]'), function(el, i) {
var o = {};
o['apn' + i] = el.value;
return o;
});
If its just checkboxes:
$('input[name="apn"]').each(function (i, el) {
if($(el).is(':checked')) {
query += '&apn'+i+'=' + el.value;
}
});
You can simply serialize the form:
var query = $("#FormId").serialize();
I want to get values of all fields in a variable separated by a comma. For example: 1,2,3
The following code will work fine, but it only adds the comma at end of the last value also. How can I remove that?
fields = $('.wrap').find('.text');
var data = '';
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value + ',';
}
});
alert(data);
JSFiddle:
http://jsfiddle.net/cn5Gt/
I always use arrays for these kind of things:
var fields = $('.wrap').find(".text[value!='']");
var data = [];
fields.each(function() {
data.push($(this).val());
});
alert(data.join(','));
You can push elements on array than just use join() method.
fields = $('.wrap').find('.text');
var data = [];
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data.push(value);
}
});
alert(data.join());
Try the code below, using the i which is the loop index and test against the length of the jQuery object.
fields = $('.wrap').find('.text');
var length = fields.length;
var data = '';
fields.each(function(i) {
var value = $(this).val();
if ( value != '' ) {
if(i === length-1) { //The last one
data += ' ' + value;
} else {
data += ' ' + value + ',';
}
}
});
Updated fiddle
You could just remove the final character afterwards?
data = data.substr(0, data.length - 1);
http://jsfiddle.net/cn5Gt/3/
Simplest of all:just replace your last line with the below line
alert(data.slice(0,-1));//where data is string
http://jsfiddle.net/cn5Gt/7/
DOC MDN : slice
How about something like this:
var data = $('.wrap').find('.text')
.map(function(i,el){ return el.value || null; })
.get().join(", ");
Demo: http://jsfiddle.net/cn5Gt/11/
jQuery's .map() method will "Pass each element in the current matched set through a function, producing a new jQuery object containing the return values." You can still include your if ( value != '' ) { test in the callback function because if your function returns null or undefined then .map() will not use that particular value. (I've used || null above as a shortcut to an if/else structure.)
Call .get() (or .toArray()) on the result and you'll have an actual array, which means you can then use the Array .join() method to form a string with the values comma separated.
If you need to do other processing on each item besides just getting the value you could stick with the .each() loop and add the values to an array that you then join after the loop (like some of the other answers), or just use the string .slice() method to remove the trailing comma and space characters.
Try this:
Using the length function to determine the position of the each
var fields = $('.wrap').find('.text');
var len = fields.length;
var data = '';
fields.each(function(index, element) {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value;
if (index != len - 1) {
data += ',';
}
}
});
alert(data);
I have a javascript function ...
function check_val(name, cat)
{
alert(cat);
var val = name.indexOf('[');
if (val == -1){
//$('input[type="checkbox"][value='+ name + ']')[0].click()
val = '"' + name + '"'
type = "'" + cat + "'"
$.get(url,{'ajaxtype':'content', type : val}, function(data{$('#search_container').html(data);$('#rotator').hide();});
}
}
when i call this function with argument say check_val('xyz','pqr')
The problem is when I check the request.get parameter I am getting
<QueryDict: {u'type': [u'"xyz"'], u'ajaxtype': [u'content']}>
instead of
<QueryDict: {u'pqr': [u'"xyz"'], u'ajaxtype': [u'content']}>
Build the object beforehand and use array subscript syntax:
var requestData = { 'ajaxtype': 'content' };
requestData[type] = val;
$.get(url, requestData,
function(data{$('#search_container').html(data);$('#rotator').hide();});
Instead of {'ajaxtype':'content', type : val} try {'ajaxtype':'content', "'" + cat + "'" : val}.
This way JS should know that it's not key name but variable.
I have multiple checkbox in my page. i want to retrieve its values if checked.
Here is HTML Code..
<input name="ctl1189" type="checkbox" id="chkTicket_189310" class=" chkTicket" value="189310">
<input name="ctl1190" type="checkbox" id="chkTicket_189311" class=" chkTicket" value="189311">
And So on..
Javascript Code:
function updateTicketAction() {
var allUpdatedVendorTickets = $('.chkTicket').filter(function() { return this.value != $input.is(':unchecked'); });
var sFinalUpdateList = '';
allUpdatedVendorTickets.each(function() {
var ids = $(this).attr('id').split('_')[1];
sFinalUpdateList += ((sFinalUpdateList == '') ? '' : '|') + ids + ',' + $(this).val();
});
alert(sFinalUpdateList);
}
function updateTicketAction() {
var sFinalUpdateList = '';
$("input.chkTicket:checked").each(
function() {
var ids = $(this).attr('id').split('_');
var id = ids[1];
sFinalUpdateList += ((sFinalUpdateList == '') ? '' : '|') + id + ',' + $(this).val();
}
);
alert(sFinalUpdateList);
}
http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html
I just created a fiddle. Look in the JavaScript console for the resulting object, which you can then further process.
Code:
var checkedCheckboxes = $('.chkTicket:checked'),
results = {};
checkedCheckboxes.each(function () {
var key = $(this).attr('id').split('_')[1];
results[key] = $(this).val();
});
function alertResults(results) {
var text = '', sep = '';
$.each(results, function (key, value) {
text += sep + key + '=' + value;
sep = '|';
});
alert(text);
}
alertResults(results);
console.log(results);
try this code
var collect='';
$('input:checked').each(function(i,e){
collect+=(collect===''? $(e).attr('name')+'='+$(e).val():','+$(e).attr('name')+'='+$(e).val());
alert(collect);
})
Here is a jsfiddle snippet that returns all checked inputs..
One question though, why do you split your id-attribute when you have your id stored in value-attribute? Anyways, hope this works for you!
function updateTicketAction() {
var allUpdatedVendorTickets = $('.chkTicket:checked');
var sFinalUpdateList = '';
allUpdatedVendorTickets.each(function () {
sFinalUpdateList += ((sFinalUpdateList == '') ? '' : '|') + $(this).val();
});
alert(sFinalUpdateList);
}
Or you can use map():
var el = $('input[type=checkbox]:checked').map(function(i,e){
var id = $(e).attr('id').replace('chkTicket_', '');
var val = $(e).val();
return {
'id' : id,
'value' : val
}
});
console.log(el[0].id);
Your filter function is wrong.
this.value != $input.is(':unchecked');
You're comparing a .value property (string) to the return value of the .is jQuery method (boolean). It's similar to:
'value' != !true //checked
'value' != !false //unchecked
Both will always return true - unless value is 0 or an empty string which evaluates to a falsy value and the right side of the expression evaluates to false, for which the != different operator will return false.
So, your filter's callback doesn't filter anything at all, except taking out checked boxes with value 0 or no value (which is unintentional).
You can avoid using a filter function by using the :checked selector:
var allUpdatedVendorTickets = $('.chkTicket:checked');
Now you'll have a jQuery object containing only the checked .chkTicket, much better.
Next thing, you're making bad use of strings.
"189310,189310|189311,189311"
That's what your function is generating. Every time you need to manipulate those results, you'll have to split the string at |, creating a new array. It's much better to store it as an array already.
var sFinalUpdateList = [];
Assuming your keys and values are always the same as in your example, you should store them only once as well.
allUpdatedVendorTickets.each(function() {
sFinalUpdateList.push(this.value);
});
This will generate a much more clean and maintainable array with only the checked boxes' values:
sFinalUpdateList =>
[0] -> "189310"
[1] -> "189311"
You can obtain their IDs by appending chkTicket_ to those values.
jsFiddle
I think it's fairly clear what I want to do here:
var viewnames = {};
viewnames['region-a'] = "Region A";
viewnames['region-b'] = "Region B, partial";
viewnames['region-c'] = "Region C";
function loadView(view_name) {
alert('view_name: ' + view_name);
alert('viewname: ' + viewnames.view_name);
document.getElementById("viewtitle").innerText = view_name;
}
But if I call this with view_name as region-a the alert says viewnames.view_name is undefined. What is the problem?
You must use viewnames[view_name] inside your function loadView
You need to index it by name, e.g. viewnames[view_name]
Access it by associative array index (viewnames[view_name]). Please DO NOT use an eval construct (eval("var tmp = viewnames." + view_name + ";")).