Option value not getting passed (.NET + Ajax) - javascript

I have a dropdown where I use ajax to fetch the select options.
<form asp-action="AdresWijzigen">
<input asp-for="KlantId" hidden />
<input asp-for="AdresType" hidden />
<input asp-for="OudStraat" hidden />
<input asp-for="OudHuisNummer" hidden />
<input asp-for="OudBus" hidden />
<input asp-for="OudPlaatsId" hidden />
<input asp-for="OudPlaatsNaam" hidden />
<div>
<label asp-for="NieuwStraat"></label>
<span asp-validation-for="NieuwStraat" class="text-danger"></span>
<input asp-for="NieuwStraat" />
</div>
<div>
<label asp-for="NieuwHuisNummer"></label>
<span asp-validation-for="NieuwHuisNummer" class="text-danger"></span>
<input asp-for="NieuwHuisNummer" />
</div>
<div>
<label asp-for="NieuwBus"></label>
<input asp-for="NieuwBus" />
</div>
<div>
<label>Postcode</label>
<input type="text" id="postcodeInput" name="postcodeInput" placeholder="Geef een postcode in" />
<input type="button" id="zoekGemeente" name="zoekGemeente" value="🔍" />
<p id="errorPostcode" class="text-danger" style="display:none"></p>
<div id="gemeenteSelect"></div>
</div>
<div>
<input type="submit" value="Adres wijzigen" class="btn btn-primary" />
</div>
</form>
<script>
$("#zoekGemeente").click(function () {
var url = "#Url.Action("FetchGemeenteObvPostcode", "Klant")";
var data = $("#postcodeInput").val();
var $postcodeControl = /^\d{4}$/;
if (data.match($postcodeControl)) {
$("#errorPostcode").css('display', 'none');
$.ajax({
type: "POST",
url: url,
dataType: "JSON",
data: { postcode: $("#postcodeInput").val() },
success: function (data) {
if (data.length < 1) {
$("#errorPostcode").css('display', 'inline-block');
$("#errorPostcode").text("Geen gemeente gevonden voor postcode " + $("#postcodeInput").val());
$("#gemeenteSelect").empty();
} else {
var g = '<select asp-for="NieuwPlaatsId">';
for (var i = 0; i < data.length; i++) {
g += '<option value="' + data[i].plaatsId + '">' + data[i].plaatsNaam + '</option>';
}
g += '</select>';
$("#gemeenteSelect").html(g);
}
}
})
} else {
$("#errorPostcode").css('display', 'inline-block');
$("#errorPostcode").text("Geldige postcode moet uit 4 cijfers bestaan");
$("#gemeenteSelect").empty();
}
})
</script>
[HttpPost]
public JsonResult FetchGemeenteObvPostcode(string postcode)
{
var gemeentes = klantenRepository.GetPlaatsenByPostcodes(postcode);
return Json(gemeentes);
}
//Valideer viewModel, als valid redirect naar WijzigenAdresBevestigen()
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AdresWijzigen(AdresWijzigenViewModel viewModel)
{
if (ModelState.IsValid)
{
return RedirectToAction(nameof(WijzigingAdresBevestigen),viewModel);
}
else
{
List<Plaats> plaatsen = new List<Plaats>();
plaatsen = _context.Plaatsen.ToList();
ViewData["NieuwAdres"] = plaatsen;
return View(viewModel);
}
}
// Redirect to page that requests confirmation
public async Task<IActionResult> WijzigingAdresBevestigen(AdresWijzigenViewModel viewModel)
{
var nieuwPlaats = await _context.Plaatsen.FindAsync(viewModel.NieuwPlaatsId);
Console.WriteLine(nieuwPlaats);
ViewData["NieuwPlaatsNaam"] = nieuwPlaats.PlaatsNaam;
return View(viewModel);
}
The fetch works fine, and the html select option value gets filled with the correct id's. However, when I submit the form, the option value that is filled in using ajax does not get filled into the model that is passed to the controller.
ViewData["NieuwPlaatsNaam"] = nieuwPlaats.PlaatsNaam;
^ this is the line that returns a "Object reference not set to an instance of an object" error on submit
Am I missing something?

Solved by adding the <select asp-for=...> tag in the HTML directly, as it seems that the asp-for doesn't work when added using Javascript (as pointed out by #PeterB in the comments).
<div>
<label>Postcode</label>
<input type="text" id="postcodeInput" name="postcodeInput" placeholder="Geef een postcode in" />
<input type="button" id="zoekGemeente" name="zoekGemeente" value="🔍" />
<p id="errorPostcode" class="text-danger" style="display:none"></p>
**<select id="gemeenteSelect" asp-for="NieuwPlaatsId" style="display:none"></select>**
</div>
....
if (data.length < 1) {
$("#errorPostcode").css('display', 'inline-block');
$("#errorPostcode").text("Geen gemeente gevonden voor postcode " + $("#postcodeInput").val());
$("#gemeenteSelect").css('display', 'none');
} else {
var g = '';
for (var i = 0; i < data.length; i++) {
g += '<option value="' + data[i].plaatsId + '">' + data[i].plaatsNaam + '</option>';
}
$("#gemeenteSelect").css('display', 'inline-block');
$("#gemeenteSelect").append(g);
}
....

Related

Problem with required warning message and submit form

I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});

How should I put limit inside for loop using if condition using javascript

My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>

empty multiple select field prevent form submission

I have multiple select field among other fields on my form and submitting the data to the database using ajax. The data is submitting successfully but the problem is, when the multiple select field is empty, noting works: both the js and php code does not execute. Even thought I have the multiple select on the form but I plan not to make mandatory. Please help
$(function() {
$('#form1').on('click', function(e) {
e.preventDefault(); // do not allow the default form action
/* var realvalues = new Array();//storing the selected values inside an array
$('#s2_multi_value:selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
}); */
var form = $(this)[0].form;
var data = $(form).serialize();
$.ajax({
method: "POST",
url: "orgprocess1.php",
data: data
})
.done(function(data) { // capture the return from process.php
var obj = $.parseJSON(data);
var orgvalid = obj.valid2;
var buty = obj.$bty;
var orgmessage = obj.msg_orgcode;
var btypemessage = obj.msg_business;
if (orgvalid == 1) { // place results on the page
$('input[name="org_Code"]').removeClass('textBoxError');
$('#result2').html('<div class="valid"></div>');
} else {
$('input[name="org_Code"]').addClass('textBoxError');
$('#result2').html('<div class="error">' + orgmessage + '</div>');
}
if (buty == 1) { // place results on the page
$('select[name="btype"]').removeClass('textBoxError');
$('#result3').html('<div class="valid"></div>');
} else {
$('input[name="btype"]').addClass('textBoxError');
$('#select3').html('<div class="error">' + btypemessage + '</div>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-4">
<p>Email Address</p>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="col-sm-4">
<p>Address</p>
<input type="text" class="form-control" id="addre" name="addre" placeholder="Physical Assress">
</div>
<div class="col-sm-4">
<p>Business Type</p>
<select id="s2_multi_value" name="btype[]" class="form-control" multiple="multiple">
<option value="">select one</option>
<option value="Goods">Goods</option>
<option value="Consultancy">Consultancy</option>
</select>
<input type="submit" value="submit" name="submit">
</div>
Try the following snippet it submits form weather you select any value or not.
$(document).ready(function() {
$(document).on('submit', function(e) {
e.preventDefault(); // do not allow the default form action
console.log("form submitting and sending ajax call");
/* var realvalues = new Array();//storing the selected values inside an array
$('#s2_multi_value:selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
}); */
var form = $(this)[0].form;
var data = $(form).serialize();
$.ajax({
method: "POST",
url: "orgprocess1.php",
data: data
}).error(function(){
console.log('error for ajax')
})
.done(function(data) { // capture the return from process.php
var obj = $.parseJSON(data);
var orgvalid = obj.valid2;
var buty = obj.$bty;
var orgmessage = obj.msg_orgcode;
var btypemessage = obj.msg_business;
console.log("into ajax done function",data);
if (orgvalid == 1) { // place results on the page
$('input[name="org_Code"]').removeClass('textBoxError');
$('#result2').html('<div class="valid"></div>');
} else {
$('input[name="org_Code"]').addClass('textBoxError');
$('#result2').html('<div class="error">' + orgmessage + '</div>');
}
if (buty == 1) { // place results on the page
$('select[name="btype"]').removeClass('textBoxError');
$('#result3').html('<div class="valid"></div>');
} else {
$('input[name="btype"]').addClass('textBoxError');
$('#select3').html('<div class="error">' + btypemessage + '</div>');
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="my-form" action="http://google.com">
<div class="form-group">
<div class="col-sm-4">
<p>Email Address</p>
<input type="text" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
<div class="col-sm-4">
<p>Address</p>
<input type="text" class="form-control" id="addre" name="addre" placeholder="Physical Assress">
</div>
<div class="col-sm-4">
<p>Business Type</p>
<select id="s2_multi_value" name="btype[]" class="form-control" multiple="multiple">
<option value="">select one</option>
<option value="Goods">Goods</option>
<option value="Consultancy">Consultancy</option>
</select>
<input type="submit" value="submit" name="submit">
</div>
</form>

Creating elements on DOM dynamically but form not sending anything

I have a form which has some of its fields dynamically added based on another field, I was able to make it create the elements, but when I send the form, none of those are sent with the non dynamically fields that are loaded on page load.
Here's how I'm adding
function foo(field) {
var selectionDiv = document.getElementById("div_" + field);
var divLength = selectionDiv.children.length;
for (var i = 0; i < divLength; i++) {
if (selectionDiv.children[i].id.indexOf(field) != -1) {
var element = document.createElement(selectionDiv.children[i].tagName);
element.setAttribute("type", selectionDiv.children[i].type);
element.setAttribute("value", selectionDiv.children[i].value);
element.setAttribute("id", selectionDiv.children[i].id);
if (selectionDiv.children[i].className != "") {
element.setAttribute("class", selectionDiv.children[i].className);
}
$(element).appendTo("#div_" + field);
}
}
}
The HTML after insertion:
<form action="/URL" id="form" method="post" name="form" onsubmit="Confirmation('Are you sure?');return false;"><div class="form-horizontal">
<...OtherFields...>
<div class="form-group" id="form_group_test">
<label class="col-xs-2 control-label" for="Identity">test:</label>
<div class="col-xs-4" id="div_test">
<input id="Fields_test__Identity" name="Fields[test].Identity" type="hidden" value="test">
<input class="form-control hasTooltip" data-placement="right" data-toggle="tooltip" id="Fields_test__Value" name="Fields[test].Value" title="" type="text" value="*">
<br>
<button type="button" onclick="foo('test'); return false;" class="btn btn-default hasTooltip form-control" data_toggle="tooltip" data_placement="right" title=""><span class="glyphicon glyphicon-plus blue"></span></button>
<input type="hidden" value="test" id="Fields_test1__Identity"><input type="text" value="*" id="Fields_test1__Value" class="form-control hasTooltip"></div>
<...MoreFields...>
</form>
Any thoughts?
When you are creating dynamically the element, the attribute "name" is missing, try the following code:
function foo(field) {
var selectionDiv = document.getElementById("div_" + field);
var divLength = selectionDiv.children.length;
for (var i = 0; i < divLength; i++) {
if (selectionDiv.children[i].id.indexOf(field) != -1) {
var element = document.createElement(selectionDiv.children[i].tagName);
element.setAttribute("type", selectionDiv.children[i].type);
element.setAttribute("value", selectionDiv.children[i].value);
element.setAttribute("id", selectionDiv.children[i].id);
element.setAttribute("name", selectionDiv.children[i].id);
if (selectionDiv.children[i].className != "") {
element.setAttribute("class", selectionDiv.children[i].className);
}
$(element).appendTo("#div_" + field);
}
}
}

asp.net mvc and javascript textbox issue

I have a problem with the TextBox. When I was entering duplicate data, it is not allowing. That is what exactly I need but after saving data again it is allowing the duplicate data. How can I handle the scenario?
Here is my code.
var Controls = {
saveObjectives: function (actionurl) {
var frm = $('form[name=frmObjectives]')
frm.attr('action', actionurl);
frm.submit();
},
addObjectiveCheckbox: function () {
var text = $('#txtObjective').val();
$('#txtObjective').val('');
if ($.trim(text) == '')
return;
if ($('input[type=checkbox][value="' + text + '"]').length == 0)
$('#dvObjectives').prepend('<input type="checkbox" name="chkNewobjectives" value="' + text + '" Checked /> ' + text + '<br />');
},
And my HTML code is:
<input id="btnAddObj" class="btn" type="button" onclick="Controls.addObjectiveCheckbox();" value="Add Objective"/>
</div>
<div id="dvObjectives" name="ObjectivesList">
#foreach (Andromeda.Core.Entities.Objectives objective in Model)
{
<label class="checkbox">
<input type="checkbox" name="chkobjectives" Checked value="#objective.ObjectiveID" />#objective.ObjectiveText
</label>
}
</div>
You are using value='whatever text` in the jQuery, but value='ObjectiveID' in the view. This should fix it:
<input type="checkbox" name="chkobjectives" Checked value="#objective.ObjectiveText" />#objective.ObjectiveText

Categories