how to get the selected value to input text box in thymeleaf - textbox

Onchange in the dropdown, dist_nm should be reflected in the text box..
Can someone help?
<select id="editDistName" th:field="*{districts}" th:onchange="selectedDistName();">
<option value="default">Select the District </option>
<option th:each="dist : ${districts}" th:value="${dist.dist_id}"
th:text="${dist.dist_nm}" th:selected="${dist.dist_nm}"/>
</select>
<input type="text" class="form-control" id="dist_nm" name="dist_nm"/>

1.) I don't think that your th:selected="..."-attribute has any effect.
2.) Try this js-code (using jquery):
function selectedDistName()
{
let txt = $("#editDistName option:selected").text();
console.log(txt);
$("#dist_nm").val(txt);
}
Comment if you are not using jquery.

Finally, I found a way to fetch the name through table by passing ID from Dropdown.
HTML - form
<div class="form-group">
<select id='DCode' name='DCode'>
<option th:each="dist : ${districts}"
th:value="${dist.dist_id}"
th:text="${dropDownItem.dist_nm}" />
</select>
</div>
<div class="form-group">
<div id="textBox"></div>
</div>
Repository -- fetching name through ID
#Query("SELECT name FROM Sample WHERE id =:ID ORDER BY id")
public String getName(#Param("ID") int code);
AjaxController
#RequestMapping(value="Ajax",method={ RequestMethod.GET, RequestMethod.POST })
public #ResponseBody String editName(#RequestParam(value="ID") int d_Code ) {
String name = rep.getName(d_Code);
return name;
}
JS-file /passing ID to get Name from table/
$(document).on("change", "#DCode", function() {
try {
var d_id= $("#DCode option:selected").val();
var params = {ID : d_id};
$.ajax({
type:'POST',
url:'/Ajax',
data:params,
success:function(responseJson){
var jSON_res = JSON.stringify(responseJson);
var d_Name = jSON_res.replace(/\"/g, "" ); //remove double quote from string
var text_val = "<input type='text' id ='new_name' name ='new_name' " +
" value =' "+d_Name+" ' />";
$("#textBox").empty().append(text_val);
}//success function
});
} catch(err) {
alert("Exception ::-- "+err);
}
});
I'm very new to spring boot and this is one of the way I tried.
Let me know, if there is better way of getting the result.
Thank you,

Related

Compare dropdown with value not key

I am fetching user data in the model and using SelectList, fetching the country detail with name and ID.
ID Name
1 USA
2 UK
3 CANADA
On my page, I have TEXTBOX, in which I am displaying the country NAME USA which is fetched from the model. Now SAME COUNTRY NAME I WANT TO KEEP SELECTED in my dropdown also.
var GetNewCountry = new SelectList(_manualGridService.GetCountry().OrderBy(l => l.Name)
.ToDictionary(us => us.ID, us => us.Name), "Key", "Value");
ViewBag.GetNewCountry = GetNewCountry ;
here is my view dropdown code
<div class="form-group">
<select asp-for="ConId" asp-items="#ViewBag.GetNewCountry" class="form-control">
<option value=""> Select </option>
</select>
<span asp-validation-for="ConId" class="text-danger"></span>
</div>
Parameter details
public int ConId { get; set; }
Here is my textbox code with parameter
public string UserConName{ get; set; }
<div class="form-group">
<input asp-for="UserConName" class="form-control" readonly="readonly" autocomplete="off" placeholder="Country Name" style="width:107%" />
</div>
The UserConName, textbox contains value USA, I want to keep seleted USA in my DROPDOWN LIST also.
MY SOLUTION
string strId = "";
foreach (var item in GetNewCountry )
{
if (item.Text == res.ConName)
{
strId = item.Value;
}
}
if (!string.IsNullOrEmpty(strId))
{
res.ConId= int.Parse(strId);
}
Shorten Answer
var GetNewCountry = new List<SelectListItem>();
foreach (var item in _manualGridService.GetCountry().OrderBy(l => l.Name).ToDictionary(us => us.ID, us => us.Name))
{
GetNewCountry.Add(new SelectListItem() {
Value = item.Key.ToString(),
Text = item.Value,
Selected = item.Value == "USA" ? true : false
});
}
ViewBag.GetNewCountry = GetNewCountry ;
Detailed explanation
Firstly you need know, by using new SelectList(_manualGridService.GetCountry().OrderBy(l => l.Name) .ToDictionary(us => us.ID, us => us.Name), "Key", "Value"), the Key equals to Id's value, the Value equals to Name's value.
Then compare with this constructor definition: public SelectList(IEnumerable items, string dataValueField, string dataTextField), we can know that ID represents the <option>'s value, 'Name' represents the <option>'s text.
<option value="IDValue">NameValue</option>
Finally the SelectList contains another constructor which can set the dropdownlist selected value:
public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
Above all, in your scenario the selected value does not match the ID, it matched Name value, so you need change the SelectList like below:
var GetNewCountry = new SelectList(_manualGridService.GetCountry().OrderBy(l => l.Name)
.ToDictionary(us => us.ID, us => us.Name), "Value", "Value","USA");
Generated html:
<select class="form-control" data-val="true" data-val-required="The ConId field is required." id="ConId" name="ConId">
<option value=""> Select </option>
<option selected="selected" value="NameValue1">NameValue1</option>
<option value="NameValue2">NameValue2</option>
//...
</select>
Note:
In this way you can get the value="USA" option selected, but another question, your select <select asp-for="ConId"> here binds value to ConId, but the option value now represents Name, so it cannot bind successfully if you do form submit.
So if you do not want to change the <select asp-for="ConId"> to <select asp-for="UserConName">, you need modify your backend code like below:
var GetNewCountry = new List<SelectListItem>();
foreach (var item in _manualGridService.GetCountry().OrderBy(l => l.Name).ToDictionary(us => us.ID, us => us.Name))
{
GetNewCountry.Add(new SelectListItem() { Value = item.Key.ToString(), Text = item.Value, Selected = item.Value == "USA" ? true : false });
}
ViewBag.GetNewCountry = GetNewCountry ;

Html.ActionLink is not working in foreach loop

I receive some data from another page. I try to loop through data and create a link. I get the data and put it in #Html.ActionLink(GroupID, "GroupActivity", "Home"). GroupID have value now.
But on screen it just shows the data but does not makes it a link.
<li>#Html.ActionLink("Timetable", "Timetable", "Home")</li>
<li>
<select class="form-control">
<option selected>Select Group</option>
#{ var GroupID = ""; }
#foreach (var item in Model)
{
<option>
#{
GroupID = item.GroupID.ToString();
ViewBag.SelectedGroup = GroupID;
}
#Html.ActionLink(GroupID, "GroupActivity", "Home")
</option>
}
</select>
</li>
enter image description here
You have to write there something like this:
Using Action link
#Html.ActionLink("Some text for link", "GroupActivity", "Home",new {GroupID=GroupID })
But in your case, this would not work because you are creating action link inside option which is invalid.
Using client side event (onchange)
$(function(){
$("#YourDropDownID").change(function(){
var selectedItem = $("#YourDropDownID option:selected").text();
var redirectURL = '#Url.Action("ActionName","ControllerName")';
window.location.href = redirectURL + "?item=" + selectedItem;
}
}

Able to Select multiple options for radiobuttons in ASP.NET MVC

I am working on developing on a voting page mechanism. Here I will have the List of questions and against each question I have 3 options(I am using radio buttons). I have attached my View and Controller method. I am getting the value saved to DB correctly, but my problem is I am able to select multiple options where radio buttons are used. I want to make sure that, if one option is selected for a question the other options must be automatically deselected, which is not happening for me.
My View :
#using (Html.BeginForm())
{
<div>
#foreach (var a in ViewBag.Questions)
{
<h4>#a.Questions</h4>
<div>
#foreach (var b in Model)
{
if (b.QuestionsID == a.id)
{
#Html.RadioButton(b.AnswersOptions,
new {Answerid= b.id, Questionid=a.id })
#b.AnswersOptions
}
}
</div>
}
</div>
<br/>
<div >
<input type="submit" value="Vote Now!!"
onclick="return confirm('Are you sure you want to
submit your choices?');"/>
</div>
}
My Controller :
public ActionResult VotingResult_Post(FormCollection resultcollection)
{
int resultcollectionCount = resultcollection.Count;
if (resultcollectionCount == CountofQuestionsDisplayed)
{
for (int i = 0; i < resultcollectionCount; i++)
{
string SelectedIDArray = resultcollection[i];
string SelectedAnswerIDValue = GetValue("Answerid", SelectedIDArray);
string SelectedQuestionID = GetValue("Questionid", SelectedIDArray);
InsertUsersReponses(SelectedQuestionID, SelectedAnswerIDValue);
}
}
List<Voting_Questions> QuesList = PopulateQuestions();
ViewBag.Questions = QuesList;
List<Voting_Answers> Answers = aobj.Voting_Answers.ToList();
return View(Answers);
}
You need an HTML helper like the following
public static System.Web.Mvc.MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
string ForFormat = String.Empty;
if (listOfValues != null)
{
// Create a radio button for each item in the list
// need to create correct ID here
var baseID = metaData.PropertyName;
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", baseID, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
// extracting the text for="##" from the label and using this for the control ID
// ASSUMES the format<label for="TestRadio_1">Line 1</label> and splitting on the quote means that the required value is in the second cell of the array
String[] temp = label.ToString().Split('"');
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = temp[1] }).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required="Option1" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line 1</label>
// e.g. <input data-val="true" data-val-required="Option2" id="TestRadio_2" name="TestRadio" type="radio" value="2" /><label for="TestRadio_2">Line 2</label>
sb.AppendFormat("<div class=\"RadioButtonList\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
which is called as follows:
#Html.ValidationMessageFor(m => m.myProperty)
#Html.LabelFor(m => m.myProperty, new { #class = "editor-label control-label" })
<div class="editor-field controls radio">
#Html.RadioButtonForSelectList(
m => m.myProperty,
ListOfOptionsForRadioButton
)
</div>
The markup is for Bootstrap.

unobtrusive MVC3 validating group of checkboxes

I need to validate a group of checkboxes using MVC3 unobtrusive validation. how would i do it? I found this and tried it, but it doesn't work.
$(function(){
$.validator.addMethod('cb_selectone', function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
}, 'Please select at least one option');
$('#main').validate({rules:{Services:"cb_selectone"}});
...
My Html:
<input type="checkbox" class="checkbox" name="Services" value="1" />
<input type="checkbox" class="checkbox" name="Services" value="2" />
<input type="checkbox" class="checkbox" name="Services" value="3" />
It would be best if someone provided a complete solution with server side + client side validation (of course using MVC3 unobtrusive validation).
Thanks
Ok, figured it out:
for server validation:
using data annotations (required will do it)
like so in my view model:
[Required(ErrorMessageResourceName = "fld_Service_val_Required_lbl", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]
public ICollection<int> Services { get; set; }
for client validation in my html i added a class to my input checkboxes:
<input type="checkbox" class="checkbox required-checkbox" name="Services" value="1" />
<input type="checkbox" class="checkbox required-checkbox" name="Services" value="2" />
<input type="checkbox" class="checkbox required-checkbox" name="Services" value="3" />
and also:
$(function(){
$.validator.addMethod('required_group', function(value, element) {
var $module = $(element).parents('form');
return $module.find('input.checkbox:checked').length;
}, 'Select at least one Service please');
$.validator.addClassRules('required-checkbox', { 'required_group' : true });
..
not sure if this is the best solution but it works :). if someone knows a better please post.
This works - validates appropriately on submit, and hides/displays the validation message if a checkbox is subsequently checked or unchecked with minimal overhead (only gets hit once per validation cycle).
JavaScript:
(function ($) {
//functions from unobtrusive:
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
var formEls;
function getUniqueFormId(form) {
if (typeof(formEls==='undefined')) {
formEls = document.getElementsByTagName('form');
}
return 'form' + Array.prototype.indexOf.call(formEls, form);
}
//from jQuery validation
function findByName(name, form) {
// select by name and filter by form for performance over form.find("[name=...]")
return $(document.getElementsByName(name)).map(function (index, element) {
return element.form == form && element.name == name && element || null;
});
}
//-------------------------
$.validator.addMethod('requiredgroup', function (value, element, params) {
for (var i = 0; i < params.length; i++) {
if (params[i].checked) { return true; }
}
return false;
});
valGroups = [];
$.validator.unobtrusive.adapters.add('requiredgroup', function (options) {
var groupName = options.element.name,
uniqueGroup = getUniqueFormId(options.form) + groupName;
if (!valGroups[uniqueGroup]) {
valGroups[uniqueGroup] = findByName(groupName, options.form);
}
//jQuery Validation Plugin 1.9.0 only ever validates first chekcbox in a list
//could probably work around setting this for every element:
setValidationValues(options, 'requiredgroup', valGroups[uniqueGroup]);
});
} (jQuery));
of course the elements must have a data-val-requiredgroup attribute. The following MVC code (as part of a helper) will add the appropriate annotations:
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
var baseAttr = htmlHelper.GetUnobtrusiveValidationAttributes(name, metaData);
baseAttr.Add("name", name);
baseAttr.Add("type", "checkbox");
if (metaData.IsRequired)
{
baseAttr.Add("data-val-requiredgroup", baseAttr["data-val-required"]);
baseAttr.Remove("data-val-required");
Because it looks for the Required attribute, server side validation is handled by the existing framework.

Refresh asp.net mvc page

I have some app on asp.net mvc.
And I am trying to create table filter. Page is very difficult, so i can't get data from JSON response. I am trying to get it via call action with params.
function refresh() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, null, "json");
}
<select id="list" onchange="refresh()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<%foreach (var i in (IEnumerable<int>)ViewData["list"])
{ %>
<%=i %><br />
<%} %>
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
ViewData["list"] = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
return View();
}
But I don't see new data. What's wrong?
How I can refresh page?
PS I meen that i wanna go(redirect) from action A to action A(with param). I don't want reconstruct page on client side
You aren't doing anything with the result you retrieve with the get call. Also, since you're returning a view, you should set your data type to html.
$.get('/Home/Index', params, function(html) {
$('body').html(html);
},'html');
I'd note that I would probably only replace the section that gets updated. You can do this by using a partial view to hold just that section, then when you get the request via AJAX you can return just the partial view instead of the full view. The other thing that I would do is make the views strongly-typed to IEnumerable<int> and pass a model, instead of using view data.
View
<script type="text/javascript">
$(function() {
$('#list').change( function() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, function(html) {
$('#listResults').replaceWith(html)
}, "html");
});
});
</script>
<select id="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<% Html.RenderPartial( "ListResults" ); %>
Partial View
<div id="listResults">
<%foreach (var i in Model)
{ %>
<%=i %><br />
<%} %>
</div>
Action
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
var model = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
if (this.Request.IsAjaxRequest())
{
return PartialView(model);
}
return View(model);
}
I see one problem in the code above:
The $.get() does not do anything when your request is complete(your data has been fetched from the server)
Instead of passing null there you should pass in a function with a parameter which is the data. Example:
$.get("/Home/Index"
, params,
function(data){
//do something with data.
//data is json object returned
}, "json");
in this function you can actually have your filter applied to the table

Resources