dynamic text box dropdown clone - javascript

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

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

Type to search from input box

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/

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>

Js on change dropdown

I have a form that has a hidden text input that gets the user id called user_number_id and depending on the value the dropdown called departamento_drop gets an options filtered to retorno1. The problem is that when I open this form to edit something inside it, the selected option of this dropdown changes automatically and changes the real selected value. How can I keep the selected value selected and make sure the filter can understand that and have to respect it?
$("#user_number_id").val(function(){
var selecionado = $(this).val();
jQuery.get("<?php echo base_url().'departamentos/filter_departamento/'; ?>"+selecionado,
function(retorno1){
var ret1 = '<option value="0">------ N/A ------</option>' + retorno1;
var ret2 = retorno1 + '<option value="0">------ N/A ------</option>';
if($("#departamento_drop option:selected").val() > '0'){
jQuery("#departamento_drop").html(ret2);
}else{
jQuery("#departamento_drop").html(ret1);
}
});
});
after 9 hours of work on it, I done this solution but still I need to find how to remove the selected option from retorno1 to not be duplicated, and for sure if there is any other idea better please share. thank you
$("#user_number_id").val(function(){
var selecionado = $(this).val();
jQuery.get("<?php echo base_url().'departamentos/filter_departamento/'; ?>"+selecionado,
function(retorno1){
var i = 0;
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(retorno1)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
for(i=0; i < count; i++){
var val_drop = $($.parseHTML(retorno1)).filter("option[value*='" + i + "']").val();
var text_drop = $($.parseHTML(retorno1)).filter("option[value*='" + i + "']").text();
if (val_drop == dep_dr){
jQuery("#departamento_drop").html("<option value ='"+val_drop+"' selected='selected'>"+text_drop+"</option>"+pre);
}else if(dep_dr == '0'){
jQuery("#departamento_drop").html("<option value ='"+dep_dr+"' selected='selected'>------ N/A ------</option>"+pre);
}
}
});
});

create html field based on js variable value

I have a property called results.row in JS. Using the value of that, I have to create textboxes in html. Suppose the value of results.row is 5,then I want to create 5 textboxes in html.
Also, the data to be shown on the textboxes is inside results.rows.item(i) . Is it possible to display?
HTML
<textbox name="Medicine Name" id="medicine"/>
JS
var rows = 5;
for (var i = 0; i < rows; i++)
{
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.value = 'value here ' + i;
document.getElementsByName('medicine')[0].appendChild(textbox);
}

Categories