HTML Dropdown Box with Search and Input - javascript

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">

Related

Jquery - setting value of <input> - function is called, but values not set

I'm trying to use jquery to set the value of some tags. This is for a the admin side of a wordpress widget which will store a list of records, keyed by a date that are retrieved by using a <select>. In order to achieve this I'm having to to some janky value storage in data-* attributes to link the contents of three hidden <select> lists.
The idea is that the hidden list's values are retrieved by grabbing the visible <select>'s selected <option>'s data-date attribute value and grabbing the <option> in each hidden <select> that has a matching data-date. These values are then put into <input> fields for the user to edit.
HTML fragment
<label for="spdates">Special Dates:</label>
<p>
<select id="spdates">
<option data-date='new' value='new'>New Date</option>
<option data-date='23/05/1992' value='23/05/1992'> 23/05/1992-jake</option>
<option data-date='15/08/1997' value='15/08/1997'> 15/08/1997-rebecca</option>
<option data-date='17/03/1995' value='17/03/1995'> 17/03/1995-clive</option>
</select>
</p>
<p>
<label for="spname">Special Name:</label>
<input class="widefat namspani" id="spname" type="text" value="" />
</p>
<p>
<label for="sptext">Special Text:</label>
<input class="widefat namspani" id="sptext" type="text" value="" />
</p>
<p>
<label for="spdate">Special Date(dd/mm/yyyy):</label>
<input class="widefat namspani" id="spdate" type="date" value="" />
</p>
<p>
<label for="spimage">Special Image:</label>
<br />
<input type="text" class="img anisp" id="spimage" value="" />
<input type="button" class="select-imgsp" value="Select Image" />
</p>
<select id="eventNames" name='widget-dates_widget[__i__][eventNames][]' multiple hidden>
<option data-date='23/05/1992' value='[23/05/1992]jake' selected> jake</option>
<option data-date='15/08/1997' value='[15/08/1997]rebecca' selected> rebecca</option>
<option data-date='17/03/1995' value='[17/03/1995]clive' selected> clive</option>
</select>
<select id="eventText" name='widget-dates_widget[__i__][eventText][]' multiple hidden>
<option data-date='23/05/1992' value='[23/05/1992]yay me' selected> yay me</option>
<option data-date='15/08/1997' value='[15/08/1997]rebecca' selected> rebecca</option>
<option data-date='17/03/1995' value='[17/03/1995]clive' selected> clive</option>
</select>
<select id="eventImages" name='widget-dates_widget[__i__][eventImages][]' multiple hidden>
</select>
Jquery function
$(function() {
//onchange for the date select to populate the other boxes
$(document).on('change', 'select#spdates', function(evt) {
var date = $(this).find(":selected").attr("data-date");
if (date == "new") {
//new date selected, discard what's in the boxes and blank values
$(".namspani").val("");
} else {
//different date selected, discard what's in the boxes and blank values
alert($("#eventNames").find("[data-date='" + date + "']").text());
$("#spname").val($("#eventNames").find("[data-date='" + date + "']").text()); //grab from other lists
$("#sptext").val($("#eventText").find("[data-date='" + date + "']").text());
$("#spdate").val(date);
$("#spimage").val($("#eventImagess").find("[data-date='" + date + "']").text());
}
});
})
I've confirmed my code is being run as I've put an alert() containing one of the values I'm trying to set in the branch of the function i expect to run. In practice the alert files, with the right content, however the input fields don't fill with data.
This code works in jsfiddle https://jsfiddle.net/ForceGaia/j363mv3w/1/ but not natively in firefox or chrome.
What is going on? I'm fairly new to jquery, so I'm now wondering if I'm missing something basic.
EDIT:
The alert fires, so i know it's getting to the right chunk of code, thus some version of JQuery seems to be working. console.log($().jquery); puts 1.12.4 to the log.
I tried putting hardcoded strings into the .var() parameters, still nothing.
I moved the $("#spname") search into a variable to see if it was finding it.
var spnamedom = $("#spname");
After that chunk of code spnamedom was an array of elements (which, knowing jQuery, i expected) I tried accessing the 0th element and it was the correct element.
so i tried both of the following
var spnamedom = $("#spname");
spnamedom.val("a thing");
And
var spnamedom = $("#spname")[0];
spnamedom.val("a thing");
spnamedom is always what I'm expecting, but neither work. There is an element with the correct id in both cases, either as the 0th element, or straight in the variable.
he latter puts TypeError: spnamedom.val is not a function to the log. I assume that error is because I'm no longer in a JQuery object and am looking at a DOM object after i grabbed the 0th element. I could possibly edit this raw DOM element to get what I want, but the initial question remains, why does my code work in jsfiddle, but not a live browser; as from the reading I'm doing, this should work.
I have also found jQuery .val change doesn't change input value and using `.attr('value','text') doesn't work either.
EDIT 2
I realised that in my code i have something that does what i want already on different controls, and it works - which is even more bewildering. I had totally forgotten that the code was performing the same action when it came down to it.
Before i only supplied an exerpt of my JQuery script, here's the entire thing
var image_field;
jQuery(function($) {
$(document).on('click', 'input.select-img1', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
$(document).on('click', 'input.select-img2', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
$(document).on('click', 'input.select-img3', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
$(document).on('click', 'input.select-imgsp', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function (html) {
imgurl = $('img', html).attr('src');
image_field.val(imgurl);
tb_remove();
}
// onchange for the date select to populate the other boxes
$(document).on('change', 'select#spdates', function (evt) {
console.log($().jquery);
var date = $(this).find(":selected").attr("data-date");
if (date=="new") {
//new date selected, discard what's in the boxes and blank values
$(".namspani").val("");
}
else {
//different date selected, discard what's in the boxes and blank values
alert($("#eventNames").find("[data-date='"+date+"']").text());
var spnamedom = $("#spname");
spnamedom.attr('value', 'new value'); //grab from other lists
$("#sptext").val($("#eventText").find("[data-date='"+date+"']").text());
$("#spdate").val(date);
$("#spimage").val($("#eventImagess").find("[data-date='"+date+"']").text());
}
});
});
the code i didn't include is acts on bits of html that look like this
<p>
<label for="s3image">Image 3:</label><br />
<input type="text" class="img ani1" name="widget-namsoc_nextmeet_widget[__i__][s3image]" id="s3image" value="" />
<input type="button" class="select-img3" value="Select Image" />
</p>
What it does is open the Wordpress image uploader dialog when you click a button. When "insert into post" is pressed it sets the path value into the field.
This code works. So what is so different to the other code that makes it fail?

Use a variable created using javascript in HTML

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
);
});

jQuery merging select field and text input values in real time to another text field

I have a three field form. I'd like the third field (text box) to display a combination of the first two fields ... one being a select field and the other being a text field; these values separated with a space. I have tried the following with little success.
<form>
<select name="val1" id="val1">
<option value="">Select a value</option>
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input name="val2" id="val2" />
<input name="val3" id="val3" />
</form>
<script>
$('#val1, #val2').keyup(function(){ $('#val3').val($('#val1').val()+' '+$('#val2').val()); });
<script>
What I'm expecting is when a user selects an option from the select field, is value would appear in the third form field and when a user types something in the second field, its value would also appear in the third field separated with a space. This would all happen in real time. Oddly enough, the jQuery code does nothing in all browsers.
Maybe something to do with the keyup() function as a select field is using the mouse only. But even if I ignore the select field and type something in the second field, it should appear in the third field alone, but it doesn't.
Your #val1 is a select element, the keyup event can't be called with that.
Instead, you neeed to use change event.
$('#val1').change(function () {
changeThird();
});
$('#val2').keyup(function () {
changeThird();
});
function changeThird() {
$('#val3').val($('#val1').val() + ' ' + $('#val2').val());
}
JsFiddle: http://jsfiddle.net/ghorg12110/e7ru9jao/
For asp:TextBox, you need to use .attr() if you want to get the data generated:
$('#val1').change(function () {
changeThird();
});
$('#val2').keyup(function () {
changeThird();
});
function changeThird() {
$('#val3').attr("value", $('#val1').val() + ' ' + $('#val2').val());
}

Change select box value text

I got one text box and one select box.
<input type="text" />
<select>
<option value=1>Test1</option>
<option value=2>Test2</option>
</select>
Now i want when user type anything in text box, to change value=2 text.
I tried this, but looks like don't work.
$(document).ready(function () {
$("#textbox").keyup(function () {
$("select#sync[value='2']").text($(this).val());
});
});
Apart from the fact that you haven't given the elements IDs, the problem is that you need to access the <option> element (that one has a value of 2 - there is no <select value=2>). Also, IDs are unique, so using select#sync is (should be) the same as #sync:
$("#sync option[value='2']")
<input type="text" id="textbox" />
<select>
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>​
$(document).ready(function () {
$("#textbox").keyup(function() {
$("select option[value='2']").text($(this).val());
});​
});
http://jsfiddle.net/gxaWE/
you can try
$("#sync").val($(this).val());
provided that the user only types the value that is in range
DEMO
$("#text_box").keyup(function() {
$("#sync option[value='2']").text($(this).val());
});
​
​
Here is fiddle showing it working:
http://jsfiddle.net/bRw8Z/1/
It changes select option number 2 text. Is that what you wanted?
I see a few problems here:
It doesn't make sense to set the innerText of a <select> element; you want to set its value instead,
The #textbox selector wouldn't actually select anything.
If your input did not exactly match an <option>'s value attribute, the first <option> would be selected.
This snippet will select an <option> if its value attribute matches the value of the text input.
$(document).ready(function () {
$("input").keyup(function () {
var $select = $("select"),
value = $(this).val();
if($select.find('option[value="' + value + '"]').length){
$select.val(value);
}
});
});​
http://jsfiddle.net/2XxRQ/1/

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