Select element has selected value -1 - javascript

Select element has selected value 4 (for example), I send form data to the server. The controller return partial view.
<script>
$(document).ready(function () {
var objSel = document.getElementById("IDVacationApplicationType");
checkVacationType(objSel);
$("select#IDVacationApplicationType").change(function () {
checkVacationType(this);
});
});
function checkVacationType(elem) {
var item = $(elem).val();
alert(item);
}
</script>
html:
<div class="form-position">
<div class="form-label">
#Html.LabelFor(model => model.VacationApplicationTypes)
</div>
<div class="form-value">
#Html.DropDownListFor(model => model.IDVacationApplicationType, Model.VacationApplicationTypes)
#Html.ValidationMessageFor(model => model.VacationApplicationTypes)
</div>
</div>
alert shows -1. After that form has select element with selected value = 4. How can I get this 4?
Answer: I had two the same ID in the page.

You can use this
$('#IDVacationApplicationType').find(":selected").val();
So change your function as checkVacationType as
function checkVacationType(elem) {
var item = $(elem).find(":selected").val();
alert(item);
}
Fiddle Demo

I had two the same ID in the page.
I need add class to the element:
#Html.DropDownListFor(model => model.IDVacationApplicationType, Model.VacationApplicationTypes, new { #class = "IDVacationApplicationType" })
<script>
$(document).ready(function () {
var objSel = $(".IDVacationApplicationType");
checkVacationType(objSel);
$(".IDVacationApplicationType").change(function () {
checkVacationType(this);
});
});
function checkVacationType(elem) {
var item = $(elem).val();
alert(item);
}
</script>

Related

Onclick text populates both textareas

I have a number of textareas and when I click on a paragraph outside the text is supposed to be added to the textarea, it works but the text is also getting added to the textareas above.
I'm a bit stumped on why this is happening and as I have 10 textaraes so clicking a paragraph at the bottom of the page adds the text to all the other textareas above.
Javascript
$(document).ready(function () {
$("#PollutionPreventionDivScrollDisplay").hide();
$("#PollutionPreventionDivScroll").on("click", function () {
$("#PollutionPreventionDivScrollDisplay").toggle();
});
var cartlist = document.querySelector("#EnvironmentalActionPollutionPreventionIdeasForAction");
var items = document.querySelectorAll("[data-item]");
[].forEach.call(items, function (item) {
item.addEventListener("click", function (e) {
e.preventDefault();
cartlist.value += `\n${item.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#WasteDivScrollDisplay").hide();
$("#WasteDivScrollDisplayScroll").on("click", function () {
$("#WasteDivScrollDisplay").toggle();
});
var cartlistOne = document.querySelector("#EnvironmentalActionWasteManagementIdeasForAction");
var itemsOne = document.querySelectorAll("[data-item]");
[].forEach.call(itemsOne,
function (itemOne) {
itemOne.addEventListener("click", function (e) {
e.preventDefault();
cartlistOne.value += `\n${itemOne.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#EnergyDivScrollDisplay").hide();
$("#EnergyDivScrollDisplayScroll").on("click", function () {
$("#EnergyDivScrollDisplay").toggle();
});
var cartlistTwo = document.querySelector("#EnvironmentalActionEnergyIdeasForAction");
var itemsTwo = document.querySelectorAll("[data-item]");
[].forEach.call(itemsTwo,
function (itemTwo) {
itemTwo.addEventListener("click", function (c) {
c.preventDefault();
cartlistTwo.value += `\n${itemTwo.innerHTML}`;
});
});
});
Example of html
<div class="row">
<div id="PollutionPreventionDivScrollDisplay" class="col-md-12 border-colour fixed-height">
#foreach (var info in Model.EnvironmentalActionPollutionPreventionExtraInfo)
{
var countItems = counter++;
<p><a data-item="#countItems" href="#">#info</a></p>
}
</div>
</div>
<div class="col-md-4 border-colour-right">
<div class="form-group">
<span class="mouse-pointer text-danger" id="PollutionPreventionDivScroll">Click to add options</span>
<label class="sr-only" for="EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder">Environmental Action Pollution Prevention Ideas For Action</label>
#Html.TextAreaFor(x => x.EnvironmentalActionPollutionPreventionIdeasForAction, new { Class = "form-control", Placeholder = Model.EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder, rows = "8" })
</div>
</div>
All other code is the same except the sames are different
Ok silly mistake, I had all 'data-item' the same should have been 'data-item-one', 'data-item-two' etc

Activate checkbox only when a particluar option in dropdown selected

I want to activate the checkbox 'id=IsHeighest', only when the option 2 of the dropdown list is selected. Otherwise disable it. Can anyone help me?
<spans>#MultiLang.Highest</spans>
#Html.CheckBoxFor(m => m.IsHighest, new { Id = "IsHighest" })
<div class="col-md-3 ltrlable">
<span class="rtllable dri">#MultiLang.Status</span>
#Html.DropDownListFor(m => m.StatusId, (IEnumerable<SelectListItem>)ViewBag.Status, new { id = "VehicleStatus", #class = "form-control" })</div>
You can do this with jquery
$(document).ready(function(){
$('#IsHighest').prop('disabled', true);
$('#StatusId').change(function () {
var selectedValue= this.value;
if(selectedValue=="2")
{
$('#IsHighest').prop('disabled', false);
}
else
{
$('#IsHighest').prop('disabled', true);
}
});
});

show and hide based on drop down list asp mvc 5

I am learning asp.net mvc 5.
My dropdownlistfor is working perfect and shows right field based on its value.
But the problem is when the page loaded first time it shows all field..
Problem is: I want default is showing nothing when the page first time loaded.
my cshtml:
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(m => m.PaymentMethod, ViewBag.PayTypeList as List<SelectListItem>, new { #class = "btn btn-primary btn-lg dropdown-toggle", #id = "PaymentId" })
<div id="PaypalButton">
<br/>
<script src="https://www.paypalobjects.com/api/button.js?"
data-merchant="braintree"
data-id="paypal-button"
data-button="checkout"
data-color="gold"
data-size="medium"
data-shape="pill"
data-button_disabled="true">
</script>
<!--data-button_type="paypal_submit"-->
</div>
<div id="EcheckForm">
<div class="form-group">
<div class="col-md-10">
#Html.TextBoxFor(m => m.VecInsNum, new { #class = "form-control input-lg", placeholder = "Vehicle Isurance Number", required = "required", tabindex = 18 })
#Html.ValidationMessageFor(m => m.VecInsNum, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
And Js:
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#PaymentId').change(function () {
var value = $(this).val();
if (value == '1') {
$('#PaypalButton').show();
$('#EcheckForm').hide();
} else if (value == '2') {
$('#PaypalButton').hide();
$('#EcheckForm').show();
} else {
$('#PaypalButton').hide();
$('#EcheckForm').hide();
}
});
});
When the page first time loaded:
When I select Paypal:
when I select E-check:
When I go back to Default:
First, create a function which contains hide methods inside it:
// hide all div options
function hideOnLoad() {
$('#PaypalButton').hide();
$('#EcheckForm').hide();
}
Then, call function above to hide all option div elements when page has loaded at first time and when default value being selected as given below:
$(document).ready(function () {
hideOnLoad(); // add this line
$('#PaymentId').change(function () {
var value = $(this).val();
if (value == '1') {
$('#PaypalButton').show();
$('#EcheckForm').hide();
} else if (value == '2') {
$('#PaypalButton').hide();
$('#EcheckForm').show();
} else {
hideOnLoad();
}
});
});
Simplified example: JSFiddle Demonstration

Preserve the hidden or visible state of initially hidden textbox on postback in mvc application

Given below is my script.My problem is I have a textbox which is hidden and is diplayed only when we select "other" from dropdownlist.On display when we enter a value after post back that value gets preserved but that textbox becomes invisible.on postback dropdown list value is however preserved and shown as "others" and only when I select someother value of dropdown and then again change it to "other" then textbox along with text gets displayed..how can I preserve that hidden or visible state of it on postback?
<script type="text/javascript">
$(document).ready(function () {
$('#SelectedCategoryId').change(function () {
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
});
});
</script>
My View
<div id="dropdown" class="form-control dropdown">
#Html.ValidationMessageFor(m => m.SelectedCategoryId, "*")
#Html.LabelFor(m => m.Category, "Department :", new { style = "display:inline;" })
#Html.DropDownListFor(m => m.SelectedCategoryId, new SelectList(Model.Category, "Value", "Text"), "SelectCategory", new { id = "SelectedCategoryId"})
#Html.ValidationMessageFor(m => m.Other, "*")
#Html.TextBoxFor(m => m.Other, new { id = "other", #class = "other" ,style = "display: none;" })
#Html.HiddenFor(m => m.SelectedCategory, new { id = "hiddenId" })
</div>
that's becaue you only check for the value of the select on "change" event. That doesn't happen when you load the page. Do it like that:
function toggleHidden() { //that's your code in a function
if ($('#SelectedCategoryId').val() === '5') {
$('#other').show(1000);
$('#other').change(function () {
var SelectedCategory = $('#other').val().toString();
$('#hiddenId').val(SelectedCategory);
});
}
else {
$('#other').hide(1000);
var SelectedCategory = $('#SelectedCategoryId option:selected').text();
$('#hiddenId').val(SelectedCategory);
}
}
$(document).ready(function () {
toggleHidden(); //execute the toggle on load
$('#SelectedCategoryId').change(toggleHidden); //execute the toggle on change
});

Dropdownlist Change event with javascript, when using an EditorTemplate

I have an EditorTemplate - which works great. Inside it, I have a dropdownlist which i decorate with a Class, and 2 divs
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
Im trying to show the 1 of the 2 divs based on the selection of the dropdown list
the dropdownlist populates fine, as is shown as a dropdown list with 2 items "Calendar" and "Email"
I have the following Javascript:
function checkSelection() {
$(".EmailDiv").hide();
$(".CalendarDiv").hide();
var selectedItem = $(this).val();
if (selectedItem == "Email") {
$(".EmailDiv").show();
} else if (selectedItem == "Calendar") {
$(".CalendarDiv").show();
}
};
var myobject = new checkSelection();
$(document).ready(function () {
checkSelection();
$(".TypeSelector").change(checkSelection);
checkSelection.apply($(".TypeSelector"));
});
The javascript file loads (I can see it in my firefox debugger)
But doesn't get hit for some reason.
Either of the divs do not show.
What am i doing wrong?
Enclose the html for each item in a container to make it easier to select relative elements
<div class="container"> // add this or similar
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
</div>
and the css
.EmailDiv, .CalendarDiv {
display:none;
}
Then the script (in the main view)
$(document).ready(function () {
// Set initial visibility
$('.TypeSelector').each(function(index, item) {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
}
});
// Update visibiity on selection
$('.TypeSelector').change(function() {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
container.find('.EmailDiv').hide();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
container.find('.CalendarDiv').hide();
} else { // this may or may not be necessary
container.find('.EmailDiv').hide();
container.find('.CalendarDiv').hide();
}
});
}

Categories