Type to search from input box - javascript

I have a form where a user can choose their Occupation. The list of occupations are in a seperate .js file like so:
var occupationSelect = "<select id='occupationSelect' onchange='selectChange()' ><option value=''></option><option value='v10173' >AA Patrolman</option><option value='v10174' >Abattoir Inspector</option>
Now in my form I want the input box (as the occupation list is very long) , for the user to type A, B etc and then the relevant occupations come up. Something like the following jsfiddle
Similar JS Fiddle
This fiddle is fine if I put all the Occupations into an array.
However the options in my .js file have values attached for use later in the web application (eg. option value='v10173')
What is the best option to get the Occupation by typing but also to make sure the value is attached.

Edited the js fiddle:
<input name="car" list="anrede" />
<input name="car-val" hidden />
<ul id="anrede"></ul>
var mycars2 = [
['Herr', 'herr'],
['thomas', 'v2345'],
];
var list = $('#anrede');
listHtml = '';
mycars2.forEach(function(item){
var option = '<li data-val="' + item[1] + '">' + item[0] + '</li>';
listHtml += option;
});
list.html(listHtml);
$('#anrede li').on('click', function(){
$('input[name="car"]').val($(this).html());
$('input[name="car-val"]').val($(this).attr('data-val'));
});
This needs jquery, and the names/values are stored in pairs inside the list.
A hidden input is used for the value.

I would suggest using data-value attribute for the "value" of selected item and array of objects, like so:
var mycars = [
{
title: 'Herr',
value: 'Herr Value'
},
{
title: 'Frau',
value: 'Frau Value'
}
];
var list = document.getElementById('anrede');
var input = document.getElementById('carList');
mycars.forEach(function(item) {
var option = document.createElement('option');
option.value = item.title;
option.dataset.value = item.value;
list.appendChild(option);
});
input.onchange = function() {
alert(document.querySelector('option[value="' + this.value + '"]').dataset.value)
}
here is the jsfiddle - https://jsfiddle.net/0jvt05L0/302/

Related

Getting selected radio button in JavaScript

I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?
<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();
SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions
Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});

Dynamically Create/Alter Form Fields from URL Parameters (Not Prepopulate Existing Fields)

In a formstack form, I need to be able to pass a list to the form as a parameter and, from that list, create checkboxes or dropdown menus that the user can select and that are saved in formstack's database and sent to integrations like all other fields. Here's an example of what I'd like to send in:
http://theformurl?list=option1,option2,option3,option4
From this, I'm trying to use code insertion in either (or a mixture of) the head, footer, or a code embed to create a new field on load that looks and acts like all the other fields.
I've been tinkering with Jenna Molby's approach to dynamically modifying html with url parameters found here:
https://jennamolby.com/tutorial-examples/dynamic-content-based-on-a-url-parameter-example/
But no luck so far. At present, I've not succeeded in getting dynamic text to populate in the form, let alone a form field that then talks to formstack's back end.
Is this doable, and if so, can anyone recommend an approach or a thread to pull on to figure it out?
--update
Thanks to Eric's suggestion, I was able to get halfway there. This code in the footer can commandeer a checkbox that you've already inserted in the form by id. It will replace that checkbox with the values you send in the url. But the selections don't get caught by Formstack when you submit.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var url = new URL(window.location.href);
//Put field number in var fieldNumber
var fieldNumber = "12345678";
//Put the parameter you're searching for in var param
var param = "parameter name";
//if you want a prefix before your values in the checkbox, use prefix
var prefix = "Prefix ";
//Put the question you want to ask here.
var theQuestion = "Which of the values that came through the url will you select?";
//What should the single checkbox say if no parameters are passed?
var theDefaultBox = "No variables were contained in the parameter.";
var theField = "field" + fieldNumber;
var theFieldID = "fsCell"+fieldNumber;
var values = url.searchParams.get(param).split(",");
var theFieldHTMLfront = "";
if (values) {theFieldHTMLfront = "<fieldset id=\"label"+fieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>"+theQuestion+"</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+ prefix + values[0] + "\" class=\"fsField vertical\" />"+ prefix + values[0] + "</label>";} else {theFieldHTMLfront = "<fieldset id=\"label"+fieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>Which values may have observed or have knowledge about this event?</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+theDefaultBox+"\" class=\"fsField vertical\" />test</label>";}
var theFieldHTMLback = "</div></fieldset>";
for (var i = 1; i < values.length; i++) {
theFieldHTMLfront += "<label class=\"fsOptionLabel vertical\" for=\""+theField+(i+1)+"\"><input type=\"checkbox\" id=\""+theField+(i+1)+"\" name=\""+theField+"[]\" value=\""+prefix+values[i]+"\" class=\"fsField vertical\" />"+ prefix + values[i] + "</label>";
}
var theFieldHTML = theFieldHTMLfront + theFieldHTMLback;
document.getElementById(theFieldID).innerHTML = theFieldHTML;
});
</script>
Any thoughts on how to get it to talk to Formstack on submit?
Not familiar with formstack or what exactly you're getting from the URL and placing into forms or of what type, but I'll take a shot in the dark here.
Perhaps something like this:
var paramsToGet = ['param', 'param', 'param'];
document.addEventListener("DOMContentLoaded", function(event) {
let url = new URL(window.location.href);
paramsToGet.forEach((v)=>{
let thisParam = url.searchParams.get(param);
newFormElement(thisParam, x, x, "Default Value");
})
});
var newFormElement = (type, element_id, target_id, default_value) => {
default_value = default_value || null;
let el = document.createElement(type);
el.id = element_id;
if (default_value) {el.value = default_value;}
document.getElementById(target_id).appendChild(el);
}
So I've managed to find a solution that works for me. Thanks Eric for getting me started.
It requires adding two fields to the form you want to use this in: (1) a hidden text entry field where the selected values will be written, and (2) a placeholder checkbox field that this code will overwrite. You'll need to grab their id numbers, which I did by opening the live form and viewing source.
<script>
var selectedValues = [];
//This code goes in your Formstack theme footer. In the form that you want to add dynamic checkboxes to, create two fields using the WYSIWYG editor: a checkbox field and a text entry field. Make the text entry field hidden. You will need to know the id number of both the text entry and checkbox fields.
//Put the text entry field number in var textFieldNumber
var textFieldNumber = "field"+"12345678";
var index;
var checkboxFieldNumber = "12345679";
//Put the parameter you're searching for in var param
var param = "param";
//if you want a prefix before your values in the checkbox, use prefix
var prefix = "";
//Put the question you want to ask here.
var theQuestion = "Your question?";
//What should the single checkbox say if no parameters are passed?
var theDefaultBox = "Default message.";
document.addEventListener("DOMContentLoaded", function(event) {
var url = new URL(window.location.href);
//Put checkbox field number in var checkboxFieldNumber
//Build the replacement HTML for the placeholder checkbox field.
var theField = "field" + checkboxFieldNumber;
var theFieldID = "fsCell"+checkboxFieldNumber;
var values = url.searchParams.get(param).split(",") || null;
var theFieldHTMLfront = "";
if (values) {theFieldHTMLfront = "<fieldset id=\"label"+checkboxFieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>"+theQuestion+"</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+values[0]+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />"+ prefix + values[0] + "</label>";} else {theFieldHTMLfront = "<fieldset id=\"label"+checkboxFieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>Which values may have observed or have knowledge about this event?</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+theDefaultBox+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />test</label>";}
var theFieldHTMLback = "</div></fieldset>";
//iterate through the array found in the url parameters, adding a new checkbox option for each element in the array.
if (values) {for (var i = 1; i < values.length; i++) {
theFieldHTMLfront += "<label class=\"fsOptionLabel vertical\" for=\""+theField+(i+1)+"\"><input type=\"checkbox\" id=\""+theField+"_"+(i+1)+"\" name=\""+theField+"[]\" value=\""+values[i]+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />"+ prefix + values[i] + "</label>";
};}
//finalize replacement HTML
var theFieldHTML = theFieldHTMLfront + theFieldHTMLback;
//write new HTML to DOM
document.getElementById(theFieldID).innerHTML = theFieldHTML;
});
function checkBoxToggle(thisBox) {
if(thisBox.checked) {
//When a new checkbox is selected, add its value to array selectedValues, sort it, and write it to the text entry field.
selectedValues.push(thisBox.value);
selectedValues.sort();
document.getElementById(textFieldNumber).value = selectedValues;
} else {
//When a checkbox is deselected, splice its value out of array selectedValues and write the array to the text entry field's value
index = selectedValues.indexOf(thisBox.value);
if (index > -1) {
selectedValues.splice(index, 1);
document.getElementById(textFieldNumber).value = selectedValues;
}
}
}
</script>

How to create a enhanced HTML TransferBox with an attribute

I need to create an enhanced transferbox, using HTML, JavaScript and JQuery.
I have a set of options a user can select from and associate with an attribute. The selection and deselection must be accomplished with two SELECT HTML elements (i.e., a transferbox). For example, these options can be a list of skill names.
When the 'add' button is clicked, the option(s) selected in the first SELECT element, along with an attribute (e.g. number of years from a text box) must be transferred from the source SELECT element to selected/destination SELECT element. The attribute must be displayed along with the item text in this second SELECT element (for example, the item displays the skill and the number of years).
When the 'remove' button is clicked, the selected option(s) in the second SELECT element must be moved back to the first SELECT element (in the original format .. without the attribute).
JSON should be the data format for initial selection setup and saving latest selections.
I want an initial set of selections and attributes to be set via JSON in an a hidden input field. I want the final set of selections to be saved to JSON in the same hidden input field.
Example HTML:
<input type="hidden" id="SelectionsId" value='[{ "id": "2", "attribute":"15"},{ "id": "4", "attribute":"3" }]' />
<!--<input type="hidden" id="SelectionsId" value='[]' />-->
<div>
<select class="MultiSelect" multiple="multiple" id="SelectFromId">
<option value="1">.NET</option>
<option value="2">C#</option>
<option value="3">SQL Server</option>
<option value="4">jQuery</option>
<option value="5">Oracle</option>
<option value="6">WPF</option>
</select>
<div style="float:left; margin-top:3%; padding:8px;">
<div>
<span>Years:</span>
<input id="YearsId" type="number" value="1" style="width:36px;" />
<button title="Add selected" id="includeBtnId">⇾</button>
</div>
<div style="text-align:center;margin-top:16%;">
<button title="Remove selected" id="removeBtnId">⇽</button>
</div>
</div>
<select class="MultiSelect" multiple="multiple" id="SelectToId"></select>
</div>
<div style="clear:both;"></div>
<div style="margin-top:40px;margin-left:200px;">
<button onclick="SaveFinalSelections();">Save</button>
</div>
Example CSS:
<style>
.MultiSelect {
width: 200px;
height: 200px;
float: left;
}
</style>
Visual of requirement:
Here's a solution to the challenge. The variables being setup at the start make this solution easy to configure and maintain.
When the page gets displayed, the SetupInitialSelections method looks at the JSON data in the hidden input field and populates the selected items.
When the 'Save' button clicked, the current selections are converted to JSON and placed back in the hidden input field.
Invisible character \u200C is introduced to delimit the item text and the attribute during display. This comes in to use if the item has to be removed and the original item text has to be determined so it can be placed back in the source SELECT element.
The selectNewItem variable can be set to true if you would like the newly added item to be selected soon after adding it to the SELECT element via the 'add' or 'remove' operations.
This solution supports multiple item selections. So multiple items can be added at once ... and similarly multiple items can be removed at once.
<script src="jquery-1.12.4.js"></script>
<script>
var savedSelectionsId = 'SelectionsId';
var fromElementId = 'SelectFromId';
var toElementId = 'SelectToId';
var includeButtonId = 'includeBtnId';
var removeButtonId = 'removeBtnId';
var extraElementId = 'YearsId';
var extraPrefix = " (";
var extraSuffix = " years)";
var noItemsToIncludeMessage = 'Select item(s) to include.';
var noItemsToRemoveMessage = 'Select item(s) to remove.';
var selectNewItem = false;
var hiddenSeparator = '\u200C'; // invisible seperator character
$(document).ready(function () {
SetupInitialSelections();
//when button clicked, include selected item(s)
$("#" + includeButtonId).click(function (e) {
var selectedOpts = $('#' + fromElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToIncludeMessage);
e.preventDefault();
return;
}
var attribute = $("#" + extraElementId).val();
selectedOpts.each(function () {
var newItem = $('<option>', { value: $(this).val(), text: $(this).text() + hiddenSeparator + extraPrefix + attribute + extraSuffix });
$('#' + toElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
//when button clicked, remove selected item(s)
$("#" + removeButtonId).click(function (e) {
var selectedOpts = $('#' + toElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToRemoveMessage);
e.preventDefault();
return;
}
selectedOpts.each(function () {
var textComponents = $(this).text().split(hiddenSeparator);
var textOnly = textComponents[0];
var newItem = $('<option>', { value: $(this).val(), text: textOnly });
$('#' + fromElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
});
// Setup/load initial selections
function SetupInitialSelections() {
var data = jQuery.parseJSON($("#" + savedSelectionsId).val());
$.each(data, function (id, item) {
var sourceItem = $("#" + fromElementId + " option[value='" + item.id + "']");
var newText = sourceItem.text() + hiddenSeparator + extraPrefix + item.attribute + extraSuffix;
$("#" + toElementId).append($("<option>", { value: sourceItem.val(), text: newText }));
sourceItem.remove();
});
}
// Save final selections
function SaveFinalSelections() {
var selectedItems = $("#" + toElementId + " option");
var values = $.map(selectedItems, function (option) {
var textComponents = option.text.split(hiddenSeparator);
var attribute = textComponents[1].substring(extraPrefix.length);
var attribute = attribute.substring(0, attribute.length - extraSuffix.length);
return '{"id":"' + option.value + '","attribute":"' + attribute + '"}';
});
$("#" + savedSelectionsId).val("[" + values + "]");
}
</script>

jquery get first text element attribute from selected dropdown

both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.
$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname + ' ' + value.name +'</option>');
what i would achieve is:
var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
so, in other hand, i would like get only first element of text in selected dropbox.
I can help me to understand how to reach my goal?
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:
var testd = $("#dropDocente").val();
and that will return the selected option's value from the dropdown.
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well
$(document).ready(function() {
var values = [
{ surname: "Doe", name: "John", idDocente: "some value here" },
{ surname: "Shmo", name: "John", idDocente: "some value here2" },
{ surname: "Little", name: "John", idDocente: "some value here3" },
];
for (var i = 0; i < values.length; i++) {
var value = values[i];
$('#dropDocente').append('<option value="'+value.idDocente+
'" data-surname="'+ value.surname +'">' + value.surname + ' '
+ value.name +'</option>');
}
// default first
$('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());
// on change, get the surname
$('#dropDocente').on('change', function() {
$('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div>
You could just split full name on select change.
Something like this:
$('select').on('change', function(){
var id = $(this).val();
var fullName = $('select option:selected').text();
var surname = fullName.split(" ", 1);
});
Full example here: https://jsfiddle.net/1aj06Lw6/1/

dynamic text box dropdown clone

i am trying to create dynamic text boxes, but i'm having trouble basing them of a clone
essentially what i am trying to do is create a certain amount of text boxes based on the amount of options in a combo box. 5 values in a
var optionValues = [];
$('#fieldnameclone option').each(function() {
optionValues.push($(this).val());
});
optionValues.shift();
var optionspacing="";
jQuery.each(optionValues, function(i, val) {
optionspacing += val + ":<br />";
});
var insfldnms = $("<div id =insertfieldname></section>").html(optionspacing);
var n = $("#fieldname option").length;// get amount of options in dropdownt box
var $frm2 = $("<form id=insertform class=form2></form>");// creates a form
$frm2.append(tblNmClnSrch,fldnmCln,insfldnms);// adds the field and name clones to the form
for(var i = 0; i < n-1; i++)
{
$('<input /></br>', {id: "valueid" + i,name: "name" + i}).appendTo($frm2);
}
var btninsert = $("<input id=inserthbtn type=button value=Submit></input>");
$(btninsert).appendTo($frm2);
$( "#reports3" ).empty();
$("#reports3").append($frm2);
not sure where i am going wrong, any help would be awesome
html for fieldname
var txt3 = $("<section id =fieldname></section>").text("Text.");
fieldname combo box is generated using getjson, that part works fine, so there are elements in the dropdown box

Categories