Setting the original dropdown text back in jquery - javascript

I am trying to select a different value from a dropdown and checking a logic based on the newly selected text from the dropdown list and comparing the text entered in a textbox. If the selected dropdown text and the text box value fails the logic, i want to revert back to the original text that was previously showing in the dropdown box.
For ex: In my dropdown box, i have values as "Valid", "Invalid", "PCR IN", "PCR OUT" and the dropdown already displays "Valid". If the user changes the value from "Valid" to "PCR IN" and the 2nd textbox value if changed to a negative number, i am throwing an error via bootbox to the user, saying the textbox value should be in positive.
But i needed to change the original value to "Valid" that was showing in the dropdown before the user changed to "PCR IN". My code is not functioning as desired. It puts a empty result in the dropdown [attached]
My code below:
My MVC View page for creating the dropdown model:
#Html.DropDownListFor(model => model.FundingStatusId, new SelectList(ViewBag.FundingStatusDdl, "FundingStatusId", "FundingStatusName"), "Select Fund Status", htmlAttributes: new { #class = "form-control rtscustomtextboxright", #id = "fundingstatus" })
$(function () {
var fundingStat = $("#fundingstatus option:selected").text();
$("#fundingstatus").change(function () {
if ($("#fundingstatus option:selected").text() == 'PCR IN') {
// debugger
if (parseFloat($('#additionalFunds').val(), 10) > 0) {
bootbox.alert({
title: "ERROR - Please fix this",
size: "lg",
message: "<br><br><br>Additional Funds must be a NEGATIVE $ amount"
})
// return false;
$("#fundingstatus").val(fundingStat);
}
}
})
});

I believe you're using the .val() method wrong.
var fundingStat = $("#fundingstatus option:selected").text();
$("#fundingstatus").val(fundingStat); // you set the val for the option's text and not its value.
You don't mention the dropdown's code in your question so I can't write the fix but checkout the following explanation:
if we have the following dropdown:
<div class="test">
<select>
<option value="a">First Choice</option>
<option value="b">Second Choice</option>
<option value="c">Third Choice</option>
</select>
</div>
In order to set the selected option we should use the .val() with the value and not the text().
$(".text select").val("b"); // will select the "Second Choice"
And not:
$(".text select").val("Second Choice");

Related

Remove Value When an option is deselected

Edit:: What I am trying to achieve is I am getting each option text not the value, so I can send it to an API. Getting the text from the select works perfectly. I want to remove it when I deselect an option from the input value when I click it again. For example if I select multiple I get Medit-4-packs, Swiss-Gear-Bag When I click it one by one it removes it but when I deselect multiple I get the value of another. I want to replace the value as empty when deselected like usual. Hope it helps to clarify
Any help on using jquery to deselect Select option from input value? These are what I have tried so far. Thanks for help
Trying to remove the values in the <input> when option gets deselected.
<input class="form-check-input" type="text" value="" id="equipment" name="equipmentitems" >
<select multiple class="image-picker show-labels show-html" data-limit="16" name="packages[]" id="group_psoft">
<option value=" " data-img-class="first" selected></option>
<option data-img-src="/images/" data-img-label="Scanner Tips(4Pcs)" name="packs" data-img-alt="KeepSame" value="400" >Medit-4-packs</option>
<option data-img-src="/images/" data-img-label="SwissGear Bag" name="bagoriginal" data-img-alt="Aggresive" value="200"> Swiss-Gear-Bag</option>
</select>
Js
$('.image-picker').imagepicker({
show_label: true,
limit: 15,
//This is setting the text in the input
selected: function($items) {
$('#equipment').val($(this).find('option:selected').text());
},
// Here I want to remove it if clicked again
changed: function(){
$('#equipment').val($(this).unbind('option:selected').text()); // This removes it but add all the other options text in the input
$('#equipment').val($(this).unbind('option:selected').val( )); // Here It removes it but I get the value of the next selected option.
$('#equipment').val($(this).unbind('option:selected').text(' ' )); This I get Js [object,object]
}
});
I solved it when I move the code outside the function. I also changed unbind() to on() method.
$('.image-picker').on('change', function() {
$('#equipment').val($(this).find('option:selected').text());
});
Try this and see if it works out.
$('.image-picker').imagepicker({
show_label: true,
limit: 15,
//This is setting the text in the input
selected: function($items) {
$('#equipment').val($(this).find('option:selected').text());
},
// Here I want to remove it if clicked again
changed: function(){
var equiValue = $('#equipment').val();
var selectedValue = $(this).find('option:selected').text();
if(equiValue === selectedValue) {
$('#equipment').val("");
}
}
});

Clear corresponding text-input when dropdown 'no/other' value is selected

CURRENT: Dropdown choice of 'Yes/No'.
'Yes' = Show 'additional' dropdown/inputs to be entered
'No' = Hide 'additional' dropdown/inputs
WANT: I want to make it so if the user chooses 'Yes', then enters something into the 'additional' dropdowns/inputs, but then decides to switch their original answer back to 'No', make it clear the 'additional' values.
This is so when the form submits, i wont be carrying over any values in the POST that aren't needed.
HTML
<section><style>.required {color:#ff0000;font-weight:bold;position:absolute;}</style>
<div class="section_header">LNB INFORMATION</div>
<label>Did you install an LNB?<span class="required">*</span> </label>
<select class="DropdownClass" name="lnb_choice" id="lnb">
<option disabled selected value="">Select... (Required)</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<br>
<div class="LNBChoice DivElement1">
<select class="DropdownClass qrt" name="lnb_type" id="lnb_type">
<option value="">Type...</option>
<option value="3D2RBLNB">REV 3 LNB</option>
<option value="5D2RBLNB">REV 5 LNB</option>
<option value="SL3S4NR2">SWM3 LNB</option>
<option value="SL5S4NR2">SWM5 LNB</option>
<option value="SL5K4NR1">KAKU LNB</option>
</select>
<input type="text" id="lnb_barcode" name="lnb_barcode" placeholder="LNB Serial..." class="scantype basic" />
</div>
</section>
JS + Jquery 1.10.1
$(".DropdownClass").change(function () {
if ($(this).attr('name') == 'lnb_choice') {
var number = $(this).val();
$('.LNBChoice').hide().slice( 0, number ).show();
}
});
JSFIDDLE: https://jsfiddle.net/ra1t9jfL/
Additional issue: This is all part of a ,
If there is an error, i return them back to this page, using &field=value on the url to return values to the corresponding text input boxes/dropdowns.
I am able to return the 'Yes' value to the dropbox, but it does not activate the 'Show additional jquery'.
So the user has to select, 'No' then back to 'Yes' for the 'additional' to show up.
Add these two lines before or after $('.LNBChoice').hide().slice( 0, number ).show();
$('#lnb_type').val('');
$('#lnb_barcode').val('');
To clear the additional fields when the user selects "No" from the first drop down, you can add this which will do that:
$('#lnb').change(function() {
if($(this).val() === '0') {
/* User selected "no" so reset the additional field values */
$('#lnb_type').val('');
$('#lnb_barcode').val('');
}
});
To initialise the form based on values passed from the query string of the URL (ie on return from error screen), you could take the following approach:
/* Add the following script to your page */
$(function() {
/*
Access query string of url, remove preceding "?", and split
query string by "&" to return an array of "field=value" sub-strings
if any exist. Iterate the array of these sub-strings with forEach
*/
location.search.slice(1).split('&').forEach(function(part){
/* Split current sub-string by "=" to obtain name and value */
var nameValue = part.split('=');
var name = nameValue[0];
var value = value[1];
​
/* Select form element by name and initialise the value */
$('[name="' + name + '"]').val(value);
});
});

Make select box change values when another value is selected from another select box

I want my select box to change depending which option I choose in the first select, and I want to hide the values that are not from that option/
My HTML here:
<select id="localidad">
#foreach (ja_era.Models.Localidades localidad in ViewBag.localidades)
{
<option value="#localidad.Id">#localidad.Zona</option>
}
</select>
<select name="Localidad" id="barrio">
#foreach (ja_era.Models.Barrios barrio in ViewBag.barrios)
{
<option class="#barrio.Localidad" value="#barrio.Id">#barrio.Barrio</option>
}
</select>
The Localidad select has 4 options and bring the countries, then I have the second select that brings the cities all in one select box. Which ones are well defined in my database.
You can see here that "Barrios" has the column localidad where I insert the localidad id
I have tried some js code but can't figure it out how to make it work.
$(document).ready(function() {
$('#localidad').change(function () {
});
})
Basically you need to get the value of the selected option of the first dropdown, send it to your an action method and let it return the data for the second dropdown in json format. Then you will go through the items in the JSON array and build the markup for the options in the second dropdown.
$(document).ready(function() {
$('#localidad').change(function () {
var v = $(this).val();
var urlToGetData="#Url.Action("GetBarrios","Home")";
var items="";
$.getJSON(urlToGetData+"?id="+v,function(a,item){
items+="<option value='"+item.Value+"'>"+item.Text+"</option>";
})
$("#barrio").html(items);
});
})
Assuming you have GetBarrios action method like this
public ActionResult GetBarrios(int id)
{
var items=db.Barrios.Where(s=>s.Localidad==id)
.Select(s=> new SelectListItem {
Value=s.Id.ToString(),
Text = s.Barrio
}).ToList();
return Json(items,JsonRequestBehaviour.AllowGet);
}

AngularJS directive for "html select required"

Another day with another question. I'm working again on my web application. Now I got a problem. THe 'required' attribute is not supported in major browsers
(http://www.w3schools.com/tags/att_select_required.asp)
, it only works if the first option value is empty. Well that works fine, the submit event does nothing if the form is $invalid and it is when it's left by "Please select".
Land*:<br />
<select id="countries" name="country" data-ng-model="contact.country" required required-select>
<option value="">Please select</option>
<script type="text/javascript">
$(document).ready(function () {
var countries = {};
if (countries.length > 0) {
return countries;
} else {
$.get('WebKalkTool/country_de.xml', function(data) {
countries = data;
var that = $('#countries');
$('name', countries).each(function() {
$('<option />', {
text: $(this).text(),
}).appendTo(that);
});
}, 'xml');
}
});
</script>
</select>
<span class="error" data-ng-show="mandatory">Please select an item</span>
</p>
What I'm searching is a directive which checks if the value is empty, and then shows
the error after submit and if they select an item, the error vanishes.
Now the directive should maybe look something like this:
authApp.directive('requiredSelect', function () {
return {
require: 'select',
link: function (scope, formElement, attr, formSelect) {
console.log('FORM : Linker called');
console.log(formSelect);
console.log(formSelect.selected.value); // is undefined..
scope.$watch(formSelect.selectedIndex.value, function () {
console.log("index changed"); // Always log when another index is selected
if (formSelect.selectedIndex.value == "") {
console.log("value="");
// only show error after submit OR has visited on span id mandatory (or add new template?
// Tell the form, it's invalid, select is invalid
} else if (formSelect.selectedIndex.value != "") {
console.log("index > 0");
// everything is fine, select is valid
} else {
console.log("FORMSELECT.SELECTINDEX = UNDEFINED");
// just 4 testing my link
}
});
}
};
});
I took out the HTML5 validation because of compatibility thoughts and HTML5 validation shows only the first hint anyway.
It should be something equals like 'required' attribute for input fields and work the same way, I don't want to make my submit button disabled. Maybe I also can remove this "Please Select" option and leave it empty.
Or maybe I'm just not that clever enough to do something equal like:
<span class="error" data-ng-show="requestForm.place.hasVisited && requestForm.place.$invalid">Required!</span>
Doesn't matter if we check the value or the selectedIndex, whatever.
Thanks for your help and regards
Anthrax
AngularJs already know how to treat the required attribute (see here). In your case you might want to do something similar to that :
<form name="myForm">
<select name="country"
ng-model="country"
ng-options="c.name for c in countries"
required>
<option value="">-- chose country --</option>
</select>
</form>
Then up to you to display an error message when your form and/or select is marked as invalid by Angular or after a click on the submit button.
// Inline validation appears directly when select value is empty
<span class="error" ng-show="myForm.country.$error.required">Required!</span>
// Or after a click on submit, assuming you have set a boolean to show/hide error
<span class="error" ng-show="validationFailed">Required!</span>
I have assembled a working example with the 2 possibilities here.

Updating Textbox's info upon selecting listbox item using javascript

I'm trying to update Textbox's with the selected items info(properties). Can I get the selected Items Name instead of the Id, or in other words how can I get the properties of whats in my ViewData in the javascript upon selecting an item and then set it to a txtbox?
#Html.ListBox("ListBoxName", new SelectList((IEnumerable<Epic>)ViewData["selectedestimate"], "Id", "Name", "EstimatedTime"), new {#class = "ListBoxClass", #style = "height: 325px;"})
#Html.TextBoxFor(model => model.Name, new {#class = "TimeClass"})
<script type="text/javascript">
$(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
// get items properties and info so that the value can be set to a textbox
//set textbox value to Name of selected Value
$(".TimeClass").val(selectedid);
event.preventDefault(); // Stop the browser from redirecting as it normally would
$.get('#Url.Action("UserStoriesList", "Estimate")', { id: selectedid }, function (result) {
$('#stories').html(result);
});
});
});
</script>
A ListBox is like a DropDownList except that it allows for multiple items to be selected. It uses the same HTML tag (<select>) but it adds the multiple attribute. So when rendered your markup will look like this:
<select id="ListBoxName" name="ListBoxName" multiple="multiple">
<option value="id1">text 1</option>
<option value="id2">text 2</option>
<option value="id3">text 3</option>
...
</select>
So as you can see you have information about the id and the text inside the DOM. If you wanted to fetch some other information about the selected item you will need to send an AJAX request to the server and pass the selected id to retrieve it. So if you only wanted to show the text:
$(function() {
​$('.ListBoxClass option')​.click(function() {
if ($(this).is(':selected')) {
var selectedId = $(this).val();
var selectedText = $(this).text();
$('.TimeClass').val(selectedText);
...
}
});​
});
The click handler will run everytime the user clicks on an element in the listbox but the if condition will be satisfied only if he selected the item.

Categories