I tried to display the Laravel 5.5 Ajax error Validation using jQuery automatically,
When for single field it was work, to use following code:
$.each(response.errors, function (key, value) {
el.find('input[name="'+key+'"] , select[name="'+key+'"] , textarea[name="'+key+'"]').parent().append('<div class="error right-align pink-text text-mute">'+value+'</div>');
});
The code above will append an error message to each element based on selector.
But if I use array field, for example <input type="text" name="start_date[]" />
Then I got following error validation:
{"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."]}}
So my javascript couldn't find the elements start_date.0
How to select the element using jQuery with that response ? (start_date.0 , start_date.1)
thanks for all the answer, I end this problem by using id attribute, so my html tag should be like this <input type="text" id="start_date.0" name="start_date[]" />
Since jquery doesn't allow dot "." pattern in selector, My selector should be like this
el.find('input[id="select_date.0"]')
So My code should be:
$.each(response.errors, function (key, value) {
el.find('input[id="'+key+'"],input[name="'+key+'"] , select[name="'+key+'"] , textarea[name="'+key+'"]').parent().append('<div class="error right-align pink-text text-mute">'+value+'</div>');
});
Use errors['start_date.0'] instead errors.start_date.0
var myObj = {"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."]}};
console.log(myObj.errors['start_date.0']);
Using start_date.0 it tries to get element 0 in object start_date, but you have this start_date.0 as element of errors so use bracket [ ] to treat start_date.0 as element of errors
var response = {"message":"The given data was invalid.","errors":{"start_date.0":["The start_date.0 field is required when availability is 0."],"start_date.1":["The start_date.1 field is required."],"end_date.0":["The end_date.0 field is required."],"end_date.1":["The end_date.1 field is required."],"dob":["Date of birth is required."]}};
$.each(response.errors, function (key, value) {
var name = $("input[name='"+key+"']");
if(key.indexOf(".") != -1){
var arr = key.split(".");
name = $("input[name='"+arr[0]+"[]']:eq("+arr[1]+")");
}
name.parent().append('<div class="error right-align pink-text text-mute">'+value[0]+'</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type="text" name="start_date[]" value=""></div>
<div><input type="text" name="start_date[]" value=""></div>
<div><input type="text" name="end_date[]" value=""></div>
<div><input type="text" name="end_date[]" value=""></div>
<div><input type="text" name="dob" value=""></div>
error: function(data){
var response = JSON.parse(data.responseText);
var errorString = '<ul style="list-style: none;">';
$.each( response.errors, function( key, value) {
errorString += '<li><small>' + value + '</small></li>';
});
errorString += '</ul>';
$("#errors").html(errorString);
}
Related
I have a json like this from a url. (Example: http//www.somedomain.com/controller/json)
[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]
I would like to import these values to an html file's form input fields with jQuery. The form is like this:
<input id="id" type="text" value="12">
<input id="event" type="text value="LOGOUT SUCCESS">
...
Is there any simple solution for this?
Since the id of each input field is the same as the name in each name/value pair, a for..in loop can do this very easily.
$.getJSON("http//www.somedomain.com/controller/json", function(json) {
json = json[0]; //the object is in the first element of the wrapping array
for (name in json)
$("form").append('<input id="'+name+'" type="text" value="'+json[name]+'"/>');
});
If you wish to just set the values of an already existing form:
$.getJSON("http//www.somedomain.com/controller/json", function(json) {
json = json[0];
for (name in json)
$("#"+name).val(json[name]);
});
You can unserialize your json :
json_string = "[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]";
var arr_from_json = JSON.parse( json_string );
And then loop on the attributes :
$.each( arr_from_json, function(i, n){
$("#"+i).attr("value",n);
});
Parse the JSON to an object. You can then iterate through it and create or set the input elements. Although you asked for it in the question, this is so trivial that there is little point in using jQuery for it (You Might Not Need jQuery).
If you wish to create the inputs:
var json = '[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]',
data = JSON.parse(json)[0];
for (var key in data) {
if (data.hasOwnProperty(key)) {
var i = document.createElement("input");
i.setAttribute('type',"text");
i.setAttribute('name',key);
i.setAttribute('value',data[key]);
document.body.appendChild(i);
}
}
If you just wish to set the values:
var json = '[{"id":"12","event":"LOGOUT SUCCESS","ip":"0.0.0.0","date":"2016.04.08 15:44"}]',
data = JSON.parse(json)[0];
for (var key in data) {
if (data.hasOwnProperty(key)) {
document.getElementsByName(key)[0].value = data[key];
//or document.getElementsById("#"+key)[0].value = data[key];
}
}
<input type="text" name="id" value="" />
<input type="text" name="event" value="" />
<input type="text" name="ip" value="" />
<input type="text" name="date" value="" />
I have 2 input fields inside a div within a form element like this
<form>
<div id="si-goal-section">
<div class="si-goal-container">
<input type="text" class="si-input goal-icon" name="goal-icon">
<input type="text" class="si-input goal-title" name="goal-title">
</div>
</div>
<div>
<button type="button" id="goal-btn">Add goal</button>
</div>
</form>
When i click on the button "Add goal" i am appending a new "si-goal-container" div. This is the script for that
$('form #goal-btn').click(function() {
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" name="goal-icon"><input type="text" class="si-input goal-title" name="goal-title"></div>')
})
i then create an array variable in JS and collect and pass the form data into it like this
var data_to_send = []
$('form').find('.si-input').each(function() {
if($(this).hasClass('goal-icon')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
if($(this).hasClass('goal-title')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
})
So this approach will not work because the name fields are the same and the values just get over written. What else could be done here so i could store the appended data in the array and access it later in the php side ?
i tried something like this
var data_to_send = {}
data_to_send.goal = []
$('form').find('.si-input').each(function() {
if($(this).attr('name') != undefined) {
data_to_send.goal.push({
'goalIcon': $(this).find('.goal-icon').val()
'goalTitle': $(this).find('goal-title').val()
})
}
})
But this too doesn't give me the required o/p i am looking for. I need my data_to_send array to look something like this in the ajax call.
...
data_to_send['bannerImage']:
data_to_send['goalName']:
data_to_send['goalIcon'][0]:
data_to_send['goalTitle'][0]:
data_to_send['goalIcon'][1]:
data_to_send['goalTitle'][1]:
...
What would be the right way to append the fields and store it into the array ? I i am using serialize() then how do i use it only for particular fields ?
Give an id to your first input elements of si-goal-section as below:
<div class="si-goal-container">
<input type="text" id="goalicon_1" class="si-input goal-icon" name="goal-icon"/>
<input type="text" id="goaltitle_1" class="si-input goal-title" name="goal-title"/>
</div>
now in JS on click event of button fetch the ids for title and icon from last si-goal-section and split it based on _ as below:
$('form #goal-btn').click(function() {
var goalIconID=parseInt($(".si-goal-container:last .goal-icon").attr('id').split("_")[1])+1;
//fetch .goal-icon's and goal-title's id by from last .si-goal-container and add + 1 [increment id]
var goalTitleID=parseInt($(".si-goal-container:last .goal-title").attr('id').split("_")[1])+1;
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" id="goalicon_'+goalIconID+'" name="goal-icon"><input type="text" id="goaltitle_'+goalTitleID+'" class="si-input goal-title" name="goal-title"></div>');
//add id to the newly created elements
})
Thus you can now have unique elements and push it to your array as values
DEMO
Try this : You can iterate over si-goal-container div and then read si-input input fields inside it. Store values in map and add map to array as shown below
$(document).ready(function(e) {
$('form #goal-btn').click(function() {
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" name="goal-icon"><input type="text" class="si-input goal-title" name="goal-title"></div>')
});
$('form #value-goal-btn').click(function() {
var data_to_send = new Array();
$('form').find('div.si-goal-container').each(function() {
var container_data = {};
$(this).find('.si-input').each(function(){
container_data[$(this).attr('name')] = $(this).val();
});
data_to_send.push(container_data);
});
alert(JSON.stringify(data_to_send));
});
});
JSFiddle Demo
For some reason I have HTML like this -
<input type="text" value="100" name="ProductPrice[1][]">
<input type="text" value="200" name="ProductPrice[2][]">
<input type="text" value="300" name="ProductPrice[3][]">
<input type="text" value="400" name="ProductPrice[4][]">
And process this on server side like this -
foreach ($_POST['ProductPrice'] as $ProductId => $Price)
{
//$Price = Price[0];
}
This works fine for me. However my problem is with validating this on client side with jquery.
I tried $.each($("input[name='ProductPrice[][]']"), function(key, value) {
but nothing seems to be working. How can I read those input boxes using the NAME property.
You can use the "Attribute Starts With Selector":
$("[name^=ProductPrice]").each(function() {
var name = $(this).attr("name");
var value = $(this).val();
// Do stuff
});
It will select all elements whose name starts with "ProductPrice"
I just can't get this to work.
HTML:
<form action="index.php?page=n0402" method="post" Name="AddPolish" >
<div id="frmBrandInput">
<label for="frmBrand">Brand name:</label>
<input type="text" name="frmBrand" size="50" onkeypress="BrandCheck();" maxlength="100" id="frmBrand" value="Enter existing or new brand" />
<span id="frmBrand_Status"></span>
</div>
</form>
Javascript:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
alert(jsBrandName);
}
Why can't I get the value of frmBrand into jsBrandName? If I use Firebug to debug, I get the following in my Watch list:
Watch Expression:
document.forms["AddPolish"]["frmBrand"];
Result:
NodeList[input#frmBrand property value = "G" attribute value = "Enter existing or new brand", input#frmBrand attribute value = ""]
I can see the value "G" which is what I entered in the input field. What am I doing wrong in passing it into the jsBrandName?
The output you got implies that there are two inputs with name="frmBrand" in the form. You need to index them, e.g.
var jsBrandName = document.forms["AddPolish"]["frmBrand"][0].value;
to get the value of the first one.
I am trying to pass an array to PHP via Ajax, but the array is being passed as an empty string. This is my code when creating the array:
var params = new Array();
var inputs = new Array();
inputs = $(":input");
$.each(inputs, function(key, value) {
params[value.id] = value.value;
});
alert(params);
Before that there are around 20 inputs that look like this:
<input name="first_name" id="first_name" type="text" class="medium"/>
<input name="last_name" id="last_name" type="text" class="medium"/>
The alert(params) is just giving me an empty string. However, alert(params['first_name']) actually gives me the first_name input value.
Why isn't the array going through?
Can you try this -
$(document).ready(function() {
var params = new Array();
var inputs = $(":input");
$.each(inputs, function(key, value) {
//I guess the problem was that params is array and your id's were strings
//array's elements are arr[0], arr[1],
//not like arr[firstname], arr[lastname], ...
params[value.id] = value.value;
});
alert(params);
});
//moved everything inside $(document).ready
with this -
<input name="first_name" id="0" value="1" type="text" class="medium"/>
<input name="last_name" id="1" value="2" type="text" class="medium"/>
<!-- Changed id's from string to numbers. -->
Update:
Also, try this it might help you understand whats going on -
$(document).ready(function() {
var params = {}; //use object instead of array
var inputs = $(":input");
$.each(inputs, function(key, value) {
params[value.id] = value.value;
});
for(var prop in params) {
alert(prop + " = " + params[prop]);
}
});
Notice: params is an object now not an array.
With this -
<input name="first_name" id="firstname" value="Your first name." type="text" class="medium"/>
<input name="last_name" id="lastname" value="Your last name." type="text" class="medium"/>
You can't simply pass a variable to the server, you need to serialize it into name, value pairs, or use JSON.
I'm slightly unsure what you're trying to accomplish by creating an array in Javascript like this.
Your best bet is probably to use the JQuery command serialize then grab the data using $_GET