How can i use dynamic variables names in my jquery function - javascript

I am just learning jquery and javascript and i have a function that unwraps [select] elements on my page and displays them as buttons. There could be multiple select boxes on my page so I need to dynanically name the following variables based on the elementname that is passed in, so that when the buttons are clicked it passed the correct values:
selector1
currentvalue1
hidden1
svalue1
This is the function:
function doUnwrap(elementname) {
var selector1 = document.getElementById('' + elementname + '');
var currentvalue1 = selector1[selector1.selectedIndex].text;
var hidden1 = $('<input type="hidden" name="' + elementname + '">');
hidden1.val($('[name=' + elementname + ']').val());
hidden1.insertAfter($('[name=' + elementname + ']'));
$("[name=" + elementname + "] option").unwrap().each(function () {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '">' + $(this).text() + '</div>');
if ($(this).text() == currentvalue[i]) {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
if ($(this).is(':checked')) btn.addClass('on');
$(this).replaceWith(btn);
} else {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
$(this).replaceWith(btn);
};
});
$(document).on('click', '.btn', function () {
$('.btn').removeClass('on');
$(this).addClass('on');
$('input[name=' + elementname + ']').val($(this).text());
var sValue1 = "&value=" + elementname + "|" + $(this).attr('id') + "";
executeAjaxEvent(sValue1, null, "ComboBoxAjaxHandler", false, null, true);
});
}

Related

jQuery When After Each Loop

I have six static html questions and then 3-4 questions being generated by JSON dynamically based upon a form choice made on a page before. What I'm trying to do is generate the questions, then create a progress bar based on the final number of questions created. Where I'm having trouble is using the jQuery when done method after my each loop. It is firing after the first iteration instead of the last. I have tried populating an array "Qs" and passing the array, after reading some other posts, but what I have hasn't worked. I would really like to segment my code and clean it up as much as possible, so I'm trying to stay away from nesting it.
var Qs = [];
var generateQs = function (){
var $dept = sessionStorage.getItem("sFGeneralDepartment1");
var $qWrapper = $("#assessmentTool");
$.getJSON("js/dept-questions.json", function(data) {
var key = $dept;
var vals = [];
switch(key) {
case 'Information technology':
vals = data.IT;
break;
case 'Finance':
vals = data.FIN;
break;
case 'Human resources':
vals = data.HR;
break;
case 'Marketing':
vals = data.MKT;
break;
default:
vals = data.OT;
break;
}
$.each(vals, function(index, value) {
var $cleanID = (value.qID).replace(/q/g, '');
$qWrapper.append('<div class="question-container rangeIcon disabled" id="' + value.qID + '"><p>Question ' + $cleanID +'</p> <h4>' + value.questionText + '</h4><ul class="answer-container"></ul></div>');
$.each(value.answers, function(i, answer) {
var $aID = answer.aID;
var $radioBtn = '<div class="radioBtn"><span class="radioBtnInner"></span></div>';
$('.question-container#' + value.qID + ' .answer-container').append('<li class="survey-item"><div class="icon-holder" id="' + $aID + '"><img src="img/' + answer.iconFileName + '" width="' + answer.iconWidth +'" height="'+ answer.iconHeight + '"/></div><input type="radio" id="'+ $aID + '" value="' + answer.pointValue + '"><label for="' + $aID + '" class="radio" data-popover="'+ answer.popoverText + '">' + $radioBtn + '<span class="labelTopText">' + answer.labelTopText + '<span class="divider">/</span></span><span class="labelBottomText">' + answer.labelBottomText + '</span></label></li>');
});
Qs.push($cleanID);
});
console.log('done');
console.log(Qs);
});
};
$.when(generateQs($,Qs)).done(function() {
//create progress bar
console.log('starting');
var qCount = ($('.question-container').length + 1);
var qList = $('#progressBar');
for (var i = 0; i < qCount; i++){
qList.append('<li class="progress-bar-steps" data-item="q' + (i+1) + '">' + '<span class="step-text">' + (i+1) + '</span>' + '</li>');
$('.question-container').each(function (i, value){
var qId = $(this).attr('id');
if ($(this).hasClass("active")) {
$(this).css('opacity','1.0');
$('#progressBar').find("[data-item='" + qId + "']").addClass('active').html('<span class="step-text">' + (i+1) + '</span>');
$('.progress-bar-steps.active').next('.progress-bar-steps').addClass('next disabled-next').html('<span class="step-text">' + (i+2) + '</span>');
} else {
$(this).addClass('disabled');
}
});
}
});

checkbox Click event is not working from second page in datatable?

I have a datatable and populating with Ajax response. I have a submit button at top and i want to handle click event for submit,
I have input text boxes in each row and The below code is working only for first 10 rows, if is click next button in data table the submit ($('#createOrderId').click) event is not working. I tried creating on change event in fndrawcallback, but that is also not working.
Can anyone help me on this.
function showCheckoutResults(obj) {
oTable = $('#checkoutTable').DataTable({
bDestroy : true,
"autoWidth": false,
columnDefs : [ {
width: "2%",
targets : 0,
className : 'dt-body-center select-checkbox',
'checkboxes': {
//'selectRow': true
}
},
{
"targets": [ 10 ],
"visible": false
}
],
select : {
style : 'multi',
selector: 'td:first-child'
},
order : [ [ 1, 'asc' ] ],
"fnDrawCallback": function() {
loadDatePicker();
$('.commonOrderQty').on('change', function () {
var dataArr = [];
var rows_selected = oTable.column(0).checkboxes.selected();
if (typeof rows_selected != 'undefined') {
$.each(rows_selected, function(index, rowId){
dataArr.push(rowId);
});
}
for(var i=0;i<dataArr.length;i++) {
$( "#ordQty" + dataArr[i] ).change(function() {
alert($("#ordQty" + dataArr[i]).val);
validateOrderQty( dataArr[i]);
});
}
});
}
});
oTable.rows().remove().draw();
$.each(obj, function(index, key) {
var ordrSrchResultData = [];
var finalLeadTime = calculateLeadTime(key.fopLeadTime);
var unitPrice = key.quote;
if(key.um == 'CPC') {
unitPrice = key.quote/100;
}
ordrSrchResultData.push(index);
ordrSrchResultData.push('<input id="po' + index
+ '" type="text" maxlength="12" class="checkoutText" value="' + key.poNo + '"/>');
ordrSrchResultData.push('<input id="ordQty' + index
+ '" type="text" class="checkoutText commonOrderQty" value="' + key.orderQty + '"/>');
ordrSrchResultData.push('<input id="boxQty' + index
+ '" type="text" class="checkoutText" value="' + key.boxQty + '"disabled/>');
ordrSrchResultData.push('<input type="text" class="checkoutText" id="datePicker' + index
+ '" value="' + key.dueDate + '" readonly="readonly"/>');
ordrSrchResultData.push('<input type="text" class="checkoutText" id="datePicker' + index
+ '" value="' + finalLeadTime + '" readonly="readonly"/>');
ordrSrchResultData.push('<input id="partNo' + index
+ '" type="text" class="checkoutText" value="' + key.partNo + '"disabled/>');
ordrSrchResultData.push('<input type="text" class="checkoutText" id="suppPartNo' + index
+ '" value="' + key.suppPartNo + '" readonly="readonly"/>');
ordrSrchResultData.push('<input type="text" class="checkoutText" id="extPrice' + index
+ '" value="' + key.extPrice + '" readonly="readonly"/>');
ordrSrchResultData.push('<input type="text" class="checkoutText" id="customerCd' + index
+ '" value="' + key.customerCd + '" readonly="readonly"/>');
ordrSrchResultData.push('<input type="text" class="checkoutText" id="quote' + index
+ '" value="' + unitPrice + '" readonly="readonly"/>');
ordrSrchResultData.push('<input type="hidden" value="'+key.dueDate+'" id="existDatePicker'+index+'"');
oTable.columns.adjust().draw();
oTable.row.add(ordrSrchResultData).draw();
localStorage.setItem('_selectedStartDate', finalLeadTime);
updateDatepicker(index, finalLeadTime);
$('#checkoutTable tr:last').attr('id', 't' + index);
$("#" + 't' + index).removeClass('selected');
$( "#ordQty" + index ).change(function() {
validateOrderQty(index);
});
});}
$('#createOrderId').click(function (){
var dataArr = [];
var rows_selected = oTable.column(0).checkboxes.selected();
$.each(rows_selected, function(index, rowId){
dataArr.push(rowId);
});
var rowsCount = dataArr.length;
var errMsg = $("#noSelectedDataErrMsg").val();
if(rowsCount == 0) {
jQuery("label[for='ordlabelvalue']").html(errMsg);
$('#orderErrorModal').modal('show');
return;
}
createOrder(dataArr);
});
Instead of:
$('#createOrderId').click(function (){
Use this:
$(document).on('click','#createOrderId',function (){

in directive, ng-click fires multiple times angularjs

I am creating a directive, which is used to add and remove elements dynamically. But my ng-click fires multiple times while adding and removing elements. Please give suggestions.
Here enable values means to select when 1=>textbox; 2=>selectbutton;3=>Radio button; 4=>CheckBox;5=>+/-
HTML:
<body ng-app = "mainApp" ng-controller = "loginController">
<div id="sampleeid">
<incrementrowsdirective idvalue="sto"
arrayvalues='[]'
labelvalues='["Concepto","Monto","Add/Remove"]'
enablevalues='[2,1,5]'></incrementrowsdirective>
<button ng-click="SampleButton()">Sample
Button</button>
</div>
CODE:
gasapp.directive("incrementrowsdirective", function ($compile) {
var trheaderelements;
var tablenm;
var tablenm1;
var trelements;
var trfirstelement;
var firstelement;
return {
restrict: 'AE',
scope: {
idvalue: '#'
},
template: function (elem, attr) {
return '<div class="col-md-8 col-sm-11 col-xs-11"><table id="tableheaderid"></table> <table id="tableid' + attr.idvalue + '" class="table table-condensed table-striped table-bordered table-hover no-margin">' +
'</table></div>'
},
link: function (scope, iElement, iAttrs) {
scope.labelval = JSON.parse(iAttrs.labelvalues);
scope.enableval = JSON.parse(iAttrs.enablevalues);
scope.arrt = JSON.parse(iAttrs.arrayvalues);
scope.c = 0;
scope.count = 1;
trheaderelements = '<thead><tr id="mytrheader' + scope.idvalue + '" >';
angular.forEach(scope.labelval, function (value, key) {
trheaderelements = trheaderelements + '<th style="width: 20%;"> ' + value + ' </th>';
});
trheaderelements = trheaderelements + "</tr></thead>";
tablenm = angular.element(document.getElementById('tableid' + scope.idvalue)).append(trheaderelements);
$compile(tablenm)(scope);
trfirstelement = "<tr id='mytrfirstelement'>";
angular.forEach(scope.enableval, function (value, key) {
if (value == 1) {
trfirstelement = trfirstelement + '<td><input type="text" name="text1name' + scope.idvalue + value + key + '" ng-model="text1value' + scope.idvalue + value + key + '" id="text1valueeid' + scope.idvalue + value + key + '" > </td>';
}
if (value == 2) {
trfirstelement = trfirstelement + '<td><select id="selectid1value' + scope.idvalue + value + key + '" name="selectname1val' + scope.idvalue + value + key + '" ng-model="selectmodel1val' + scope.idvalue + value + key + '" style="width:185px;"><option>..select..</option><option>Brother</option><option>Sister</option><option>Wife/Husband</option></select></td>';
}
if (value == 3) {
trfirstelement = trfirstelement + '<td><input type="radio" id="radio1idvalue' + scope.idvalue + value + key + '" name="radio1nameval' + scope.idvalue + value + key + '" ng-model="radio1modelval' + scope.idvalue + value + key + '" > </td>';
}
if (value == 4) {
trfirstelement = trfirstelement + '<td><input type="checkbox" id="checkbox1idval' + scope.idvalue + value + key + '" name="checkbox1nameval' + scope.idvalue + value + key + '" ng-model="checkbox1modelval' + scope.idvalue + value + key + '"> </td>';
}
if (value == 5) {
trfirstelement = trfirstelement + '<td> <input type="button" value="+" id="addbtn' + scope.idvalue + value + key + '" ng-click="addRow1(' + scope.c + ')">' +
' </td>';
}
});
trfirstelement = trfirstelement + "</tr>";
firstelement = angular.element(document.getElementById('tableid' + scope.idvalue)).append(trfirstelement);
$compile(firstelement)(scope);
trfirstelement = '';
scope.addRow1 = function (a) {
scope.c++;
scope.count++;
trelements = '<tr id=mytr' + scope.idvalue + scope.c + '>';
angular.forEach(scope.enableval, function (value, key) {
scope.keyvalue = key;
if (value == 1) {
trelements = trelements + '<td><input type="text" name="text1name' + scope.idvalue + scope.c + value + key + '" ng-model="text1value' + scope.idvalue + scope.c + value + key + '" id="text1valueeid' + scope.idvalue + scope.c + value + key + '" > </td>';
}
if (value == 2) {
trelements = trelements + '<td><select id="selectid' + scope.idvalue + scope.c + value + key + '" name="selectname' + scope.idvalue + scope.c + value + key + '" ng-model="selectmodel' + scope.idvalue + scope.c + value + key + '" style="width:100%;"><option>..select..</option><option>Brother</option><option>Sister</option><option>Wife/Husband</option></select></td>';
}
if (value == 3) {
trelements = trelements + '<td><input type="radio" id="radioid' + scope.idvalue + scope.c + value + key + '" ></input> </td>';
}
if (value == 4) {
trelements = trelements + '<td><input type="checkbox" id="checkboxid' + scope.idvalue + scope.c + value + key + '" name="aaa" ></input> </td>';
}
if (value == 5) {
trelements = trelements + '<td> <input type="button" value="+" id="addbtn' + scope.idvalue + scope.c + value + key + '" ng-click="addRow1(' + scope.c + ')">' + ' <input type="button" value="-" ng-click="removerowbutton1(' + scope.c + ')" > </td>';
}
});
trelements = trelements + "</tr>";
tablenm1 = angular.element(document.getElementById('tableid' + scope.idvalue)).append(trelements);
$compile(tablenm1)(scope);
trelements = '';
}
scope.removerowbutton1 = function (index) {
//scope.c--;
alert("Removed")
var myEl = angular.element(document.querySelector('#mytr' + scope.idvalue + index));
myEl.remove();
}
}
};
});
Need to remove the lines,
$compile( firstelement )( scope );
$compile( tablenm1 )( scope );
and replace the line with
firstelement = angular.element(document.getElementById('tableid'+scope.idvalue)).append($compile(trfirstelement)(scope));

Updating two dynamic text fields simultaneously

See below code. I am creating 2 text fields at a time. Now how could I type on one text field and make the other twin text field have the same values simultaneously?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
<script>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..."/>' + '<br>' + '</div>' + '</div>');
$(OuterWrapper).append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '">' + '</div>');
x++;
return false;
});
});
</script>
I created a fiddle that I think does what you want: http://jsfiddle.net/3h1h5j7y/
Here is the code.
HTML
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
JavaScript
I added a data- attribute to the inputs with the tfCont id so that they can operate in pairs as they are added.
Also, I am using the on() method so that objects can be added dynamically. It is filtering on the fTypex class.
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});
I had to change $(OuterWrapper) from your example to $("#OuterWrapper") because there was not a variable.
Try something like this :
use onkeyup to call a function which binds the values
HTML
<body>
<input id='ip1' onkeyup='updateOther(this);' type='text'>
<input id='ip2' type='text'>
<script src="script.js"></script>
</body>
JS:
function updateOther(obj){
$('#ip2').val($(obj).val()) ;
}
http://plnkr.co/edit/dpwav5fGcisZcjBIzYyz?p=preview

change text to input and back to text

I have a product list, price is normal text. When I click in with price, I want to replace text by input and when I call the blur event, it update DB data and replace input by text.
I have this code:
<td>
<span onclick="make_field(this, 'text', '11', '12,350.00')">12,350.00</span> €
</td>
<script>
function make_field(el, type, id, val) {
var el = $(el);
el.html('<input onblur="update_db_row(params); make_el(this, \'span\', ' + id + ', \'' + val + '\', \'' + **this.value** + '\')" type=' + type + ' name=' + id + ' value="' + val.replace(',',' ').replace(',',' ').replace('.',',') + '">'); // replace 12,350.00 to 12350,00
el.attr('onclick', '');
}
function make_el(el, tag_name, id, old_value, **new_value**) {
var el = $(el);
alert(old_value);
alert(new_value); // undefined, how I can give current input value to function when I click outside the input?
}
</script>
Thanks.
I believe this is what you want: jsFiddle example
You can obtain the new value directly from the input element, as follows:
function make_field(el, type, id, val) {
var el = $(el);
el.html('<input onblur="update_db_row(); make_el(this, \'span\', ' + id + ', \'' + val + '\')" type=' + type + ' name=' + id + ' value="' + val.replace(',', ' ').replace(',', ' ').replace('.', ',') + '">'); // replace 12,350.00 to 12350,00
el.attr('onclick', '');
}
function make_el(el, tag_name, id, old_value) {
var el = $(el);
// Get the new value directly from the input.
var new_value = el.val();
// Set the new value on the span and remove the input box.
el.parent().html(new_value);
el.remove();
}
function update_db_row() {}

Categories

Resources