Need a solution to this javascript coding problem - javascript

I have a SELECT in a FORM.
This select is populated using js.
I need to add a "Selected" attribute to one of these options.
I get which one, by checking a MySql database to see the name of the community which needs to have a "selected attribute" added to it.
<select name="community" id="community">
//OPTIONS HERE
</select>
The filler() function:
function filler(com){
//com is the options which needs to be selected, this variables value comes from the mysql database
var community = document.getElementById("community");
var area = document.getElementById("area").value;
// area is just another input on the page which value also is fetched from mysql db. Each area has x communities, so I have alot of IF:s.
if(area == 'Blekinge') {
community.length = 6;
community.options[0].value = "Välj Kommun";
community.options[0].text = "-- Välj Kommun --";
community.options[0].id = "Välj Kommun";
community.options[1].value = "Karlshamn";
community.options[1].text = "Karlshamn";
community.options[1].id = "Karlshamn";
community.options[2].value = "Karlskrona";
community.options[2].text = "Karlskrona";
community.options[2].id = "Karlskrona";
community.selected = 0;
}
}
As you can see, "com" variable is the option which needs to have the "selected" attribute added to it.
I have over 30 of these if-statements, and I have no clue how to create a function to add this "Selected" attribute to the matching option.
So I have "com" which for example could be "Karlskrona" in the example above. How should I add the selected to it?
I need a simple function for this which works in all major browsers...

Set the selectedIndex property of the SELECT to whichever index you need. Zero-based, of course.

Just do
community.value = com;
example at http://www.jsfiddle.net/jMapA/

for(var i = 0; i < community.options.length; i++) {
if(community.options[i].id == com)
community.selectedIndex = i;
}

function selectOptionValue(selectId, value)
{
select = document.getElementById(selectId);
if (select)
{
for (var i = 0; i < select.options.length)
{
if (select.options[i].value == value)
{
select.options[i].selected = 'selected';
return true;
}
}
}
return false;
}
Use my function like this:
selectOptionValue('community', 'Karlskrona');

Related

Get the selected value in google app script

How to pass a select box value.
I have a spreadsheet where i want to filter based on a select box value.
I made a way to call the app function on form submit. But I am not able to pass one more parameter at the other side.
I want to filter based on the select box value and thereby retrieve the result from the spreadsheet on to the web app. This is my selectbox in html.
Select DATA
<select name ="productId" id="gettheVAL">
<option>DATA1 </option>
<option>DATA2 </option>
<option>DATA3 </option>
</select>
Can anyone guide me on this? I have called the function via this
form.on('submit', function(event){
event.preventDefault();
runner.withSuccessHandler(function(array){
for (var i = 0; i < array.length; i++) {
var item = '<tr><td>' + array[i] +'</td></tr>';
table.append(item);
}
}).retrieveValuesFromForm(this);
Update
Adding the function - retrieveValuesFromForm below:
function retrieveValuesFromForm(req) {
//var selectedvalue=$('input[name="gettheSelectValue"]:checked').val();// tried like this but $ is undefined here
var sheetActive = SpreadsheetApp.openById("SHEETID");
var sheet = sheetActive.getSheetByName("SHEETNAME");
var range = sheet.getRange('A:U');
var rawData = range.getValues();
var data = [];
for (var i = 0; i < rawData.length; i++) {
if ((rawData[i][2] == selectedvalue)) // Check to see if column 3 says selectedvalue if not skip it
{
//processing
}
}
return data;
}
Based on the assumption that you have a field in your form such as
<select name ="productId" id="gettheVAL">
In your form, You could call your Google App Script function with the following parameter
runner.withSuccessHandler(function(array){
...
}).retrieveValuesFromForm($("#gettheVAL").val());
You would then change the signature for retriveValuesFromForm
function retrieveValuesFromForm(selectVal) {
...
}
Here's how I pass a selected option and a few other things.
function sendText()
{
var culr=$('input[name="priority"]:checked').val();
var type=$('#sel1').val();
var txt=$('#txt1').val();
var obj={'type':type,'text':txt,'color':culr};
$('#txt1').css('background-color','#ffff00');
google.script.run
.withSuccessHandler(clearText)
.dispText(obj);
}
I'm guessing that you need to add this line into your head tag area.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Javascript validation on select input

I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating

Conditional drop down menu in javascript, problems with the selector

I have a conditional dropdown menu which works but it depends on where I put it on the page. If I don't put it in a specific position the positions in the menu don't fill at all. The problem is also that I want to add a second conditional dropdown, and that one doesn't work regardless of where I put it. So my question is: do I need to add the script twice on the page to correspond the two forms I have? I actually want both drop downs to fill with the exact same words.
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
I'm guessing it's something related with the [0] there. I tried adding an id to the form and then writing the the second script document.forms('myId')[] but that didn't work either. How should I go about doing this?
<script type="text/javascript">
var categories = [];
categories["startList"] = ["Programming","Science","History","Business and Economics","Software","Languages","Do it Yourself","Others"];
categories["Programming"] = ["Java","C++","C.","Python","Html","Php","Mysql","ObjectiveC","Android","Others"];
categories["Science"] = ["Mathematics","Physics","Biology","Chemistry","Medicine","Astronomy","Statistics","Others"];
categories["Others"] = ["All"]
var nLists = 2; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue( L2, L1) {
$.post( "", { List1: L1, List2: L2 } );
}
function init() {
fillSelect('startList',document.forms[0]['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
<form action="" method="post">
<select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>Category</option>
</select>
<select name='List2' onchange="getValue(this.value,this.form['List1'].value)">
<option selected >Subcategory</option>
</select>
<input type="Submit">
Fixed it. I just had to add either a selector or 1 there to correspond to my second form.
document.forms[1]['List'+i].length = 1;
document.forms[1]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue( L2, L1) {
$.post( "", { List1: L1, List2: L2 } );
}
function init() {
fillSelect('startList',document.forms[1]['List1'])

How might javascript to update dropdown options conflict with CakePHP's save?

This code causes my save to either flash "404 not found" when in a modal dialog or goes to a blank white page when in a separate tab.
Heres the code:
<script>
function changeSelection()
{
var value = $('#typeSelect').val();
var div = document.getElementById('sigType');
if(value >= 1 && value <= 3)
{
var signalTypeOptions =
<?php echo json_encode( array_values( $signalTypeOptions));?>;
var selection = document.getElementById('valueSelect');
selection.innerHTML = '';
var i = 0;
for(optionText in signalTypeOptions[value])
{
var option = document.createElement('option');
option.innerHTML = optionText;
selection.appendChild(option);
}
$(div).show();
}
else
{
$(div).hide();
}
}
</script>
The code is used to update the dropdown options for a secondary select element (valueSelect) based off of an initial select element (typeSelect).
I found that when a value is selected in the dynamically populated dropdown, the html doesn't reflect the selection.

How can I disable an <option> in a <select> based on its value in JavaScript?

I have a <select> with a number of <option>s. Each has a unique value. I need to disable an <option> with a given defined value (not innerHTML).
Anyone have an idea how?
JavaScript, in 2022
You can use querySelectorAll, and forEach off of the resulting NodeList to do this same thing more easily in 2022.
document.querySelectorAll("#foo option").forEach(opt => {
if (opt.value == "StackOverflow") {
opt.disabled = true;
}
});
Do be mindful of string-comparisons, however. 'StackOverflow' and 'stackoverflow' are not the same string. As such, you can call .toLowerCase() on strings before comparing, or even go with a case-insensitive regular expression comparison like the this:
if ( /^stackoverflow$/i.test(option.value) ) {
option.disabled = true;
}
Pure Javascript (2010)
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Without enabling non-targeted elements:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
###jQuery
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Without enabling non-targeted elements:
$("option[value='stackoverflow']").attr("disabled", "disabled");
​
Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Without enabling non-targeted elements:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
Set an id to the option then use getElementById and disable it when x value has been selected, like so:
<body>
<select class="pull-right text-muted small"
name="driveCapacity" id=driveCapacity onchange="checkRPM()">
<option value="4000.0" id="4000">4TB</option>
<option value="900.0" id="900">900GB</option>
<option value="300.0" id ="300">300GB</option>
</select>
</body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){
document.getElementById("driveCapacity").value = "4000.0";
document.getElementById("4000").disabled = false;
}else{
document.getElementById("4000").disabled = true;
}
</script>
For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:
Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;
or
selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;
The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one. Also the first one uses Array.find and arrow functions that are not available in IE11.
Use a straightforward selector:
document.querySelector('select[name="theName"] option[value="theValue"]').disabled = true;
Here with JQuery, if anybody search it:
var vals = new Array( 2, 3, 5, 8 );
select_disable_options('add_reklamaciq_reason',vals);
select_disable_options('add_reklamaciq_reason');
function select_disable_options(selectid,vals){
var selected = false ;
$('#'+selectid+' option').removeAttr('selected');
$('#'+selectid+' option').each(function(i,elem){
var elid = parseInt($(elem).attr('value'));
if(vals){
if(vals.indexOf(elid) != -1){
$(elem).removeAttr('disabled');
if(selected == false){
$(elem).attr('selected','selected');
selected = true ;
}
}else{
$(elem).attr('disabled','disabled');
}
}else{
$(elem).removeAttr('disabled');
}
});
}
I would like to give you also the idea to disable an <option> with a given defined value (not innerhtml). I recommend to it with jQuery to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed option when current Status is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
https://jsfiddle.net/chetabahana/f7ejxhnk/28/
You can also use this function,
function optionDisable(selectId, optionIndices)
{
for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
{
document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
}
}

Categories