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);
}
}
});
});
Related
Helo guys, I've been working for my project for several months.
Now I'm trying to fill my dropdown list named (drpIdCorsi), based on the selection of another dropdown list named (drpDocente).
This is how my JSON object is composed:
listaCorsi =
[
{nomeCorso: "some course name"},
{emailDocente: "some email"},
]
I've loaded with an AJAX request a JSON object (which is filled correctly).
Now I'm trying to navigate my JSON object and fill the dropdown list, but it doesn't work.
This is the first function:
var listaCorsi = selezionaCorsoDocenti();
var listaCorsiDDL = '';
$('#drpDocente').on('change',function()
{
docente = $('#drpDocente').val();
docente = docente.trim();
docente= docente.split("-")[0];//gets the email of the professor
console.log(listaCorsi);
console.log(docente);
console.log(listaCorsi);
if(!$.isArray(listaCorsi))
listaCorsi = [listaCorsi];
$.each(listaCorsi,function(key,value)
{
console.log(value);
if(docente == value.emailDocente)
listaCorsiDDL += '<option value="">' + value.nomeCorso + '</option>';
});
$('#drpIdCorsi').append(listaCorsiDDL);
}).change();
This is the function called above (It actually works, but I'm not able to fill the second dropdown list, cause it shows undefined as result or nothing in the second dropdown list)
function selezionaCorsoDocenti()
{
var listaCorsi = [{}];
$.get('selezionaCorsiPerDocente',function(responseJson)
{
if(responseJson != null)
{
var i = 0;
$.each(responseJson,function(key,value)
{
listaCorsi[i] = [{nomeCorso: value.NOME_CORSO}, {emailDocente: value.EMAIL}];
i = i + 1;
});
}
else
alert("AJAX FAILED");
});
return listaCorsi;
}
I'd like to fill the second dropdown list like this:
if(docente === value.EMAIL)
course += '<option value="">' + value.NOME_CORSO + '</option>
$('#drpIdCorsi').append(course);
The function selezionaCorsoDocenti() WORKS JUST FINE.
The problem is that the JSON object listaCorsi, when I iterative over that object with the $.each() prints undefined for a certain field of the object
Your main issue is in this line:
var listaCorsi = selezionaCorsoDocenti();
$.get('selezionaCorsiPerDocente',.... is an ajax call, so it's asynchronous. You need to wait in order to get the result.
Moreover, when a change happens you need to empty the dropdown. From:
$('#drpIdCorsi').append(listaCorsiDDL);
to:
$('#drpIdCorsi').empty().append(listaCorsiDDL);
function selezionaCorsoDocenti() {
var listaCorsi = [{}];
return $.get('https://gist.githubusercontent.com/gaetanoma/5f06d1dbd111ff6a7778cd6def6b1976/raw/037587e927ac297e1f4907364898ead22ed03a0d/selezionaCorsiPerDocente.json',function(responseJson) {
responseJson = JSON.parse(responseJson);
if(responseJson != null) {
var i = 0;
$.each(responseJson,function(key,value) {
listaCorsi[i] = [{nomeCorso: value.nomeCorso}, {emailDocente: value.EMAIL}];
i = i + 1;
});
}
});
}
selezionaCorsoDocenti().then(function(x) {
listaCorsi = JSON.parse(x);
$('#drpDocente').trigger('change');
});
$('#drpDocente').on('change',function(e) {
var listaCorsiDDL = '';
docente = $('#drpDocente').val();
docente = docente.trim();
docente= docente.split("-")[0];//gets the email of the professor
if(!$.isArray(listaCorsi))
listaCorsi = [listaCorsi];
$.each(listaCorsi,function(key,value) {
if(docente == value.emailDocente)
listaCorsiDDL += '<option value="">' + value.nomeCorso + '</option>';
});
$('#drpIdCorsi').empty().append(listaCorsiDDL);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="drpIdCorsi"></select>
<select id="drpDocente">
<option>docente1#mail.edu</option>
<option>docente2#mail.edu</option>
<option>docente3#mail.edu</option>
</select>
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);
});
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>
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
I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.