jQuery select value failing - javascript

I have done some research on this and everything said / suggested so far has failed to work.
I am trying to capture the input from a select tag, however nothing comes through, not even null.
The code:
function validateForm()
{
var name = $('#txtName').val();
var email = $('#txtEmail').val();
var tel = $('#txtTel').val();
var look = $('#lookingFor').val();
var goals = $('#goals').val();
alert(name + " " + email + " " + tel + " " + look + " " + goals);
return false;
}
HTML:
<select class="fomForm select" style="color:#777;"
id="lookingFor" name="lookingFor">
<option value="">I'm looking for</option>
<option value="">CYCLING</option>
<option value="">RUNNING</option>
<option value="">TRIATHLONS</option>
<option value="">TRAINING CAMPS</option>
<option value="">PERFORMANCE TESTING</option>
<option value="">DIET & NUTRITION</option>
<option value="">WELLNESS</option>
</select>
I apologise for asking this as there are quite a few resources on the internet however they don't seem to help this case. The name, email etc all display fine in the alert but the select boxes do not.
I have no errors in the console.

It is not showing because all the values in your select options are empty.
Try putting some value:
<option value="TRIATHLONS">TRIATHLONS</option>

you have no value in your select box option...so the alert is empty
<option value="">I'm looking for</option>
<option value="">CYCLING</option>
replace the value with the value u want....
<option value="iamlookingfor">I'm looking for</option>
......

$(function(){$(".fomForm").change(function(){
alert($(".fomForm option:selected").text()); })});
Take a demo in this fiddle: http://jsfiddle.net/tAxDv/

Seems like you are missing the value for options. They all say option=""
Put the value in there, and it should start working with $('#lookingFor').val()
If you don't have control on the html, or can't add values for whatever reasons, this should give you the text displayed in the option
$('#lookingFor option:selected').text()

Related

Trouble setting value of select input from success function of getJSON

I have an html page with a select input that is being used to filter a getJSON request in a function. In the success function of the request, I am dynamically creating an html table from the JSON and appending the table to a div in the html document. All is working fine, but the select input resets back to the default upon calling the function.
I am trying to set the select input back to the selected value so the end user know what data they are looking at. I have the class name of the select input stored in a parameter called p1Name and the selected value stored in a parameter called p1.
Normally I would use something like this: $('.ddlUserID').Val(p1); where the class name is hard coded in. But I need this function to be dynamic and need to use the parameter of p1Name for the class name. So I have tried:
var DDL1 = "'." + p1Name + "'";
$(DDL1).val(p1);
This returns the following error, Uncaught Error: Syntax error, unrecognized expression: '.ddlUserID'. I have also tried the javascript syntax of document.getElementsByClassName(DDL1).value = p1; which returns the same error.
If I change the parameter of DDL1 to the hard coded value of '.ddlUserID' the form works as expected.
What is the proper way to set the selected value of a select input when using a parameter as the id or class name?
You don't need to add extra quotation marks to your selector string.
var DDL1 = "." + p1Name;
$(DDL1).val(p1);
This should work
Leave out the extra quotes in var DDL1 = "'." + p1Name + "'";
Should be var DDL1 = '.' + p1Name;
It should work, you can use strings in the selector. I think you don't need the single quotes
var p1Name = 'ddlUserID'
var selector1 = `.${p1Name}`
var selector2 = '.' + p1Name
console.log('selector1:', $(selector1))
console.log('selector2:', $(selector2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ddlUserID">ddlUserID</div>
You can use .val() in JQuery to set the value of select inputs.
What is the proper way to set the selected value of a select input when using a parameter as the id or class name?
See this: https://stackoverflow.com/a/5891929/11860085.
$(document).ready(function(){
var p1 = "foo";
var p2 = "bar";
var p1name = "some_id";
var p2name = "some_class";
$( "#setValues" ).click(function() {
$('#' + p1name).val(p1);
$('.' + p2name).val(p2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="setValues">Set values</button>
<select id="some_id">
<option value="" disabled selected>Select something...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="foo">foo</option>
</select>
<select class="some_class">
<option value="" disabled selected>Select something...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="bar">bar</option>
</select>

How to build image name/path from two select/option id by Javascript

I'm trying to bulid an image path from two select fields. I have to use the "id"s because "value"s are used already. Unfortunatedly only the second select works. Does anyone have a hint? As you might see I'm not a coder. Could anyone be so kind and help to make the code more elegant/slim?
I use onchange to update the "result1" and "result2" allways when the user alters his selection.
Thanks in advance, Georg
Here is my code:
<script>
function showOptions1(s) {
document.getElementById("result1").innerHTML = "<img src='img/preview/" + s[s.selectedIndex].id;
}
</script>
<script>
function showOptions2(s) {
document.getElementById("result2").innerHTML = s[s.selectedIndex].id + ".jpg'>";
}
</script>
<select onchange="showOptions1(this)" id="my_select1">
<option value="werta" id="1">Text Item 1a</option>
<option value="wertb" id="2">Text Item 1b</option>
</select>
<select onchange="showOptions2(this)" id="my_select2">
<option value="wertc" id="3">Text Item 1c</option>
<option value="wertd" id="4">Text Item 1d</option>
</select>
<span id="result1"></span><span id="result2"></span>
I wouldn't use the onchange event because you want the user to select two things before building the path. So, put another button on the screen called "save image" or something like that. The onclick of this button gets the "value" of each select input and concats them together. You can easily get a handle to the select inputs using jquery by name
var select1 = $("#my_select1");
Now your problem is that you don't want the value. That would be easy. Instead you want the select option and then you want to get the id. You can do that as follows
var my1id = $("#my_select1 option:selected" ).id;
Thanks a lot for your support. Cheers Georg
Finaly I use this code (and stick to onchange because I dont want another button because there are allready three of them):
<script>
var selection01, selection02;
showOptions1 = function(s) {
selection01 = "<img src='img/preview/" + s[ s.selectedIndex ].id;
getResult();
};
showOptions2 = function(s) {
selection02 = s[ s.selectedIndex ].id + ".jpg' width='200px;'>";
getResult();
};
function getResult() {
var total = selection01 + selection02;
console.log( total );
document.getElementById("Image").innerHTML = total;
};
</script>
<select id="select1" onchange="showOptions1(this)">
<option value="" id="01" selected>...</option>
<option value="werta" id="10">Text Item 1a</option>
<option value="wertb" id="20">Text Item 1b</option>
</select>
<select id="select2" onchange="showOptions2(this)">
<option value="" id="02" selected>...</option>
<option value="wertc" id="30">Text Item 1c</option>
<option value="wertd" id="40">Text Item 1d</option>
</select>
<hr><span id="Image"></span>

display:block not working on option tag

UPDATE : I test my code on firefox and everything was alright but on chrome :|
I have two different selecting drop lists . one for Province and another for cities.
I want to let users first select their Province then i show them cities selection list which is only containing cities of selected Province . my idea was to achieve it this way :
HTML
<select id="Province">
<option value = "1">Province1</option>
<option value = "2">Province2</option>
</select>
<select id = "CityList">
<option value = "1">city1</option>
<option value = "1">city2</option>
<option value = "2">city3</option>
</select>
cities with value one are inside Province with value one
jquery
$("#Province").change(function(){
$("#CityList option").css({'display':'none'});
var id = "#CityList option[value = " + $("#Province option:selected").val() + "]" ;
$(id).css({'display':'block'});
})
But the problem is none of the options will get visible again :|
And i checked if i'm selecting correct option by changing font color of it
I don't know why display : block is not working on them
If you just want to hide the options and then selectivly show them, hide and show are better options.
$("#Province").change(function(){
$("#CityList option").hide();
var id = "#CityList option[value = " + $("#Province option:selected").val() + "]" ;
$(id).show();
})

jQuery Selectmenu Plugin - Can't Hide Selectbox

I am using the "Selectmenu" plugin created by Filament Group. I can't provide a hyperlink because I haven't posted enough on Stackoverflow to use more than 2 hyperlinks.
I have 2 selectboxes; one listing s/w (tool) and one for tool version. I want to be able to select a tool, show the tool version selectbox and write version-specific data to the screen. This is working fine as long as the user does not select another tool before selecting a version.
When the user selects a tool w/out selecting a version, the previous version selectbox does not hide. For instance if the user select "cgs" then the "cgs versions" selectbox shows. But if the user does not select a version and instead selects another tool, say "dpss", the "dpss versions" selectbox appears but the "cgs versions" selectbox does not hide.
It should be as simple as this, which does not work:
$("select:not(#cgs)").hide();
I am placing it inside the If statement that checks for the tool version.
Javascript Pastie: http://pastie.org/2695842
HTML Pastie: http://pastie.org/2685522
Any help would be greatly appreciated.
Live demo (using the above-linked jQuery and HTML): at JS Fiddle: http://jsfiddle.net/davidThomas/Na9Wq/.
In case anyone is interested, I have it solved. I think my problem has something to do w/ the Selectmenu plugin. I started w/ example code and tried to make my code fit w/in it's structure. I'm sure someone w/ more Javascript experience than I can turn this into fewer lines of code.
Anyway, the secret was to create an ID for the fieldset containing the "tool" selectbox and then call the following code as soon as the tool is selected:
$('fieldset:not(#fs-tool, ' + tool + ')').hide();
This hides everything except the fieldset and selectbox for the selected tool.
$('select:not(#tool, ' + tool + ')').hide(); does not work here.
Also, I added "lasttool = tool;" for 1st run through, otherwise multiple version selectboxes will show depending on order in which user selects them.
These two changes allowed other scripts to be removed that made the code verbose. In the end, I'm not 100% sure why this works but I'm glad it does. Below is the final Javascript and HTML.
Javascript
$(document).ready(function(){
var tool; //The selected tool
var version; //The selected tool version
var lasttool; //The previously selected tool
$('select#tool').selectmenu({
// use select callback
select: function(event, options) {
tool = options.value;
$('select#'+tool).val("none"); //This resets the version selectbox to "Select a version". Otherwise the last version selected shows and the ".change(function(){..." does not fire.
$('fieldset:not(#fs-tool, ' + tool + ')').hide(); //Hide everything except the fieldset and selectbox for the selected tool.
//"$('select:not(#tool, ' + tool + ')').hide();" does not work here
if (tool == "cgs") {
lasttool = tool; //Set lasttool= tool for 1st run through, otherwise multiple version selectboxes will show depending on order in which user selects
$('select#'+tool).selectmenu({maxHeight: 150}).parent("fieldset").hide(); //Without this, the version selectbox won't show
$('select#'+lasttool).selectmenu({maxHeight: 150}).parent("fieldset").hide(); //Hide the last tool version selected
$('select#'+tool).parent("fieldset").show(); //This shows the version selectbox
$("#cgs").change(function(){
version = $(this).val();
document.getElementById("val_scenarios").innerHTML=(tool + " - " + version);
lasttool = tool; //Must keep track to hide later, if needed
});
} else if (tool == "dpss"){
$('select#'+tool).selectmenu({maxHeight: 150}).parent("fieldset").hide();
$('select#'+lasttool).selectmenu({maxHeight: 150}).parent("fieldset").hide();
$('select#'+tool).parent("fieldset").show();
$("#dpss").change(function(){
version = $(this).val();
document.getElementById("val_scenarios").innerHTML=(tool + " - " + version);
lasttool = tool;
});
} else if (tool == "elt5500"){
$('select#'+tool).selectmenu({maxHeight: 150}).parent("fieldset").hide();
$('select#'+lasttool).selectmenu({maxHeight: 150}).parent("fieldset").hide();
$('select#'+tool).parent("fieldset").show();
$("#elt5500").change(function(){
version = $(this).val();
document.getElementById("val_scenarios").innerHTML=(tool + " - " + version);
lasttool = tool;
});
} else if (tool == "iapioneer"){
$('select#'+tool).selectmenu({maxHeight: 150}).parent("fieldset").hide();
$('select#'+lasttool).selectmenu({maxHeight: 150}).parent("fieldset").hide();
$('select#'+tool).parent("fieldset").show();
$("#iapioneer").change(function(){
version = $(this).val();
document.getElementById("val_scenarios").innerHTML=(tool + " - " + version);
lasttool = tool;
});
} else {
$('select#'+lasttool).parent("fieldset").hide(); //Hide the last tool version selectbox when "Select a tool" is selected instead of an actual tool"
document.getElementById("val_scenarios").innerHTML=("Tool: " + tool + "; Version - " + version + "; Last Tool - " + lasttool);
}
}
});
});
HTML
<div id="tb" class="qualifier">
<form id="info" action="">
<fieldset id="fs-tool">
<select name='tool' id='tool'>
<option value="none" selected>Select a tool...</option>
<option value="cgs" >CGS/GXP</option>
<option value="dpss">DPSS</option>
<option value="elt5500">ELT5500</option>
<option value="iapioneer">IAPioneer</option>
</select>
</fieldset>
<fieldset>
<select id="cgs" name='cgs'>
<option value="none" selected>Select a version...</option>
<option value="cgs_1.0"> CGS 1.0/GXP</option>
<option value="cgs_1.1"> CGS 1.1/GXP</option>
</select>
</fieldset>
<fieldset>
<select id="dpss" name='dpss'>
<option value="none" selected>Select a version...</option>
<option value="dpss_2.0">DPSS 2.0</option>
<option value="dpss_2.0.7.29">DPSS 2.0.7.29</option>
</select>
</fieldset>
<fieldset>
<select id="elt5500" name='elt5500'>
<option value="none" selected>Select a version...</option>
<option value="elt5500_4.0">ELT5500 PRO 4.0/CGS 2.1</option>
<option value="elt5500_4.1">ELT5500 PRO 4.1/CGS 2.1</option>
</select>
</fieldset>
<fieldset>
<select id="iapioneer" name='iapioneer'>
<option value="none" selected>Select a version...</option>
<option value="iapioneer_2.1">IAPioneer/CGS 2.3.1</option>
</select>
</fieldset>
</form>
</div>
<br />
<div id="val_scenarios"></div>

Manually type in a value in a "Select" / Drop-down HTML list?

In a Windows Forms application, a drop-down selector list also gives the user the option of typing an alternate value into that same field (assuming the developer has left this option enabled on the control.)
How does one accomplish this in HTML? It appears as if it is only possible to select values from the list.
If it's not possible to do this with straight HTML, is there a way to do this with Javascript?
It can be done now with HTML5
See this post here HTML select form with option to enter custom value
<input type="text" list="cars" />
<datalist id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</datalist>
I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.
The good news is that selectize.js does exactly this:
Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)
EDIT: Browse all controls etc, here: http://www.sencha.com/products/js/
Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.
Example: http://jsfiddle.net/c258Q/
HTML code:
Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
<option value="apple">Apple</option>
<option value="orange">Apricot </option>
<option value="melon">Peach</option>
<option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>
JavaScript:
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["fruit_txt"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["fruit"];
var oDDL = oForm.elements["fruit_ddl"];
var oTextbox = oForm.elements["fruit_txt"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
And in the server side, read the value of "fruit" from the Request.
I love the Shadow Wizard answer, which accually answers the question pretty nicelly.
My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/
After typing new value, the form is ready to send, just need to handle new values on the back end.
jQuery is:
(function ($)
{
$.fn.otherize = function (option_text, texts_placeholder_text) {
oSel = $(this);
option_id = oSel.attr('id') + '_other';
textbox_id = option_id + "_tb";
this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
this.change(
function () {
oTbox = oSel.parent().children('#' + textbox_id);
oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
});
$("#" + textbox_id).change(
function () {
$("#" + option_id).val($("#" + textbox_id).val());
});
};
}(jQuery));
So you apply this to the below html:
<form>
<select id="otherize_me">
<option value=1>option 1</option>
<option value=2>option 2</option>
<option value=3>option 3</option>
</select>
</form>
Just like this:
$(function () {
$("#otherize_me").otherize("other..", "put new option vallue here");
});
Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.
http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx
But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

Categories