Razor show / hide base on radio button using javascript - 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.

Related

jquery onchange get enter key

I have this code
<script type="text/javascript">
$(function () {
$("#temperature").change(function (e) {
// elaboration
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group" id="TemperatureGroup">
#Html.LabelFor(model => model.temperature, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.temperature, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.temperature, "", new { #class = "text-danger" })
<div id="infoPaintTemperature" class="col-md-10">
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Salva" class="btn btn-default" />
</div>
</div>
</div>
}
I need to catch if the user have press Enter key inside the input "Temperature", to prevent elaboration of "change" javascript. I can't find anywhere how to get the info of which key has been pressed inside "change" function.
Thanks for who can help
EDIT
I would like to do two different elaboration in .change() if I leave the textbox or if I press Enter inside textbox.
I am assuming you want to trigger some function (elaboration inside "change" event callback) only if the user leaves the input box.
If that is the case then you can try using the .focusout((event) => {}) method of javascript.
It will be only triggered when input is focused out and inside which you can compare the currentInput value with previousInput value and accordingly trigger run the logic.
$(function () {
let previousInput = '' // blank for first time use
$("#temperature").focusout(function(e){
// console.log(e.target.value)
if (previousInput !== e.target.value) {
// Input changed
previousInput = e.target.value
// rest of elaboration
} else {
// Input not changed
}
});
});
You could try something like this;
$('input').on('keypress', function(e) {
if (e.keyCode == '13') {
e.preventDefault();
$(this).blur()
};
});
Which when the user presses ENTER will enact blur which can also enact the change.
.preventDefault(); will stop the form submitting when ENTER is pressed.
you muse use delegate to attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements, and you can use .temperature
$( ".form-horizontal" ).delegate( ".temperature", "change", function()
{ }

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

When I pick default dropdown value with javascript, it doesn't trigger change

I have a textfield and a date textfield. I am trying to connect them with Javascript, but I encounter a problem. My script is:
<script>
$("#solDate").change(function () {
if ($(this).val().trim() == '') {
$("#caseStatus").val('In Progress');
$("#solvedBy").val('Pick an option');
$("#solvedBy").change();
}
else if ($(this).val().trim() != '' && $("#solvedBy").val().trim() == '') {
$("#caseStatus").val('Solved');
$("#solvedBy").val('Please, pick the issue solver');
$("#solvedBy").change();
}
});
</script>
When date is picked from calendar, it should set a value 'Please, pick the issue solver'. It works perfectly.
Then, if you entered the date incidentally, it should return the previous default value - "Pick an option".
In both cases, a change is triggered.
Then, another trigger is listening for these changes.
<script>
$("#solvedBy").change(function () {
if ($(this).val() == 'Please, pick the issue solver') {
$("#saveBtn").attr('disabled', true);
$("#slvByValMsg").text('You have solution date and no solver');
}
else if ($(this).val().trim() == '' && $("#solDate").val().trim() != '') {
$("#saveBtn").attr('disabled', true);
$("#slvByValMsg").text('You have solution date and no solver');
}
else {
$("#saveBtn").attr('disabled', false);
$("#slvByValMsg").text('');;
}
});
</script>
After my troubleshooting, it turns out, that the first if statement on the first script doesn't trigger a change. It may be because it doesn't recognize the default pick option with value ''. I am not sure. Anyhow, when I delete the date from the textfield, the value of the other textfield doesn't change to 'Pick an option', but to ''.
HTML Code:
#Html.LabelFor(model => model.Solution_Date, htmlAttributes: new { #class = "control-label col-md-2" })<sup> 1 </sup>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Solution_Date, new { #id = "solDate", #class = "one", #type = "datetime" })
<br />
#Html.ValidationMessageFor(model => model.Solution_Date, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.Solved_by, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="dropdown">
#Html.DropDownListFor(model => model.Solved_by, (IEnumerable<SelectListItem>)ViewBag.SlvBy, "Pick an option", new { #id = "solvedBy" })
<br />
#Html.ValidationMessage("Solved_by", "", new { #id = "slvByValMsg", #class = "text-danger" })
</div>
I know there are probably better ways to do this, but I'm looking for a resolution mainly because I don't know why this change trigger doesn't fire.
Thanks in advance!
I've found what causes the issue. It turns out that
$("#solvedBy").val('Pick an option');
Cannot be executed, because this is the default option and the value behind it is ''. This must be messing with the .change() triggers and created havoc in other scripts as well.
I changed it to
$("#solvedBy").val('');
...and everything works now.

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