Creating dropdown <select><option> elements with javascript - javascript

I am new to jQuery and Javascript. I have to create select->option drop down control with client side jQuery/Javascripting. These drop downs are having their options from array and i have to create as many drop down as the array items. Please below two functions written, they are not drawing many drop downs but only one.
<script type="text/javascript">
// program inputs
var format1Fields = ",RepID,RetailOutlet,Address,Information,City,State,ZipCode, Demographic,Bullet,Date,Note1,Note2,Note3,Note4,Note5,AssignTask1,AssignTask2,AssignTask3,AssignTask4,LiquorPresence,PhotoLink1,Description1,PhotoLink2,Description2,PhotoLink3,Description3,PhotoLink4,Description4,PhotoLink5,Description5,PhotoLink6,Description6,PhotoLink7,Description7,PhotoLink8,Description8,PhotoLink9,Description9,PhotoLink10,Description10,PhotoLink11,Description11,PhotoLink12,Description12,Videolink1,Videodescription1,Videolink2,Videodescription2,Videolink3,Videodescription3,Videolink4,Videodescription4,POSInstalled1, POSQuantity1,POSInstalled2,POSQuantity2,POSInstalled3,POSQuantity3,POSInstalled4,POSQuantity4,POSInstalled5,POSQuantity5, POSInstalled6,POSQuantity6,POSInstalled7,POSQuantity7,POSInstalled8,POSQuantity8,POSInstalled9,POSQuantity9,POSInstalled10, POSQuantity10,POSInstalled11,POSQuantity11,POSInstalled12,POSQuantity12,Project,Visit,";
var outputFieldsString = "date visited,Mapping link,Date,RepID,Project,RetailOutLet,Address,City,State,Information,Demographic,Bullet,Note1,Note2,Note3,Note4,Note5,AssignTask1,AssignTask2,Assigntask3,AssignTask4,LiquorPresence,PhotoLink1,Picture01,Description1,PhotoLink2,Picture02,Description2,PhotoLink3,Picture03,Description3,PhotoLink4,Picture04,Description4,PhotoLink5,Picture05,Description5,PhotoLink6,Picture06,Description6,PhotoLink7,Picture07,Description7,PhotoLink8,Picture08,Description8,PosInstalled1,MC Cold Box Sticker,PosInstalled2,MC Poster 12 X 18,PosInstalled3,MC Poster 18 X 24,PosInstalled4,MC Poster 24 X 36,PosInstalled5,MC Case Cards,PosInstalled6,MC Standees,PosInstalled7,GM Poster 11 X 17,PosInstalled8,GM Poster 18 X 24,PosInstalled9,GM Recipe Table Tent,Photolink9,Description9,Photolink10,Description10,Photolink11,Description11,Photolink12,POSInstalled10,GM Shelf talker,POSInstalled11,GM Case Cards,POSInstalled12,GM Standees,Picture09,Picture10,Picture11,Picture12,Description12";
var outputDelimiter = ",";
var inputFieldList = new Array();
var outputFieldList = new Array();
$(document).ready(function(){
//$('#inputfields').val(trimOnSides(format1Fields.replace(' /g',''),","));
$('#inputfields').val(trimOnSides(format1Fields,","));
// start mapping click event
$('#start_mapping').click(function(){
var inputFieldString = $('#inputfields').val();
var inputDelimiter = $('#delimiter option:selected').val();
// input field validation
if(inputFieldString == ""){
alert("Please provide Input Fields header line having delimeter to identify the field names!");
$('#inputfields').focus();
return false;
}
// delimiter validation
if(inputDelimiter == "0"){
alert("Please select the correct delimiter that is matches with the seperating delimiter of the Input Fields!");
return false;
}
// Load input fields item array
inputFieldList = getFieldsList(inputFieldString,inputDelimiter);
if(inputFieldList.length==0){
alert("Problem transforming Input Field data into list of items for mapping");
return false;
}
// Load output fields item array
outputFieldList = getFieldsList(outputFieldsString,outputDelimiter);
if(outputFieldList.length==0){
alert("Problem transforming Output Field data into list of items for mapping");
return false;
}
// print field list item in HTML <ol>
getFormListItems(inputFieldList);
//getDropDownList('waqas','aiseha',inputFieldList);
});
});
// ###### HELPER FUNCTIONS #######
// helper to generate form of drop down
function getFormListItems(fieldListItems){
if((fieldListItems instanceof Array) && (fieldListItems.length>0)){
var list = $('#mappingitems').append('<ul></ul>').find('ul');
for(i=0; i<=fieldListItems.length-1; i++){
list.append('<li>');
list.append(getDropDownList(fieldListItems[i],fieldListItems[i],fieldListItems));
list.append('</li>');
//list.append('<li>'+fieldListItems[i]+'</li>');
//alert(i);
}
}
}
function getDropDownList(name, id, optionList) {
var combo = $("<select></select>").attr("name", name);
$.each(optionList, function (i, el) {
combo.append("<option>" + el + "</option>");
});
return combo;
// OR
//$("#SELECTOR").append(combo);
}
// helper split based string array generators
function getFieldsList(fieldsString, delimiter){
var returnList = new Array();
//alert(fieldsString);
// validating the arguments and their data type
if((fieldsString.length > 0) && (delimiter.length>0)){
returnList = fieldsString.split(delimiter);
return returnList;
}else{
alert('Problem in function arguments');
}
}
// helper string functions
function trimOnSides(str, chars) {
return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
</script>
this is the call to the function: getFormListItems(inputFieldList);
inputFieldList can contain Apple, Orange, Banana, Mango
Please help
thanks
Waqas

This will create the drop downs on the fly:
function getDropDownList(name, id, optionList) {
var combo = $("<select></select>").attr("id", id).attr("name", name);
$.each(optionList, function (i, el) {
combo.append("<option>" + el + "</option>");
});
return combo;
// OR
$("#SELECTOR").append(combo);
}

Related

Passing tab delimiter through via parameter not splitting string

My issue essentially is, I have a select box that has 2 options "Tab or CSV", those options meaning what to split a string on, my issue is when every I pass through "\t" as a parameter, it doesn't split on tabs. if I explictly type "\t" it splits the string but not if its being passed via a parameter.
I am trying to create a sql results to jira table chrome extention
The issues reside in the GetDelimiterType function and GenerateLine< first line.
I have no idea what is going on, if i check the value of delimerType it reads "\t" but doesn't split
$("#btn").click(function(){
var textToChange = $("#input").val().split("\n");
var topLineRow = $("#topRow").prop("checked");
var delimiterType = $("#delimiterSelect option:selected").val();
var jiraTable = "";
debugger;
if(topLineRow){
jiraTable += GenerateLine("||", textToChange[0], GetDelimiterType(delimiterType))
}
topLineRow = false;
var generatedString = "";
$.each(textToChange, function(index, value){
if(!topLineRow){
jiraTable += GenerateLine("|", textToChange[index],GetDelimiterType(delimiterType));
}
})
alert(jiraTable);
})
function GetDelimiterType(delimiterType){
debugger;
if(delimiterType == 0){
return ",";
}else if(delimiterType == 1){
return "\\t";
}
}
function GenerateLine(seperator, row, delimiter){
var rowArray = row.split(delimiter);
var rowText = "";
$.each(rowArray, function(index, value){
var isLastElement = index == rowArray.length -1;
value = value.replace(/\s/g,'');
if(index == 0){
rowText += seperator;
}
if(isLastElement){
rowText += value + seperator + "\n";
}else{
rowText += value + seperator;
}
});
return rowText;
}
.split(/.../)
.split() method can pass a regex literal as a delimiter.
/\b[^\S]+?\b|,\s/
\boundary meta-sequence denotes a non-spaced character next to a word character
[^\S]+? class ignores one or more non-whitespace characters
\b as above
|,\s OR a literal comma followed by a space
Demo
var row = `Mike, Alpha, Tango, Tango Zulu Echo Romeo 0 0 November Echo`;
var rowArray = row.split(/\b[^\S]+?\b|,\s/);
console.log(JSON.stringify(rowArray));

Grab cell values from a table using Jquery?

I'm trying to grab the cell values from an HTML table generated from another PHP code. That I can use the result to send a rendezvous at final user.
My current JSFiddle can grab some values but not like I want. I need to retrieve the attrib title & value from the button in the TD, my problem is currently the code return data from morning day and jump to the next morning day.
How I can return entire day value & title data's for each available days in the table ?
Code :
$(document).ready(function(){
eachCell();
function eachCell(){
var cellInnerText = [];
var cellValue = [];
var out = document.getElementById("out");
var out2 = document.getElementById("out2");
$('#ft_agenda tbody tr').each(function(index) {
// console.log("index ", index, " this: " , this, "this.attr(rel)", $(this).attr('rel'), "$(this).text()", $(this).text());
console.log($(":first-child", $(this))[0]);
cellInnerText.push($("td button", $(this)).attr('value'));
cellValue.push($("td button", $(this)).attr('title'));
});
out.innerHTML = cellInnerText.join(" | ");
out2.innerHTML = cellValue.join(" | ");
}
});
// Try this code on your jsfiddle
// https://jsfiddle.net/g60ogt8c/1/
$(function() {
function findColumnByDate(date) {
var col;
$('#ft_agenda thead th').each(function(idx) {
if ($(this).text().trim() == date.trim()) col = idx;
});
return col;
}
function showAvailableTimes(date) {
var times = [],
column = findColumnByDate(date);
if (column) {
var $rows = $('#ft_agenda tbody td:nth-of-type('+column+')');
if ($rows.length) {
times[0] = '';
$rows.find('button').each(function() {
times[times.length] = $(this).attr('value')+' - '+$(this).attr('title');
});
times[0] = 'For date '+date+' found '+(times.length-1)+' free terms';
} else {
times[0] = ['No free terms for date: '+date];
}
} else {
times[0] = ['Invalid date '+date+' or date not found'];
}
return times;
}
// Function showAvailableTimes() now returns array.
// In index 0 is status message and if available times found,
// these lies on indexes 1 and more.
// Use it this way:
$('#out').html('');
showAvailableTimes('15-09-2016').forEach(function(item) {
$('#out').append(item + '<br>');
});
// Or this way:
// Jsonify returned array and send it toSome.php.
var json = JSON.stringify(showAvailableTimes('09-09-2016'));
$.post('toSome.php', {times: json});
// Or if there are free terms, filter status message
// and send just free terms - without status message.
var times = showAvailableTimes('09-09-2016');
if (times.length > 1) {
var json = JSON.stringify(times.filter(function(itm,idx){return idx>0}));
$.post('toSome.php', {times: json});
// Here you can see that status message was skipped
$('#out2').text(json);
}
});

Jquery excel type dynamic formulas calculation

I am generating FINANCIAL ANALYSIS and i generate dynamic formula for chart of accounts.
Example
Cash -- Input able Field
Short Term Investments -- Input able Field
Liquid Assets -- Formula Field and i generate formula for this #1~Cº + #2~Cº
Notes Receivable -- Input able Field
Accounts Receivable -- Input able Field
Provision for Debts -- Input able Field
Net Accounts Receivable -- Formula Field and i generate formula for this #4~Cº + #5~Cº+#6~Cº
and so on...
i am calculating on text box focusout calculate_year.
function calculate_year(ThisObj) {
var obj;
//intiate vaiables
var year_formulaTxt = "",resultExp ="",lastPos ="",sequenceTypePosC="",sequenceTypePosP="",sequenceTypePosF="",COACode="",COAValue="",ratio_formulaTxt = "";
var ratio_formulaTxt = "",COACode_P="",COAValue_Pyear_formula = "",ratio_formula = "",year_formulaObj = "",ratio_formulaObj = "",year_formulaArr = "",ratio_formulaArr = "",FormulaResult="";
//match paterm for
var matchPattern = /[^\s()*/%+-/]+/g;
var tableId = $(ThisObj).closest('table').attr('id');
var CuurentDiv = $(ThisObj).closest('.program-column').index();
if (CuurentDiv < 2){ // to check if previous month added
CuurentDiv = CuurentDiv + 1 ;
}
var tableIdNext = $('.mCSB_container .program-column:eq('+CuurentDiv+') table').attr('id');
//get all textbox inside div
$('#'+tableId+' .financial_txt').each(function () {
//º
obj = $(this);
year_formulaObj = obj.find('input[type=text]');
ratio_formulaObj= obj.find('input[type=text]:eq(1)');
//calcualtion for only formula fields
if ($(year_formulaObj).attr('data-fieldtype') == "F") {
//get formula from custom field
year_formula = $(year_formulaObj).attr('year_formula');
if($.trim(year_formula) !=""){
//match formula with math's operator(Binary operator)
year_formulaArr = year_formula.match(matchPattern);
//break string # º : working for single experssion using loop
// ----------------------For Year ---------------------------
for( var i=0; i< year_formulaArr.length; i++ ){
//sub string from '#' to 'º'
lastPos = year_formulaArr[i].substring(1, year_formulaArr[i].length - 1);
//all sequence type
sequenceTypePosC = lastPos.indexOf("C");
sequenceTypePosP = lastPos.indexOf("P");
sequenceTypePosF = lastPos.indexOf("F");//
if(sequenceTypePosC >= 0){
//console.log(lastPos);
//getting value of COACode From Formula
COACode = lastPos.substring(0, sequenceTypePosC - 1);
//getting value of COACode From Text box id
COAValue = $.trim($('#'+tableId+' #txt_year_formula'+COACode).val()) == "" ? 0 : $.trim($('#'+tableId+' #txt_year_formula'+COACode).val());
$('#'+tableId+' #txt_year_formula'+COACode).val(COAValue);
//work for field value
var tempRes = year_formula.substring(year_formula.indexOf("#"), year_formula.indexOf("º")+1);
year_formula = year_formula.replace(tempRes,COAValue);
tempRes = year_formula;
//replace rest of # ,º with 0
tempRes = tempRes.replace(/\s*#[^º]+º\s*/g,parseFloat(0));
var result = parseFloat(mathEval(tempRes)).toFixed(3)|| 0;
$('#'+tableId+' #txt_year_formula'+$(this).attr('id')).val(mathEval(result) == "NaN" ?"0":mathEval(result));
}
}
}
}
});
}
function mathEval (exp) {
var reg = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]"'!&<>^\\?:])/ig,
valid = true;
// Detect valid JS identifier names and replace them
exp = exp.replace(reg, function ($0) {
// If the name is a direct member of Math, allow
if (Math.hasOwnProperty($0))
return "Math."+$0;
// Otherwise the expression is invalid
else
valid = false;
});
// Don't eval if our replace function flagged as invalid
if (!valid){
//console.log("Invalid arithmetic expression");
}
else{
try { return (eval(exp) == "Infinity" ? "0":eval(exp)); } catch (e) { };
}
}
The String break and then generate calculation is best way on function calculate_year ?
As you seen i am calculating amount from dynamic formulas,the problem is that there is some formulas return me Infinity because of tempRes.replace(/\s*#[^º]+º\s*/g,parseFloat(0));
#8~Cº / #27~Cº
how i can handle this ?Sorry for English
Working link
if you inspect you will see formula.

How can I show only the row of a table that has the same value that was entered in a textbox with jquery

I have a table of rank where I type the ID of the rank and it shows me only the column line that has this line as my code:
$('button').click(function () {
var data = $("textarea").val();
var rank = $("#rank").val();
if(rank == ""){
alert("digit rank number");
}
else{
data = data.replace(/\s/, " #");
data = data.replace(/([0-9]\s)/g, "$1#");
var lines = data.split("#"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>" + lines[i].slice(0,-1).split(",").join("</td><td>") + "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
}
});
I'm doing this filter in that part of the code
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
DEMO CODE
(Forgive me if you did not understand something, my english sucks. I hope it is clear what I need.)
You need to change this -
return $(this).children('td').eq(1).text() == rank;
to this -
return $(this).children('td').eq(0).text() == rank;
.eq() is a zero-based array method.
http://jsfiddle.net/jayblanchard/qM6Fj/19/
http://api.jquery.com/eq/
You need to have a search feature for the contents you have displayed in the table is what i got.....
You can use jQuery DataTable for this purpose which does this job link .. scroll down to see the table show with sort, search etc features

How to prevent Javascript updating entire control, and refreshing content?

I have this code:
function addFormControls() {
var e = document.getElementById("ProductsList");
var prodid = e.options[e.selectedIndex].value;
var prodvalue = e.options[e.selectedIndex].text;
if (num == 0) {
document.getElementById("ProductsPanel").innerHTML = '<h3>Products added to Variant</h3>';
}
if (num < 10) {
var boolCheck = checkArrayData(prodid);
if (boolCheck == false) {
document.getElementById("ProductsPanel").innerHTML = document.getElementById("ProductsPanel").innerHTML + prodvalue + '<input type="text" id="' + prodid + 'product" value="0" width="50px" maxlenght="2" /><input type="button" onclick="updateArrayData(\'' + prodid + '\', document.getElementById(\'' + prodid + 'product\').value);" value="Update Number" /><br />';
num++;
prodIdArray.push({
'key': prodid,
'value': prodvalue,
'num': 0
});
document.getElementById("productsArray").value = prodIdArray;
} else {
alert("Sorry product has already been added!");
}
}
}
which happily updates a div tag with new info, however if you look at the section where it prints a text box to the screen, line 13, these textbox's will be updated by the user.
So in short, textboxs are added, and value update.
however if there is a textbox with value 5, then this function called again to add another textbox, the previous textbox' values will be wiped clean!
So, how do i prevent this, will i have to do some, for loop over div controls taking the values, then put them back after this function is called?!?
I create some javascript to save all the values in a particular input's value field before adding the control, then return all the saved values back to their respected inputs.
function saveValuesOfProducts()
{
// initialise the array
numOfProds = new Array();
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of inputs left saving their value
for (i=0; i<x.length; i++)
{
numOfProds.push(x[i].value);
}
}
function returnValuesOfProducts()
{
// get all the elements which are inputs
var x=document.getElementsByTagName("input");
// remove all un necessary inputs
x = leaveTextInputs(x);
// loop through the entire list of saved values and return them to the input
for (i=0; i<numOfProds.length; i++)
{
x[i].value = numOfProds[i];
}
}
function leaveTextInputs(value)
{
// create a new blank array
var newArr = new Array();
// loop through all the elements in passed array
for (i=0; i<value.length; i++)
{
// cache the element
var thevalue = value[i];
// check if the element is a text input
if (thevalue.type == "text")
{
// check the id consists of product in it!
var regexteststring = thevalue.id;
// create the pattern to match
var patt1 = /product/i;
if (regexteststring.match(patt1) == "product")
{
// as additional check, if it has a size quantity of 2 then its defo out stuff
if (thevalue.size == 2)
{
newArr.push(thevalue);
}
}
}
}
// now return the new array
return newArr;
}

Categories

Resources