Use a variable created using javascript in HTML - javascript

Using JavaScript I get the selected value of this select:
<select class="form-control pull-right" name="Type" id="Type" tabindex="" >
<option>-Type-</option>
<option value="1">Re</option>
<option value="2">Cre</option>
<option value="3">Ca</option>
</select>
var drop = document.getElementById("Type")
alert(drop.value)
I want use the variable gotten by JavaScript in the same HTML file. How can I do it?
In HTML I want something like this:
<div class="col-xs-12 col-sm-3 col-md-3">
{{.TYPE.Account_Number}}
</div>
so that while displaying Account number is dynamic depending on the selected value

I'm not sure what you are trying to do but here is a start point for you.
Use some jQuery events to hook the user actions to the code - in this case I would use change() event to display the selected value dynamically on the page.
Here is a sample code and demo:
JSnippet Demo
$('#Type').change(function(){
//Get selected value:
var selectedValue = $(this).val();
var selectedText = $(this).children(":selected").text();
//Set result:
$('div').text(
"Type Value:" + selectedValue +
" Type name:" + selectedText
);
});

Related

How to update a dropdown list dynamically using JQuery?

I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
Try this solution:
$.each(items, function (i, value) {
$('#boardingDropdown').append($('<option>', {
value: value_value,
text : text_value
}));
});
The output should be something like this:
<select title="Select pickup city" id="boardingDropdown">
<option value="value_value">text_value</option>
</select>
Instead of:
let $boardingOption = $("<option>" + value + "</option>");
you should use:
let boardingOption= "<option>" + value + "</option>";
And in your code:
$(#boardingDropdown").append($boardingOption);
you missed a quote mark, it should be: $("#boardingDropdown")
Finally, according to my corrections, it should become:
$("#boardingDropdown").append(boardingOption);
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
<select title="Select pickup city" id="boardingDropdown">
</select>
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
<div>
<label>Boarding Point </label>
<div id="boardingDropdown"></div>
</div>
Then in the jquery, I appended the <select> tag as well:
$.getJSON(busApi, function (boardingPoints) {
let opt = '<select>';
$.each(boardingPoints, function (index, value){
opt += '<option value="' + index + '">' + value + '</option>';
});
opt += '</select';
$("#boardingDropdown").append(opt);
});
Now it is working as expected. :)

HTML Dropdown Box with Search and Input

I've tried to search for what I'm after, and this is the closest I can get:
Make a Dropdown with Search Box using jQuery (by Yogesh Singh)
https://makitweb.com/make-a-dropdown-with-search-box-using-jquery/
It can provide a HTML Dropdown with Search capability.
However, what I hope to have is to have input capability as well. I.e., if nothing found, then use the user input as the result.
I tried to look at the code,
$(document).ready(function(){
// Initialize select2
$("#selUser").select2();
// Read selected option
$('#but_read').click(function(){
var username = $('#selUser option:selected').text();
var userid = $('#selUser').val();
$('#result').html("id : " + userid + ", name : " + username);
});
});
UPDATE: using datalist. Requirement:
if found, use found value as the result.
if nothing found, then use the user input as the result.
Maybe both are the same case, but I don't know js well to say that.
$(document).on('change', '#place', function () {
$("#fax").val($("#place").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="place" list="places">
<datalist id="places">
<option value="WVC" label="503-882-1212"></option>
<option value="HAM" label="612-883-1414"></option>
<option value="WON" label="317-445-8585"></option>
</datalist>
<br>
<input type="text" id="fax">
I don't see an easy way to do that myself, as I don't know js quite well.
It is possible, to use the user input as the result if nothing found? thx
<datalist> is like a separate select element and linked to the text field previous to it and simply updates the value of textfield based on what is selected. If you like to run your code based on change event on the text field, you need to read the datalist first and then pick the label from it. If there is no value, then pick the text from the textfield.
$(document).ready(function () {
$(document).on('change', '#place', function () {
let myString =
$(this).next().find("option[value='" + $(this).val() + "']").prop("label");
myString = myString ? myString : $(this).val();
$("#fax").val(myString);
$(this).val(myString); //IF YOU LIKE TO SHOW SAME STRING IN TEXT FIELD TOO
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="place" list="places">
<datalist id="places">
<option value="WVC" label="503-882-1212"></option>
<option value="HAM" label="612-883-1414"></option>
<option value="WON" label="317-445-8585"></option>
</datalist>
<br>
<input type="text" id="fax">

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>

jQuery getting selected option of dynamically rendered dropdown list

I am working on an MVC + jQuery project, I am creating dropdown list on runtime. After rendering while submitting form through jQuery, I am trying to get selected value. Drop down is rendered and working fine
Also I can check in source code. I am trying to get dropdown list by
$('#Monday_Periods').children('.PeriodRow').each(function () {
var elements = $(this).html();
var found = $('.Subject', elements);
});
I found all objects in variable found, and I can see it in Chrome debug
But after this I am unable to get selected value. As you can see in debug mode that no option is selected. I tried to get by val or text but no luck. Anybody can tell me that how I can get selected value
$(this).html(); is loosing the reference to the DOM (html() returns a String, not a DOM node).
Try to modify in:
var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
console.log($(this).val());
}
or use directly (you already have an id on it!):
$('#subject1').val();
EDIT: SNIPPET ADDED
function printResults(){
$('#Monday_Periods').children('.PeriodRow').each(function () {
var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
console.log($(this).val());
});
});
}
$('#print-results').click(printResults);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Monday_Periods">
<div class="PeriodRow">
<select class="Subject">
<option value="none">-- Select Subject --</option>
<option value="1">Biology</option>
<option value="2">Physics</option>
</select>
<select class="Subject">
<option value="none">-- Select Subject --</option>
<option value="1">Biology</option>
<option value="2">Physics</option>
</select>
</div>
<button type="button" id="print-results">PRINT RESULTS</button>
</form>

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