Reputation: 1771
This is my HTML form. I am trying to show errors if the fields are left blank. Only the select field shows the error if left blank and others do not. I tried to manipulate the DOM from firebug but even there, i could not add the error div in email, password field.
<form name="sentMessage" id="RegisForm" novalidate>
<div class="control-group form-group">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="controls">
<input type="email" class="form-control " name="email" id="email" placeholder="Email" value="{{ old('email') }}">
</div>
<div class="controls">
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<div class="controls">
<input type="password" class="form-control" name="password_confirmation" id="re-passd" placeholder="Retype Password">
</div>
<div class="control-group form-group">
<div class="controls">
<select name="type" class="form-control" id="type">
<option value="" selected="selected">Account Type</option>
<option value="Buyer">Buyer</option>
<option value="Seller">Seller</option>
<option value="Agent">Agent</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Create Account</button>
<!-- For success/fail messages -->
</div>
</form>
Here is my js code
$(document).ready(function () {
"use strict";
$('#RegisForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: '/auth/register',
data: $(this).serialize(),
success: function (msg) {
window.location.replace('dashboard');
},
error: function (errors) {
$('.text-danger').remove();
$.each(errors.responseJSON, function (fieldName, error) {
var fieldNameArray = fieldName.split('.'),
inputName = '';
$.each(fieldNameArray, function (index, value) {
inputName += "\\[" + value + "\\]";
});
inputName = inputName.replace('\\[', '').replace('\\]', '');
$('#' + inputName ).before('<div class="text-danger">' + error[0] + '</div>');
});
}
});
});
});
after I did console.log(inputName + ' ' + error[0] );
I got something like this:
type The type field is required.
email The email field is required.
password The password field is required.
Upvotes: 1
Views: 124
Reputation: 8523
Try selecting with names instead of IDs.
$("[name='"+inputName+"']")
I generally avoid dynamically selecting with IDs because of weird behaviors like this. I wish I knew more specifics about your case- it's possible there are other elements with the same IDs that is getting selected instead of your elements (since IDs are supposed to unique).
Upvotes: 1