krishan krishan - 7 months ago 20
Javascript Question

Not getting value of text input field

I am trying to validate my inputs using Jquery. Partial code, which is relevant to question is below. Don't worry about clicking to individual that's the other option. But I need to get text value in alert and hence show add button when the field is not blank. I cant change HTML as it is generated by Django.



$(document).ready(function() {
var rad_ind = $("label:contains('Individual')");
var rad_com = $("label:contains('Company')");
var co_name = $("#id_emp_coname").closest("p");
var add_button = $("[value^='Add']");

$("p:has(input)").hide();
add_button.hide();


rad_com.click(function() {
$("p:has(input)").hide();
co_name.show();
co_name.change(function() {
alert(co_name.val());
if (co_name.val() == null || co_name.val() == "") {
add_button.hide();
} else {
add_button.show();
}
});
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<p>
<label for="id_ind_or_company_0">Is employer an individual or company:</label>
<ul id="id_ind_or_company">
<li>
<label for="id_ind_or_company_0">
<input id="id_ind_or_company_0" name="ind_or_company" type="radio" value="True" />Individual</label>
</li>
<li>
<label for="id_ind_or_company_1">
<input id="id_ind_or_company_1" name="ind_or_company" type="radio" value="False" />Company</label>
</li>
</ul>
</p>
<p>
<label for="id_emp_coname">Company Name:</label>
<input id="id_emp_coname" maxlength="87" name="emp_coname" type="text" />
</p>
<input type="submit" value="Add" />





My question is why I am not getting the text value with .val()

I am getting blank alert. And therefore the add(submit) button does not work as expected. Can somebody tell me where am I making a mistake.

I know there are tons of pages on this and have been reading but cant find out what mistake I am doing.

Thanks,

Krishan

Answer

You have to use .val() on the input, not on the closest p element.

Try

$("#id_emp_coname").val();

I tested on a CodePen and it worked, change this on your code:

$(document).ready(function() {
  var rad_ind = $("label:contains('Individual')");
  var rad_com = $("label:contains('Company')");
  var co_name = $("#id_emp_coname"); //Changed here
  var add_button = $("[value^='Add']");

  $("p:has(input)").hide();
  add_button.hide();


  rad_com.click(function() {
        $("p:has(input)").hide();
        co_name.show();
        co_name.change(function() {
          alert(co_name.val());
          if (co_name.val() == null || co_name.val() == "") {
            add_button.hide();
          } else {
            add_button.show();
          }
      });
  });
});
Comments