Not able to set textarea and checkbox to set value in mvc5 - javascript

Hi I am trying to set my value in javascript + jquery in mvc 5 for textarea and checkbox but it is not working.
My javscript code is as
document.getElementById("UpdatetxtDescription").value = "abc";
document.getElementById("UpdateActive").checked = true;
my view page code is as
#Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { #class = "form-control", id = "UpdatetxtDescription" } })
#Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { #class = "form-control", id = "UpdateActive" } })
In console I am able to see
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = UpdateActive }" id="Active" name="Active" type="checkbox" value="true">
<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }" id="Description" name="Description" rows="2"></textarea>
I can set value with id="Description" and id="Active" nut as I have 2 checkbox and 2 text area I can not make that id use because both the control have same id as decription for textarea and Active for checkbox
2nd textarea and checkbox are as below whose Id I have set as different
#Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { #class = "form-control", id = "txtDescription", rows = "3" } })
#Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { #class = "form-control", id = "txtDescription" } })
but in console I can see there Id as
<textarea cols="20" htmlattributes="{ class = form-control, id = txtDescription, rows = 3 }" id="Description" name="Description" rows="2"></textarea>
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = txtDescription }" id="Active" name="Active" type="checkbox" value="true">

You are setting htmlAttributes parameter of your HTML Helpers the wrong way. If you see the generated HTML, you can see that id and class are not being set. But an attribute called htmlAttributes itself is being added like this:
<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }"></textarea>
So you should change it to:
#Html.TextAreaFor(model => model.Description, new { #class = "form-control", id = "UpdatetxtDescription" })
#Html.CheckBoxFor(model => model.Active, new { #class = "form-control", id = "UpdateActive" })
and
#Html.TextAreaFor(model => model.Description, new { #class = "form-control", id = "txtDescription", rows = "3" })
#Html.CheckBoxFor(model => model.Active, new { #class = "form-control", id = "txtDescription" })
(PS: If you were to submit this form, only one textarea and checkbox will be bound to model because you are creating more than one input with the same name.attribute)

The id should be unique in the same document for a valid structure, if you can't change it so you could deal with this duplication using jQuery selectors like :
$('[id="Description"]:eq(0)') //Select the first element with id "Description"
$('[id="Description"]:eq(1)') //Select the second element with id "Description"
The same thing for the second element input :
$('[id="Active"]:eq(0)') //Select the first element with id "Active"
$('[id="Active"]:eq(1)') //Select the second element with id "Active"
Hope this helps.

Related

Razor show / hide base on radio button using javascript

I am trying to hide or show a textbox, in a ASP MVC razor view, now i using javascript to handle when i click the radio button which can help me to do hide or show function.
however, i want to base on database record hide and show the textbox, so if i use below code , i need to click the radio for hide or show a textbox, anyone can give me advise how to hide or show textbox base on database record and no need to click radio button? thanks
<script type="text/javascript">
const { checked } = require("modernizr");
function text(x) {
if (x == 0 ) document.getElementById("name").style.display = "block",
document.getElementById("address").style.display = "none",
else document.getElementById("name").style.display = "none",
document.getElementById("address").style.display = "block",
return;
}
</script>
//radio name
#Html.LabelFor(Model => Model.Type, "A")
#Html.RadioButtonFor(Model => Model.Type, "A" , new { #onclick = "text(0)", #id = "but1" })
#Html.LabelFor(Model => Model.Type, "B")
#Html.RadioButtonFor(Model => Model.Type, "B" , new { #onclick = "text(1)", #id = "but2" })
//textbox(name)
<div class="form-group col-md-6" id="name">
#Html.LabelFor(model => model.name, new { #class = "control-label" })
#Html.TextBoxFor(model => model.name, new { #class = "form-control"e })
</div>
//textbox(address)
<div class="form-group col-md-6" id="address">
#Html.LabelFor(model => model.address, new { #class = "control-label" })
#Html.TextBoxFor(model => model.address, new { #class = "form-control" })
</div>
<script>
// self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
text(#Model.Value);
})();
</script>
This is a document ready function. Your text() method will be called when page is loaded.
Use #Model.Value your initial db value. That way it will work for the first time with the value which is in the db.

Selecting only the closest input outside of a Html.dropdownlistfor

I have three dropdownlistfor sets, with three separate inputs that are shown on selecting the value "other" from the list. The following code is meant to select only the closest input to the item that was clicked.
Set 1
#Html.DropDownListFor(m => m.Title, "--Select Title --", new { #class = "form-control requiredField dropListFunction", required="true" })
set2
#Html.TextBoxFor(m => m.TitleOther, new { #class = "form-control hidden", placeholder = "Enter New Title" })
#Html.DropDownListFor(m => m.Branch "--Select Branch --", new { #class = "form-control requiredField dropListFunction", required = "true" })
#Html.TextBoxFor(m => m.BranchOther, new { #class = "form-control hidden", placeholder = "Enter New Branch" })
Set 3
#Html.DropDownListFor(m => m.State, Enum.GetNames(typeof(State)).Select(e => new SelectListItem { Text = e }), "--Select State --", new { #class = "form-control requiredField dropListFunction", required = "true" })
#Html.TextBoxFor(m => m.StateOther, new { #class = "form-control hidden", placeholder = "Enter New State" })
with the following jquery handling selection of the input closest to the dropListFunction that contains a clicked option with value other
$('option[value=Other]').on('click',function(){
var nextInput = $('.dropListFunction').next('input');
nextInput.removeClass('hidden')
});
The problem is that it is not selecting just the next item in the list, but opening all hidden inputs when selected. Any help is greatly appreciated
All your DropDowns have the class .dropListFunction so you will get all the next inputs.
$('.dropListFunction').on('change', function(e){
var dd = $(e.target), input = dd.next('input');
if(dd.val() === 'other'){
input.removeClass('hidden');
}else{
input.addClass('hidden');
}
});
see jsbin here
https://jsbin.com/lacimoyula/edit?html,console,output

jquery autocomplete - string array

My web form model(AdtFormModel) has this variable:
public List<String> TemoinsVille { get; set; }
I use a list because I want the user to be able to dynamically add more 'TemoinsVille' in the form. For now I have two textboxfor, when I fill both of them, my controller receives a string list with 2 items in it. I will add the feature to dynamically add TemoinsVille later.
In my form, I want to use an auto-complete field for this TemoinVille variable. I use a method called 'AutocompleteTous' that works, I use it somewhere else in the form. I don't know how to write the script so that the autocomplete works for a second TemoinVille input.
My JQuery code is:
var auto5 = $('#AdtFormModel_TemoinsVille').autocomplete({
source: '#Url.Action("AutocompleteTous", "InvForm")',
minLength: 3,
delay: 400
}).data("ui-autocomplete");
auto5._renderItem = function (ul, item) {
return $("<li>")
.attr("ui-autocomplete-item", item)
.append(item.label.split("|")[0])
.appendTo(ul);
};
auto5._renderMenu = function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).addClass("dropdown-menu");
};
In my view, I have t TemoinVille textboxfor inputs:
#Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) #Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { #class = "text-danger" })
#Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) #Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { #class = "text-danger" })
the autocomplete works for the first input, but not for the second...
Here is the html code for the two inputs:
<div class="invalidite-section">
<input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
</div>
<div class="invalidite-section">
<input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
</div>
Any suggestions?
You are targeting an id #AdtFormModel_TemoinsVille, that's the input right?
The ID must be unique on page. So it will work only on first input it finds.
You need to target the elements by class, then the autocomplete should work in all inputs.
try something like this:
var auto5 = $('.form-control input').autocomplete({ // I suppose .form-control is a div that contains the input

hide or show form control based on ddl selection in MVC using jQuery

My problem is similar to the one in show divs based on drop down selection. I have a dropdown list in a div with four options. Depending on which is selected I want one of two other controls to show in the next div and in one case it will show an EditorFor and I want the value populated. Here's what I have...
<div class="form-group">
#Html.Label("OriginType", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("OriginType", ViewData["OriginType"] as SelectList, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group" id="pnlOrigin">
#Html.LabelFor(model => model.Origin, htmlAttributes: new { #class = "control-label col-md-2" })
<div id="pnlOrigin1"class="col-md-4">
#Html.DropDownList("ddlORDER_10", (IEnumerable<SelectListItem>)ViewBag.Order, "Select an Order Number", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Origin, "", new { #class = "text-danger" })
</div>
<div id="pnlOrigin2"class="col-md-4">
#Html.EditorFor(model => model.Origin, new { htmlAttributes = new { #class = "form-control", #id = "tbOrigin" } })
#Html.ValidationMessageFor(model => model.Origin, "", new { #class = "text-danger" })
</div>
</div>
So what I need is when a user selects from the OriginType dropdown (STK, PO, WO, OTHER) it will show or hide the dropdown list or EditorFor in the pnlOrigin div. If PO or WO is selected it will show the ddl. If OTHER or STK is selected it will show the EditorFor, and in the case of STK it will prepopulate the Editor with STK.
I've tried to modify the function in the referenced post but it's not hiding the controls initially and a selection from the OriginType dropdown list isn't having any affect?
Here's the jQuery I created. I'm not sure where I'm going wrong.
$(document).ready(function () {
function ShowOptions(originType) {
if (OriginType == "0"){
$("#pnlOrigin").hide();
$("#pnlOrigin1").hide();
$("#pnlOrigin2").hide();
// hide all before show
var showOriginPanel = false;
}
if (OriginType == 'STK') {
$("#pnlOrigin").show();
$("#tbOrigin").val('STK');
showOriginPanel = true;
}
if (OriginType == 'PO') {
$("#pnlOrigin1").show();
showOriginPanel = true;
}
if (OriginType == 'WO') {
$("#pnlOrigin1").show();
showOriginPanel = true;
}
if (OriginType == 'OTHER'){
$("#pnlOrigin2").show();
showOriginPanel = true;
}
if(showOriginPanel) {
$("#pnlOrigin").show();
}
}
ShowOptions($("#OriginType").val());
$("#OriginType").change(function () {
ShowOptions($(this).val());
});
});
Any help would be greatly appreciated!
I seem to have found the problem with my code although I'm not sure why it affected the function. I had the htmlAttribues declared for the two hidden controls as "new { htmlAttributes = new { #class = "form-control" } }". Once I changed them to "htmlAttributes: new { #class = "form-control" }" the function started working properly.
I also had to add some .hides in case the user changed their initial selection prior to posting.

How to make a radio button disappear in a section with 4 radio buttons

So I have this in my HTML:
<div class="field">
#Html.RadioButton("button1", id1, new { #id = "button1", #class = "radio" })
<label for="button1" class="radio">Label1</label>
#Html.RadioButton("button2", id2, new { #id = "button2", #class = "radio" })
<label for="button2" class="radio">Label2</label>
#Html.RadioButton("button3", id3, new { #id = "button3", #class = "radio" })
<label for="button3" class="radio">Label3</label>
#Html.RadioButton("button4", id4, new { #id = "button4", #class = "radio" })
<label for="button4" class="radio">Label4</label>
</div>
and I want to make one of those disappear, in some of the cases I receive, so it appears like
<div class="field">
#Html.RadioButton("button1", id1, new { #id = "button1", #class = "radio" })
<label for="button1" class="radio">Label1</label>
#Html.RadioButton("button2", id2, new { #id = "button2", #class = "radio" })
<label for="button2" class="radio">Label2</label>
#Html.RadioButton("button3", id3, new { #id = "button3", #class = "radio" })
<label for="button3" class="radio">Label3</label>
</div>
but of course I can't make two copies and show the copy I want, because then I would have some buttons with same ids and I want to work with them in my .js afterwards.
The question is: Is there a way to make the button I want disappear from the view without destroying the view? (I tried to insert the radio button into a div and then "hiding" (.hide() method in javascript) it when I wanted, but it didn't look well when it had to appear.

Categories

Resources