1

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>' );
}

3 Answers 3

2

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('][') + ']');
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Hi, it will not work with 'Payments.0.1.Amount' and with input without array, for example -> 'Payments'. You can see my own answer, there are solved all this issues :)
for this you need to concat $nameArr[3]
0

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.