JavaScript redirect to next page error - javascript

I am totally noob for javascript, I just started to learn and I stuck.
I am working on ASP.NET app and in my view I create JavaScript function that need to check If checkbox is checked and It need to redirect to next View either if option is Yes or No.
For option Yes work perfectlly, but when I select "No" it display required message and in console I get error
Uncaught TypeError: Cannot read property 'checked' of null
at YesNoChecked (CreateManually:940)
at HTMLButtonElement.onclick (CreateManually:886)
So my code so far
function YesNoChecked() {
var Yes = document.getElementById('Yes');
var No = document.getElementById('No');
if (document.getElementById('Yes').checked ==true) {
console.log('Successfull');
}
if (document.getElementById('No').checked==false) {
console.log('Error');
}
}
HTML
<div class="form-group">
#Html.LabelFor(model => model.Chapel, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "Yes", new { #class = "styled", htmlAttributes = new { #checked = "true" } })
Yes
</label>
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "No", new { #class = "styled", htmlAttributes = new { #checked = "true" } })
No
</label>
#Html.ValidationMessageFor(model => model.Chapel, "", new { #class = "text-danger" })
</div>
</div>
So basically, either choice is selected "No" or "Yes" it need to redirect to next View, but when choice is selected to "No" it need to hidden element called Chapel.
Please help guys :/
If you need some more code let me know, I will publish
UPDATE
Button click
<button type="submit" onclick="YesNoChecked()" class="btn btn-success"><i class="icon icon-check position-left"></i> Proceed to Payment</button>
Radiobutton Yes HTML
<input class="styled" htmlattributes="{ checked = true }" id="Chapel" name="Chapel" type="radio" value="Yes" autocomplete="off">
Radiobutton No HTML
<input checked="checked" class="styled" htmlattributes="{ checked = true }" id="Chapel" name="Chapel" type="radio" value="No" autocomplete="off">

Your code to generate a check box is wrong. At least in asp.net core you should receive the error "No overload for method 'CheckBoxFor' takes 3 arguments"
If Chapel in your model is a bool property, this creates a checkbox for it:
#Html.CheckBoxFor(m => m.Chapel, new { id="Yes", #class = "styled", htmlAttributes = new { #checked = "true" } })
If you want radio buttons:
#Html.RadioButtonFor(model => model.Chapel, true, new { id = "Yes", #class = "styled" }) Yes <br/>
#Html.RadioButtonFor(model => model.Chapel, false, new { id = "No", #class = "styled" }) No
This will properly create two html elements for you with the Ids Yes and No and will let your js work:
function YesNoChecked() {
var Yes = document.getElementById('Yes');
var No = document.getElementById('No');
if (Yes.checked ==true) {
console.log('Successfull');
}
if (No.checked==false) {
console.log('Error');
}
}

Related

Cascading population of a mvc dropdown

I have 2 DropDowns in an MVC application. Trying to populate the second one based on the first one's chosen value (Cascading)..
Since I am rather new to MVC this is giving me a little problem..
This is how ot looks in my View..
I am getting the data based on the selection in the first DropDown
This is the JS code for retriving the data..
<script type="text/javascript">
$('#AllShips').change(function () {
var selectedShip = $("#AllShips").val();
console.log(selectedShip);
var arrivalSelect = $('#AllShipArrivals');
arrivalSelect.empty();
if (selectedShip != null && selectedShip != '') {
$.getJSON('#Url.Action("GetArrivals")', { ShipID: selectedShip }, function (arrivals) {
console.log(arrivals);
if (arrivals != null && !jQuery.isEmptyObject(arrivals))
{
arrivalSelect.append($('<option/>', {
value: null,
text: ""
}));
$.each(arrivals, function (index, arrival) {
console.log(arrival.Value);
console.log(arrival.Text);
arrivalSelect.append($('<option/>', {
value: arrival.Value,
text: arrival.Text
}));
});
};
});
}
});
Here is my HTML
<div class="col-lg-2 form-group">
#Html.LabelFor(model => model.AllShips, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#if (Model.AllShips != null)
{
#Html.DropDownListFor(model => model.ShipID, Model.AllShips, new { #class = "form-control", id = "AllShips" })
#Html.ValidationMessageFor(model => model.ShipID, "", new { #class = "text-danger" })
}
</div>
</div>
<div class="col-lg-2 form-group">
#Html.LabelFor(model => model.AllShipArrivals, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#if (Model.AllShipArrivals != null)
{
#Html.DropDownListFor(model => model.ArrivalId, Model.AllShipArrivals, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ArrivalId, "", new { #class = "text-danger" })
}
else
{ #Html.DropDownListFor(model => model.ArrivalId, null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ArrivalId, "", new { #class = "text-danger" })}
</div>
</div>
Still the second DropDown is not changing (initially I populate it with a list of all Arrivals, yes I know..not a good option)
Any idea what I am doing wrong here??
Thanks for the HTML, it is what I suspected. In your JS your are referencing 2nd DDL by var arrivalSelect = $('#AllShipArrivals'); but there is no such element (it is, but this is just a label), instead you should use:
var arrivalSelect = $('#ArrivalId');
Make 'PartialView' or 'ViewComponent' for the second Dropdown, do ajax call on changing selection in the first dropdown, choose data depending on the value you passed during the ajax call, pass the data into your partial view and return it.
Something like
public IActionResult SecondDropdownPartial(int selectedShip)
{
var data = GetSomeData(selectedShip);
return Partial("ViewName", data);
}
In js 'success' you get your view in response. Replace it on the page with
$('#container').html(response);
for example.
More information : Rendering Partial Views using ajax
edited
try making the value to be empty string rather than null
emptyStr="";
arrivalSelect.append('<option value="${emptyStr}"> ${emptyStr} </option>');
arrivalSelect.append('<option value="${arrival.Value}"> ${arrival.Text} </option>');

Div class show after refresh page

I have a radio button which has option to show or hide div content defending of radiobutton state, but after i fill the form and I press F5 the previous state stay, but div class is dissapear.
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
HTML
<div class="form-group">
#Html.LabelFor(model => model.Chapel, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "Yes", new { #class = "styled", htmlAttributes = new { #checked = "true", #name = "Chapel"} }) Yes
</label>
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "No", new { #class = "styled", htmlAttributes = new { #checked = "true" , #name = "Chapel" } })
No
</label>
#Html.ValidationMessageFor(model => model.Chapel, "", new { #class = "text-danger" })
</div>
</div>
Any comment, where It should be problem ?
After page refresh if you want to show a div then you need to add that code outside click function.
$(document).ready(function () {
// Add logic when to show this div
$("div#hideChapel").show(); // Here you go
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});

Disable require message when radiobutton is selected to No

I am trying to disable required message when I checked radio button "No"
However when I submit form nothing happen, it's just redirect to same page and required message is display
Updated code
//hide/show chapela Yes/No
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
$(document).ready(function () {
var test = $(this).val();
if(test == 'No'){
$("hideChapel").prop("required", false);
}
else {
$("hideChapel").prop("required", true);
}
});
<div class="form-group">
#Html.LabelFor(model => model.Chapel, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "Yes", new {id="Yes", #class = "styled", htmlAttributes = new { #checked = "true"} })
Yes
</label>
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "No", new {id="No", #class = "styled", htmlAttributes = new { #checked = "true" } })
No
</label>
#Html.ValidationMessageFor(model => model.Chapel, "", new { #class = "text-danger" })
</div>
</div>
RENDERED HTML
<label class="radio-inline">
<div class="choice" id="uniform-No"><span class="checked"><input checked="checked" class="styled" htmlattributes="{ checked = true }" id="No" name="Chapel" type="radio" value="No" autocomplete="off"></span></div>
No
</label>
<input class="styled" htmlattributes="{ checked = true }" id="Yes" name="Chapel" type="radio" value="Yes" autocomplete="off">
You need to do it on form submit, you're currently setting the required attr on document load and on input click. Achieve like this:
$('form').submit(function(e)
{
e.preventDefault(); //stop form submitting straight away
var radio = $('.my-radio');
if (radio.val() === 'foo') {
//disable require msg e.g. (this is an example - not a copy + paste)
$('form input').each(function()
{
$(this).removeAttr('required')
})
}
$(this).submit()
})
ref:
https://api.jquery.com/removeAttr/

ASP.NET MVC jQuery JSON result redirecting URL

Using MVC/Json/Jquery.
Using form to create a new "group".
Form is on ~Group/Manage, posting form to ~Group/Create
Whilst working on this, returning Json result was working fine, handling in Jquery, no URL redirection.
Now, everytime I run it, it redirects me to ~Group/Create and displays the Json result.
Controller Group/Create
[HttpPost]
public ActionResult Create([Bind(Include="name,description")] GroupModel groupmodel)
{
...
return Json(new { success = true, message = groupmodel.name }, JsonRequestBehavior.AllowGet);
}
Form
<form id="frm_createGroup" action="/Groups/Create" method="post">
<h2>Create Group</h2>
<div class="form-group">
#Html.LabelFor(model => model.name, new { #for = "name" })
#Html.TextBoxFor(model => model.name, new { #class = "form-control", #placeholder = "Group Name" })
#Html.ValidationMessageFor(model => model.name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.description, new { #for = "description" })
#Html.TextBoxFor(model => model.description, new { #class = "form-control", #placeholder = "Group Description" })
#Html.ValidationMessageFor(model => model.description)
</div>
<span id="createGroupMessage"></span>
<button type="submit" class="btn btn-primary pull-right">Create</button>
</form>
Jquery to handle form
$(document).ready(function (){
$('#navGroups').makeActiveMenuItem();
var options = {
success: groupCreateSubmitted
,error: groupCreateError
}
$('#frm_createGroup').ajaxForm(options);
});
function groupCreateSubmitted(responseText, statusText, xhr, $form) {
if (responseText.success)
{
$('#createGroupMessage').html = "Group Created";
}
else
{
$('#createGroupMessage').html = responseText.message;
}
}
To be clear, I don't want URL redirection, I just want the Jquery to catch the return (it was before, have no idea why its changed...)
Thanks!
removed
,error: groupCreateError
working now...form bind was failing.

how to set id to Html.TextBox item on MVC

Im trying to catch the textbox element by javascript, in order to put text into it.
so how to set id to the textbox ??
<tr>
// Id to this textbox
<td>#Html.TextBoxFor(item => item.OperationNo)</td>
</tr>
and then to put text into it by JS
//
document.getElementById("Textbox id").Text= " Some text " ;
You can set ID of a textbox like this.
#Html.TextBoxFor(item => item.OperationNo, new { id = "MyId" })
OR
#Html.TextBoxFor(item => item.OperationNo, htmlAttributes: new { id = "MyId" })
Output:
<input ... id="MyId" name="OperationNo" type="text" />
You can use below code for resolve that problem:
function steVal() {
document.getElementById('txtPlace').value = "Set The Text";
}
#Html.TextBoxFor(m => m.OperationNo,new { #id = "txtPlace",#name="txtPlace" })
It should be the property name, which is OperationNo.
So your JS will be
document.getElementById("OperationNo").html = " Some text " ;
You can use the web inspector in Chrome or JS to view the html on your page to see the element attributes.
This is happens in a scenario of using same input fields with same properties in web form. Like the case of Login and Signup forms in single view/page.
Previously it was like this
input one >
<div class="field-wrap">
#Html.TextBoxFor(model => model.Username, new { #class = "form-control",placeholder = "Username", #required = "required", autofocus = "" })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
input two>
<div class="field-wrap">
#Html.TextBoxFor(model => model.Username, new { #class = "form-control", placeholder = "Username", #required = "required", autofocus = "" })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
then i added a unique id # for the username input
the new input one >
<div class="field-wrap">
#Html.TextBoxFor(model => model.Username, new { #class = "form-control", id = "loginUsername", placeholder = "Username", #required = "required", autofocus = "" })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
the new input two >
<div class="field-wrap">
#Html.TextBoxFor(model => model.Username, new { #class = "form-control", id = "SignupUsername" , placeholder = "Username", #required = "required", autofocus = "" })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>

Categories