Reputation: 61
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button.When yes radiobutton is clicked. the quantity textbox should not be empty.but it can be empty if no radiobutton is clicked.This functionality should work when submit button is clicked with yes radiobutton is selected.any ideas? MY VIEW:
<HTML>
<head>
radio
</head>
<body>
<form id=radio>
Add to electronic <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
<label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>
im new to mvc and javascript help me with javascript code too.and the way i should link it with my view. Javascript:
function validate(_this) {
if ($(_this).attr('id') == "yes") {
$('#dir').attr('required');
alert("Text Box required");
}
else {
$('#dir').removeAttr('required');
alert("Text Box not required");
}
}
Upvotes: 0
Views: 2237
Reputation: 845
HTML Required
attribute can be really helpful in such scenarios.
Go through this Link for more information.
Also, Check Jquery Validator if you need more customization.
<HTML>
<head>
radio
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function validate(_this)
{
if($(_this).attr('id') == "yes")
{
$('#quantity').attr('required');
alert("Text Box required");
}
else
{
$('#quantity').removeAttr('required');
alert("Text Box not required");
}
}
</script>
</head>
<body>
<form id=radio>
Add to electronic
<input type="radio" name="yes" id="yes" onchange="validate(this)"/>Yes
<input type="radio" name="yes" id="no" onchange="validate(this)"/>No<br />
<label>Quantity</label>
<input type="text"size="25" name="quantity"id="quantity" required/>
<button type=submit name=insert>insert</button>
</body>
</html>
Upvotes: 1
Reputation: 506
$(function() {
$("#radio").submit(function() {
if ($('#yes').is(':checked') && !$.trim($('#quantity').val())) {
alert("Please input the quantity.");
return false;
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form id=radio>
Add to electronic <input type="radio" name="yes" id="yes" />Yes<input type="radio" name="yes" id="no" />No<br />
<label>Quantity</label><input type="text" size="25" name="quantity" id="quantity" />
<button type=submit name=insert>insert</button>
</form>
</body>
</html>
Upvotes: 1