I am trying to validate an Hidden filed in MVC using javascript. I build a star rating feedback I want the validation to failed when the user have not selected a rating. I commented ‘ignore: “:hidden’ in the jquery.validate.js file but I am still having the same issue
@Html
<div class="col-md-10 col-sm-10">
<div style="display:inline-block;" id="rateYo"></div>
<input type="hidden" name="rating" id="rating_input" />
</div>
<button type="submit" class="btn btn-primary btn-lg" id="btnSubmit"</button>
Javascript code
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.2.0/jquery.rateyo.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.2.0/jquery.rateyo.min.js"></script>
// Setting the star value
$(function () {
$("#rateYo").rateYo({
onSet: function (rating, rateYoInstance) {
rating = Math.ceil(rating);
$('#rating_input').val(rating);
}
});
});
// Validating when button is clicked
$(function () {
$('input[id$=btnSubmit]').click(function (z) {
var x = document.getElementById("rating_input");
if (x.val == 0) {
alert('Rating is Required');
z.preventDefault();
}
});
});
2
Answers
Since you are using
getElementById
to get therating_input
DOM Node, you have to use the DOM properties of that Node to access the value of the input.$("someSelector").val()
is how you would retrieve the value attribute of a jQuery object..val()
is a jQuery specific function that is only available when you retrieve DOM elements via jQuery –$("#rating_input").val()
https://api.jquery.com/val/#valHowever, DOM Nodes do not have a
val
attribute. Instead,input
elements, in particular, have avalue
attribute. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#AttributesSo, try
if (x.value === 0)
.Please use var
x = $('input#rating_input').val()
to get hidden value.