Change Javascript function from checkbox to select - javascript

I have a function that based on a checkbox id determines a price value. This works fine except I need to change the checkbox to a select. I tried to change the line:
if(peo14.checked==true)
To this:
if(peo14.select==Yes)
This did not work...how do I alter this to a Yes/No select?
function peoPrice()
{
var peoPrice=0;
//Get a reference to the form id="quicksheet"
var theForm = document.forms["quicksheet"];
//Get a reference to the checkbox id
var peo14 = theForm.elements["peo14"];
//If they checked the box set peoPrice to value
if(peo14.checked==true)
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}

You have to use the .options property and choose the selected index, then get the value of that index.
if (peo14.options[ peo14.selectedIndex ].value === 'Yes') {
peoPrice = 199;
}

Select Box
<select id="peo14" name='peo14' >
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
function peoPrice()
{
var peoPrice=0;
var e = document.getElementById("peo14");
var peo14val = e.options[e.selectedIndex].value;
if(peo14val=="Yes")
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}

Related

Copy selected multiple values to the text box

I have drop down list as below.
<select id="checkOwner" multiple="multiple" onchange="copyValue()">
<option value="FIRSTNAME">First Name</option>
<option value="LASTNAME">Last Name</option>
</select>
I used Below javascript to add checkbox
$(function() {
$('#checkOwner').multiselect({
});
});
I used below javascript to copy selected value to text field.
function copyValue() {
var dropboxvalue = document.getElementById('checkOwner').value;
document.getElementById('mytextbox').value = dropboxvalue;
}
But the problem is, this copy only one value. I want to copy all the selected values. How can I do this?
Loop through the option and put selected values in a string and then output the string on the textbox
function copyValue() {
var str = "";
for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = str;
}
}
my approach is loop on the options then check the condition if isSelected
html
<select name="checkOwner" multiple="multiple" onchange="copyValue(this)">
js
const copyValue = me => {
let y = Array.from(document.querySelectorAll('select option')).map(x => x.selected ? x.value : '')
document.getElementById('mytextbox').value = y.join(' ');
}

Set multi select options from stored localstorage values

I am trying to set multiple select options to selected, based on the corresponding localstorage value.
Storing the values in an array in localstorage is working, but I need help selecting the options in a form based on these values..
The values in localstorage are collected from checkboxes like so:
jQuery(document).ready(function(){
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
checkboxes = jQuery(".add-selectie :checkbox");
checkboxes.on("change", function(){
checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
jQuery.each(checkboxValues, function(key, value) {
jQuery('#' + key).prop('checked', value);
});
});
This saves the values in an array with the key "checkboxValues" in localstorage like so:
{"value1":true,"value2":true,"value3":false}
But how do I pre populate select options in a form if the value is found in localstorage AND set to true?
I made this pen containing all above code + a demo form. Any help would be greatly appreciated!
The code below should give you snippets to update selected state of option elements by reading values from localStorage.
Please note that there is a security issue in using localStorage in stackoverflow execution context so
I created a custom singleton/static class CustomLocalStorage having similar methods.
Additionally I've used a complete object OptionValueObject to back
the properties of checkbox and select elements.
var CustomLocalStorage = (function() {
var items = {};
function getItem(itemKey) {
for (var _itemKey in items) {
if (_itemKey === itemKey) {
return JSON.parse(items[itemKey]);
}
}
return null;
}
function setItem(itemKey, itemValue) {
items[itemKey] = JSON.stringify(itemValue);
}
return {
getItem: getItem,
setItem: setItem
}
})();
function OptionValueObject(id, label, value) {
this.id = id; // Used to identify checkboxes
this.label = label; // Not used in this example
this.value = value; // To bind it to select > option > value property
this.checked = true; // To bind it to checkbox > checked property
}
$(document).ready(function() {
function initialize() {
initializeData();
initializeUi();
}
function initializeData() {
var optionValueObjects = [];
optionValueObjects.push(new OptionValueObject(1, 'Label of option 1', 'value1'));
optionValueObjects.push(new OptionValueObject(2, 'Label of option 2', 'value2'));
optionValueObjects.push(new OptionValueObject(3, 'Label of option 3', 'value3'));
CustomLocalStorage.setItem('options', optionValueObjects);
}
function initializeUi() {
var optionValueObjects = CustomLocalStorage.getItem('options');
for (var i = 0; i < optionValueObjects.length; i++) {
var optionValueObject = optionValueObjects[i];
var id = optionValueObject.id;
// Checkbox: Identify element and set UI related property
var checkboxElement = $('#checkbox' + id);
checkboxElement.prop('checked', optionValueObject.checked);
console.log(optionValueObject.value);
// Option: Identify element and set UI related property
var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
optionElement.prop('selected', optionValueObject.checked);
}
}
function handleEvents() {
function checkboxChangeHandler() {
// Get the object, update the checked property and save it back
// 1. Get the object
var id = $(this).prop('id');
var optionValueObjects = CustomLocalStorage.getItem('options');
var optionValueObject = optionValueObjects.filter(function(optionValueObject) {
if (('checkbox' + optionValueObject.id) === id) {
return optionValueObject;
}
})[0];
// 2. Update the checked property
var checked = $(this).prop('checked');
optionValueObject.checked = checked;
// Bind the checked property to options selected property
var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
optionElement.prop('selected', optionValueObject.checked);
// 3. Save it back
CustomLocalStorage.setItem('options', optionValueObjects);
}
$('#checkbox1').change(checkboxChangeHandler);
$('#checkbox2').change(checkboxChangeHandler);
$('#checkbox3').change(checkboxChangeHandler);
}
initialize();
handleEvents();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-selectie">
<input id="checkbox1" class="selector" type="checkbox"><label for="checkbox1">Value 1</label>
<input id="checkbox2" class="selector" type="checkbox"><label for="checkbox2">Value 2</label>
<input id="checkbox3" class="selector" type="checkbox"><label for="checkbox3">Value 3</label>
</div>
<form>
<select id="optionsSelect" multiple="multiple">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
</form>

Is there any handler that can detect if a select field has any option selected without jQuery

When an option is selected that wasn't previously, the onChange handler can detect this. How can a preselected option be detected (i.e., whether a select field has any option selected)? Is this possible without jQuery? Is there a handler, such as onSelected (not the same as onSelect for highlighted text) for this event?
Example:
<select onSelected="FunctionRunIfOptionSelected()">
<option> ... </option>
...
</select>
The preselected option will have been selected on page load. i.e., with the HTML dynamically rendered:
<option selected> ... </option>
If I understand, the task is to tell if an option has the selected attribute hard-coded into the HTML? If so, this should work:
function test () {
var opts = document.getElementById("myselect").options;
var i, len = opts.length;
for(i = 0; i < len; i++) {
if (opts[i].getAttribute("selected" ) != null ) { // opts[i] has the selected attribute
change_other_select(i); // pass the option index to your other function
break;
}
}
}
window.onload = test;
The trick is to distinguish between the selected property and the selected attribute, and also between a null value and an empty string.
var myselect = document.getElementByid('selectid');
myselect.options[myselect.selectedIndex];
To test for selected option on page load, you'll need to catch these in the window.onload handler
One the page is loaded you'll need to continue to use the onChange handler, but use selectedIndex property to test if this is populated with an index within your option list.
Alternatively give your options values in the HTML and check the values themselves. This will allow deterministic behavior when expanding the option list.
Yes, using the .options[] and .selectedIndex methods you can handle this cleanly and unobtrusively like so:
HTML
<select name="select" id="select">
<option value="">...</option>
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>
JavaScript
window.onload = function(){
var select = document.getElementById("select"), selected = select.value;
select.onchange = function(){
var val = select.options[select.selectedIndex].value;
if(val != selected) {
alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
} else {
alert("Same value as the default of " + selected + " was selected");
}
};
};
From within the JS, you can check and manipulate the val variable as you like.
You can detect if the select field does not have the default value selected like this:
var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
if (selects[i].selectedIndex != 0) {
eval(selects[i].getAttribute("onSelected"));
}
}

How to get checkbox value in multiselect onchange event

I implement jquery multiselect and its working properly now i need to add extra feature that when a user select another option in dropdown ( check another checkbox ) then i want to get the value of the related option
in above picture in did not insert checkbox it is automatically inserted by jquery now i want that if i select the check =box with XYZ then i want to get the value of XYZ which is the id of XYZ
here is how i implemented it
<select multiple="multiple" id="CParent" name="parent" class="box2 required">
#foreach (var item in Model.Categories.OrderBy(c => c.Name))
{
if (Model.Coupon.Categoryid.Id == item.Id)
{
<option selected="selected" value="#item.Id">#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
and it is how it looks like after rendering in browser source
Thanks in advance for helping me .
what i tried yet
$('#CParent input:checked').change(function () {
var parentid = $(this).val()+'';
var array = parentid.split(",");
alert(array);
getchildcat(array[array.length -1]);
});
});
Edit
Code to initialize multiselect
$("#CParent").multiselect({
header: "Choose only THREE items!",
click: function () {
if ($(this).multiselect("widget").find("input:checked").length > 3) {
$(warning).show();
warning.addClass("error").removeClass("success").html("You can only check three checkboxes!");
return false;
}
else if ($(this).multiselect("widget").find("input:checked").length <= 3) {
if ($(warning).is(":visible")) {
$(warning).hide();
}
}
}
});
try this
$('#CParent').val();
this will give you the selectbox value
OR
from docs
var array_of_checked_values = $("#CParent").multiselect("getChecked").map(function(){
return this.value;
}).get();

How do i manipulate select box using jquery?

I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight

Categories

Resources