roi
roi

Reputation: 7

How to refer to the input field by name

How should I refer to the input field in my JS code?

input[name="email"]

Is not quit right.

$("#reg-form").find('input[name="email"]').parent("").addClass('has-error');
<div class="form-group">
    <label for="email">EMAIL</label><span> *</span>
    <input type="text" class="form-control" name="user_details[email]">
    <div class="help-block"></div>
    <!-- errors will go here -->
</div>

Upvotes: 0

Views: 109

Answers (5)

Dhara Parmar
Dhara Parmar

Reputation: 8101

Simply use:

$('input[name="user_details[email]"]')

Upvotes: 0

Justinas
Justinas

Reputation: 43479

There is no element named email, your input name is user_details[email].

Also there is no need for empty selector in .parent()

$(document).ready(function() {
  $("#reg-form")
    .find('input[name="user_details[email]"]')
    .parent()
    .addClass('has-error')
  ;
});
.has-error label {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reg-form">
  <div class="form-group">
    <label for="email">EMAIL</label><span> *</span>
    <input type="text" class="form-control" name="user_details[email]">
    <div class="help-block"></div>
    <!-- errors will go here -->
  </div>

</form>

Upvotes: 0

Tinmar
Tinmar

Reputation: 370

$('input[name="user_details\\[email\\]"]');

Try like this.

You don't have input with name="email" attribute.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

Your input is not named 'email', you need to include the full name while remembering to escape the square brackets. Try this:

$("#reg-form").find('input[name="user_details\\[email\\]"]').parent().addClass('has-error');

Also note that "" isn't a valid selector for parent().

Upvotes: 2

Jo&#227;o Pedro
Jo&#227;o Pedro

Reputation: 546

Try this:

.find("input[type='text']")

Upvotes: 0

Related Questions